Rebuilt on top of REGL.

This commit is contained in:
Rezmason
2020-01-19 16:03:53 -08:00
parent 09677e5aa4
commit a760d6854a
22 changed files with 10869 additions and 49444 deletions

View File

@@ -1,94 +0,0 @@
/**
* @author rezmason
*/
const easeInOutQuad = input => {
input = Math.max(0, Math.min(1, input));
if (input < 0.5) {
return 2 * input * input;
}
input -= 1;
return 1 - 2 * input * input;
}
const ARRAY_SIZE = 2048;
THREE.ColorMapPass = function (entries, ditherMagnitude = 1, graininess = 100) {
const colors = Array(ARRAY_SIZE).fill().map(_ => new THREE.Vector3(0, 0, 0));
const sortedEntries = entries.slice().sort((e1, e2) => e1.at - e2.at).map(entry => ({
color: new THREE.Vector3(entry.r, entry.g, entry.b),
arrayIndex: Math.floor(Math.max(Math.min(1, entry.at), 0) * (ARRAY_SIZE - 1))
}));
sortedEntries.unshift({color:sortedEntries[0].color, arrayIndex:0});
sortedEntries.push({color:sortedEntries[sortedEntries.length - 1].color, arrayIndex:ARRAY_SIZE - 1});
sortedEntries.forEach((entry, index) => {
colors[entry.arrayIndex].copy(entry.color);
if (index + 1 < sortedEntries.length) {
const nextEntry = sortedEntries[index + 1];
const diff = nextEntry.arrayIndex - entry.arrayIndex;
for (let i = 0; i < diff; i++) {
colors[entry.arrayIndex + i].lerpVectors(entry.color, nextEntry.color, i / diff);
}
}
});
const values = new Uint8Array([].concat(...colors.map(color => color.toArray().map(component => Math.floor(component * 255)))));
this.dataTexture = new THREE.DataTexture(
values,
values.length / 3,
1,
THREE.RGBFormat,
THREE.UnsignedByteType,
THREE.UVMapping);
this.dataTexture.magFilter = THREE.LinearFilter;
this.dataTexture.needsUpdate = true;
this.graininess = graininess;
this.shader = {
uniforms: {
tDiffuse: { value: null },
tColorData: { value: this.dataTexture },
ditherMagnitude: { value: ditherMagnitude },
tTime: { value: 0 }
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4( position, 1.0 );
}
`,
fragmentShader: `
#define PI 3.14159265359
uniform sampler2D tDiffuse;
uniform sampler2D tColorData;
uniform float ditherMagnitude;
uniform float tTime;
varying vec2 vUv;
highp float rand( const in vec2 uv, const in float t ) {
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
return fract(sin(sn) * c + t);
}
void main() {
gl_FragColor = texture2D( tColorData, vec2( texture2D( tDiffuse, vUv ).r - rand( gl_FragCoord.xy, tTime ) * ditherMagnitude, 0.0 ) );
}
`
};
THREE.ShaderPass.call(this, this.shader);
};
THREE.ColorMapPass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), {
constructor: THREE.ColorMapPass,
render: function() {
this.uniforms[ "tColorData" ].value = this.dataTexture;
this.uniforms[ "tTime" ].value = (Date.now() % this.graininess) / this.graininess;
THREE.ShaderPass.prototype.render.call(this, ...arguments);
}
});

View File

@@ -1,46 +0,0 @@
/**
* @author alteredq / http://alteredqualia.com/
*
* Full-screen textured quad shader
*/
THREE.CopyShader = {
uniforms: {
"tDiffuse": { value: null },
"opacity": { value: 1.0 }
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform float opacity;",
"uniform sampler2D tDiffuse;",
"varying vec2 vUv;",
"void main() {",
"vec4 texel = texture2D( tDiffuse, vUv );",
"gl_FragColor = opacity * texel;",
"}"
].join( "\n" )
};

View File

@@ -1,189 +0,0 @@
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.EffectComposer = function ( renderer, renderTarget ) {
this.renderer = renderer;
if ( renderTarget === undefined ) {
var parameters = {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
format: THREE.RGBAFormat,
stencilBuffer: false
};
var size = renderer.getDrawingBufferSize();
renderTarget = new THREE.WebGLRenderTarget( size.width, size.height, parameters );
renderTarget.texture.name = 'EffectComposer.rt1';
}
this.renderTarget1 = renderTarget;
this.renderTarget2 = renderTarget.clone();
this.renderTarget2.texture.name = 'EffectComposer.rt2';
this.writeBuffer = this.renderTarget1;
this.readBuffer = this.renderTarget2;
this.passes = [];
// dependencies
if ( THREE.CopyShader === undefined ) {
console.error( 'THREE.EffectComposer relies on THREE.CopyShader' );
}
if ( THREE.ShaderPass === undefined ) {
console.error( 'THREE.EffectComposer relies on THREE.ShaderPass' );
}
this.copyPass = new THREE.ShaderPass( THREE.CopyShader );
};
Object.assign( THREE.EffectComposer.prototype, {
swapBuffers: function () {
var tmp = this.readBuffer;
this.readBuffer = this.writeBuffer;
this.writeBuffer = tmp;
},
addPass: function ( pass ) {
this.passes.push( pass );
var size = this.renderer.getDrawingBufferSize();
pass.setSize( size.width, size.height );
},
insertPass: function ( pass, index ) {
this.passes.splice( index, 0, pass );
},
render: function ( delta ) {
var maskActive = false;
var pass, i, il = this.passes.length;
for ( i = 0; i < il; i ++ ) {
pass = this.passes[ i ];
if ( pass.enabled === false ) continue;
pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive );
if ( pass.needsSwap ) {
if ( maskActive ) {
var context = this.renderer.context;
context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta );
context.stencilFunc( context.EQUAL, 1, 0xffffffff );
}
this.swapBuffers();
}
if ( THREE.MaskPass !== undefined ) {
if ( pass instanceof THREE.MaskPass ) {
maskActive = true;
} else if ( pass instanceof THREE.ClearMaskPass ) {
maskActive = false;
}
}
}
},
reset: function ( renderTarget ) {
if ( renderTarget === undefined ) {
var size = this.renderer.getDrawingBufferSize();
renderTarget = this.renderTarget1.clone();
renderTarget.setSize( size.width, size.height );
}
this.renderTarget1.dispose();
this.renderTarget2.dispose();
this.renderTarget1 = renderTarget;
this.renderTarget2 = renderTarget.clone();
this.writeBuffer = this.renderTarget1;
this.readBuffer = this.renderTarget2;
},
setSize: function ( width, height ) {
this.renderTarget1.setSize( width, height );
this.renderTarget2.setSize( width, height );
for ( var i = 0; i < this.passes.length; i ++ ) {
this.passes[ i ].setSize( width, height );
}
}
} );
THREE.Pass = function () {
// if set to true, the pass is processed by the composer
this.enabled = true;
// if set to true, the pass indicates to swap read and write buffer after rendering
this.needsSwap = true;
// if set to true, the pass clears its buffer before rendering
this.clear = false;
// if set to true, the result of the pass is rendered to screen
this.renderToScreen = false;
};
Object.assign( THREE.Pass.prototype, {
setSize: function ( width, height ) {},
render: function ( renderer, writeBuffer, readBuffer, delta, maskActive ) {
console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
}
} );

View File

@@ -1,368 +0,0 @@
/**
* @author yomboprime https://github.com/yomboprime
*
* GPUComputationRenderer, based on SimulationRenderer by zz85
*
* The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
* for each compute element (texel)
*
* Each variable has a fragment shader that defines the computation made to obtain the variable in question.
* You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader
* (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency.
*
* The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used
* as inputs to render the textures of the next frame.
*
* The render targets of the variables can be used as input textures for your visualization shaders.
*
* Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers.
* a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity...
*
* The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example:
* #DEFINE resolution vec2( 1024.0, 1024.0 )
*
* -------------
*
* Basic use:
*
* // Initialization...
*
* // Create computation renderer
* var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer );
*
* // Create initial state float textures
* var pos0 = gpuCompute.createTexture();
* var vel0 = gpuCompute.createTexture();
* // and fill in here the texture data...
*
* // Add texture variables
* var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 );
* var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 );
*
* // Add variable dependencies
* gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] );
* gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] );
*
* // Add custom uniforms
* velVar.material.uniforms.time = { value: 0.0 };
*
* // Check for completeness
* var error = gpuCompute.init();
* if ( error !== null ) {
* console.error( error );
* }
*
*
* // In each frame...
*
* // Compute!
* gpuCompute.compute();
*
* // Update texture uniforms in your visualization materials with the gpu renderer output
* myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture;
*
* // Do your rendering
* renderer.render( myScene, myCamera );
*
* -------------
*
* Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures)
* Note that the shaders can have multiple input textures.
*
* var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } );
* var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } );
*
* var inputTexture = gpuCompute.createTexture();
*
* // Fill in here inputTexture...
*
* myFilter1.uniforms.theTexture.value = inputTexture;
*
* var myRenderTarget = gpuCompute.createRenderTarget();
* myFilter2.uniforms.theTexture.value = myRenderTarget.texture;
*
* var outputRenderTarget = gpuCompute.createRenderTarget();
*
* // Now use the output texture where you want:
* myMaterial.uniforms.map.value = outputRenderTarget.texture;
*
* // And compute each frame, before rendering to screen:
* gpuCompute.doRenderTarget( myFilter1, myRenderTarget );
* gpuCompute.doRenderTarget( myFilter2, outputRenderTarget );
*
*
*
* @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
* @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
* @param {WebGLRenderer} renderer The renderer
*/
function GPUComputationRenderer( sizeX, sizeY, renderer ) {
this.variables = [];
this.currentTextureIndex = 0;
var scene = new THREE.Scene();
var camera = new THREE.Camera();
camera.position.z = 1;
var passThruUniforms = {
texture: { value: null }
};
var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );
var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), passThruShader );
scene.add( mesh );
this.addVariable = function( variableName, computeFragmentShader, initialValueTexture ) {
var material = this.createShaderMaterial( computeFragmentShader );
var variable = {
name: variableName,
initialValueTexture: initialValueTexture,
material: material,
dependencies: null,
renderTargets: [],
wrapS: null,
wrapT: null,
minFilter: THREE.NearestFilter,
magFilter: THREE.NearestFilter
};
this.variables.push( variable );
return variable;
};
this.setVariableDependencies = function( variable, dependencies ) {
variable.dependencies = dependencies;
};
this.init = function() {
if ( ! renderer.extensions.get( "OES_texture_float" ) ) {
return "No OES_texture_float support for float textures.";
}
if ( renderer.capabilities.maxVertexTextures === 0 ) {
return "No support for vertex shader textures.";
}
for ( var i = 0; i < this.variables.length; i++ ) {
var variable = this.variables[ i ];
// Creates rendertargets and initialize them with input texture
variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );
// Adds dependencies uniforms to the ShaderMaterial
var material = variable.material;
var uniforms = material.uniforms;
if ( variable.dependencies !== null ) {
for ( var d = 0; d < variable.dependencies.length; d++ ) {
var depVar = variable.dependencies[ d ];
if ( depVar.name !== variable.name ) {
// Checks if variable exists
var found = false;
for ( var j = 0; j < this.variables.length; j++ ) {
if ( depVar.name === this.variables[ j ].name ) {
found = true;
break;
}
}
if ( ! found ) {
return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
}
}
uniforms[ depVar.name ] = { value: null };
material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
}
}
}
this.currentTextureIndex = 0;
return null;
};
this.compute = function() {
var currentTextureIndex = this.currentTextureIndex;
var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
for ( var i = 0, il = this.variables.length; i < il; i++ ) {
var variable = this.variables[ i ];
// Sets texture dependencies uniforms
if ( variable.dependencies !== null ) {
var uniforms = variable.material.uniforms;
for ( var d = 0, dl = variable.dependencies.length; d < dl; d++ ) {
var depVar = variable.dependencies[ d ];
uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;
}
}
// Performs the computation for this variable
this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );
}
this.currentTextureIndex = nextTextureIndex;
};
this.getCurrentRenderTarget = function( variable ) {
return variable.renderTargets[ this.currentTextureIndex ];
};
this.getAlternateRenderTarget = function( variable ) {
return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
};
function addResolutionDefine( materialShader ) {
materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )";
}
this.addResolutionDefine = addResolutionDefine;
// The following functions can be used to compute things manually
function createShaderMaterial( computeFragmentShader, uniforms ) {
uniforms = uniforms || {};
var material = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: getPassThroughVertexShader(),
fragmentShader: computeFragmentShader
} );
addResolutionDefine( material );
return material;
}
this.createShaderMaterial = createShaderMaterial;
this.createRenderTarget = function( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
sizeXTexture = sizeXTexture || sizeX;
sizeYTexture = sizeYTexture || sizeY;
wrapS = wrapS || THREE.ClampToEdgeWrapping;
wrapT = wrapT || THREE.ClampToEdgeWrapping;
minFilter = minFilter || THREE.NearestFilter;
magFilter = magFilter || THREE.NearestFilter;
var renderTarget = new THREE.WebGLRenderTarget( sizeXTexture, sizeYTexture, {
wrapS: wrapS,
wrapT: wrapT,
minFilter: minFilter,
magFilter: magFilter,
format: THREE.RGBAFormat,
type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? THREE.HalfFloatType : THREE.FloatType,
stencilBuffer: false,
depthBuffer: false
} );
return renderTarget;
};
this.createTexture = function() {
var a = new Float32Array( sizeX * sizeY * 4 );
var texture = new THREE.DataTexture( a, sizeX, sizeY, THREE.RGBAFormat, THREE.FloatType );
texture.needsUpdate = true;
return texture;
};
this.renderTexture = function( input, output ) {
// Takes a texture, and render out in rendertarget
// input = Texture
// output = RenderTarget
passThruUniforms.texture.value = input;
this.doRenderTarget( passThruShader, output);
passThruUniforms.texture.value = null;
};
this.doRenderTarget = function( material, output ) {
mesh.material = material;
renderer.render( scene, camera, output );
mesh.material = passThruShader;
};
// Shaders
function getPassThroughVertexShader() {
return "void main() {\n" +
"\n" +
" gl_Position = vec4( position, 1.0 );\n" +
"\n" +
"}\n";
}
function getPassThroughFragmentShader() {
return "uniform sampler2D texture;\n" +
"\n" +
"void main() {\n" +
"\n" +
" vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
"\n" +
" gl_FragColor = texture2D( texture, uv );\n" +
"\n" +
"}\n";
}
}

View File

@@ -1,64 +0,0 @@
/**
* @author rezmason
*/
THREE.HorizontalColorationPass = function (colors, ditherMagnitude = 1) {
const values = new Uint8Array([].concat(...colors.map(color => color.toArray().map(component => Math.floor(component * 255)))));
this.dataTexture = new THREE.DataTexture(
values,
values.length / 3,
1,
THREE.RGBFormat,
THREE.UnsignedByteType,
THREE.UVMapping);
this.dataTexture.magFilter = THREE.LinearFilter;
this.dataTexture.needsUpdate = true;
this.shader = {
uniforms: {
tDiffuse: { value: null },
tColorData: { value: this.dataTexture },
ditherMagnitude: { value: ditherMagnitude },
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4( position, 1.0 );
}
`,
fragmentShader: `
#define PI 3.14159265359
uniform sampler2D tDiffuse;
uniform sampler2D tColorData;
uniform float ditherMagnitude;
varying vec2 vUv;
highp float rand( const in vec2 uv ) {
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
return fract(sin(sn) * c);
}
void main() {
float value = texture2D(tDiffuse, vUv).r;
vec3 value2 = texture2D(tColorData, vUv).rgb - rand( gl_FragCoord.xy ) * ditherMagnitude;
gl_FragColor = vec4(value2 * value, 1.0);
}
`
};
THREE.ShaderPass.call(this, this.shader);
};
THREE.HorizontalColorationPass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), {
constructor: THREE.HorizontalColorationPass,
render: function() {
this.uniforms[ "tColorData" ].value = this.dataTexture;
THREE.ShaderPass.prototype.render.call(this, ...arguments);
}
});

View File

@@ -1,41 +0,0 @@
/**
* @author rezmason
*/
THREE.ImageOverlayPass = function (texture) {
this.texture = texture;
this.shader = {
uniforms: {
tDiffuse: { value: null },
map: { value: this.texture },
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4( position, 1.0 );
}
`,
fragmentShader: `
uniform sampler2D tDiffuse;
uniform sampler2D map;
varying vec2 vUv;
void main() {
gl_FragColor = vec4(texture2D(map, vUv).rgb * (pow(texture2D(tDiffuse, vUv).r, 1.5) * 0.995 + 0.005), 1.0);
}
`
};
THREE.ShaderPass.call(this, this.shader);
};
THREE.ImageOverlayPass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), {
constructor: THREE.ImageOverlayPass,
render: function() {
this.uniforms[ "map" ].value = this.texture;
THREE.ShaderPass.prototype.render.call(this, ...arguments);
}
});

View File

@@ -1,64 +0,0 @@
/**
* @author bhouston / http://clara.io/
*
* Luminosity
* http://en.wikipedia.org/wiki/Luminosity
*/
THREE.LuminosityHighPassShader = {
shaderID: "luminosityHighPass",
uniforms: {
"tDiffuse": { type: "t", value: null },
"luminosityThreshold": { type: "f", value: 1.0 },
"smoothWidth": { type: "f", value: 1.0 },
"defaultColor": { type: "c", value: new THREE.Color( 0x000000 ) },
"defaultOpacity": { type: "f", value: 0.0 }
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform sampler2D tDiffuse;",
"uniform vec3 defaultColor;",
"uniform float defaultOpacity;",
"uniform float luminosityThreshold;",
"uniform float smoothWidth;",
"varying vec2 vUv;",
"void main() {",
"vec4 texel = texture2D( tDiffuse, vUv );",
"vec3 luma = vec3( 0.299, 0.587, 0.114 );",
"float v = dot( texel.xyz, luma );",
"vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );",
"float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );",
"gl_FragColor = mix( outputColor, texel, alpha );",
"}"
].join("\n")
};

View File

@@ -1,397 +0,0 @@
const makeMatrixRenderer = (renderer, {
fontTexture,
numColumns,
animationSpeed, fallSpeed, cycleSpeed,
glyphSequenceLength,
numFontColumns,
hasThunder,
hasSun,
isPolar,
slant,
glyphHeightToWidth,
glyphEdgeCrop,
cursorEffectThreshold,
showComputationTexture,
raindropLength,
cycleStyle,
rippleType,
rippleScale,
rippleSpeed,
rippleThickness,
brightnessMultiplier,
brightnessOffset,
}) => {
const matrixRenderer = {};
const camera = new THREE.OrthographicCamera( -0.5, 0.5, 0.5, -0.5, 0.0001, 10000 );
const scene = new THREE.Scene();
const gpuCompute = new GPUComputationRenderer( numColumns, numColumns, renderer );
const glyphValue = gpuCompute.createTexture();
const pixels = glyphValue.image.data;
const scramble = i => Math.sin(i) * 0.5 + 0.5;
for (let i = 0; i < numColumns * numColumns; i++) {
pixels[i * 4 + 0] = 0;
pixels[i * 4 + 1] = showComputationTexture ? 0.5 : scramble(i);
pixels[i * 4 + 2] = 0;
pixels[i * 4 + 3] = 0;
}
const glyphVariable = gpuCompute.addVariable(
"glyph",
`
precision highp float;
#define PI 3.14159265359
#define SQRT_2 1.4142135623730951
#define SQRT_5 2.23606797749979
uniform bool hasSun;
uniform bool hasThunder;
uniform bool showComputationTexture;
uniform float brightnessChangeBias;
uniform float brightnessMultiplier;
uniform float brightnessOffset;
uniform float cursorEffectThreshold;
uniform float time;
uniform float animationSpeed;
uniform float cycleSpeed;
uniform float deltaTime;
uniform float fallSpeed;
uniform float raindropLength;
uniform float glyphHeightToWidth;
uniform float glyphSequenceLength;
uniform float numFontColumns;
uniform int cycleStyle;
uniform float rippleScale;
uniform float rippleSpeed;
uniform float rippleThickness;
uniform int rippleType;
highp float rand( const in vec2 uv ) {
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
return fract(sin(sn) * c);
}
float max2(vec2 v) {
return max(v.x, v.y);
}
vec2 rand2(vec2 p) {
return fract(vec2(sin(p.x * 591.32 + p.y * 154.077), cos(p.x * 391.32 + p.y * 49.077)));
}
highp float blast( const in float x, const in float power ) {
return pow(pow(pow(x, power), power), power);
}
float ripple(vec2 uv, float simTime) {
if (rippleType == -1) {
return 0.;
}
float rippleTime = (simTime + 0.2 * sin(simTime * 2.0)) * rippleSpeed + 1.;
vec2 offset = rand2(vec2(floor(rippleTime), 0.)) - 0.5;
vec2 ripplePos = uv + offset;
float rippleDistance;
if (rippleType == 0) {
rippleDistance = max2(abs(ripplePos) * vec2(1.0, glyphHeightToWidth));
} else if (rippleType == 1) {
rippleDistance = length(ripplePos);
}
float rippleValue = fract(rippleTime) * rippleScale - rippleDistance;
if (rippleValue > 0. && rippleValue < rippleThickness) {
return 0.75;
} else {
return 0.;
}
}
void main() {
vec2 cellSize = 1.0 / resolution.xy;
vec2 uv = (gl_FragCoord.xy) * cellSize;
float columnTimeOffset = rand(vec2(gl_FragCoord.x, 0.0));
float columnSpeedOffset = rand(vec2(gl_FragCoord.x + 0.1, 0.0));
vec4 data = texture2D( glyph, uv );
float brightness = data.r;
float glyphCycle = data.g;
float simTime = time * 0.0005 * animationSpeed;
float columnTime = (columnTimeOffset * 1000.0 + simTime * fallSpeed) * (0.5 + columnSpeedOffset * 0.5) + (sin(simTime * fallSpeed * 2.0 * columnSpeedOffset) * 0.2);
float glyphTime = (gl_FragCoord.y * 0.01 + columnTime) / raindropLength;
float value = 1.0 - fract((glyphTime + 0.3 * sin(SQRT_2 * glyphTime) + 0.2 * sin(SQRT_5 * glyphTime)));
float newBrightness = 3.0 * log(value * 1.25);
if (hasSun) {
newBrightness = pow(fract(newBrightness * 0.5), 3.0) * uv.y * 2.0;
}
if (hasThunder) {
vec2 distVec = (gl_FragCoord.xy / resolution.xy - vec2(0.5, 1.0)) * vec2(1.0, 2.0);
float thunder = (blast(sin(SQRT_5 * simTime * 2.0), 10.0) + blast(sin(SQRT_2 * simTime * 2.0), 10.0));
thunder *= 30.0 * (1.0 - 1.0 * length(distVec));
newBrightness *= max(0.0, thunder) * 1.0 + 0.7;
if (newBrightness > brightness) {
brightness = newBrightness;
} else {
brightness = mix(brightness, newBrightness, brightnessChangeBias * 0.1);
}
} else {
brightness = mix(brightness, newBrightness, brightnessChangeBias);
}
float glyphCycleSpeed = 0.0;
if (cycleStyle == 1) {
glyphCycleSpeed = fract((glyphTime + 0.7 * sin(SQRT_2 * glyphTime) + 1.1 * sin(SQRT_5 * glyphTime))) * 0.75;
} else if (cycleStyle == 0) {
if (brightness > 0.0) glyphCycleSpeed = pow(1.0 - brightness, 4.0);
}
glyphCycle = fract(glyphCycle + deltaTime * cycleSpeed * 0.2 * glyphCycleSpeed);
float symbol = floor(glyphSequenceLength * glyphCycle);
float symbolX = mod(symbol, numFontColumns);
float symbolY = ((numFontColumns - 1.0) - (symbol - symbolX) / numFontColumns);
float effect = 0.;
effect += ripple(gl_FragCoord.xy / resolution.xy * 2.0 - 1.0, simTime);
if (brightness >= cursorEffectThreshold) {
effect = 1.0;
}
if (brightness > -1.) {
brightness = brightness * brightnessMultiplier + brightnessOffset;
}
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
gl_FragColor.r = brightness;
gl_FragColor.g = glyphCycle;
if (showComputationTexture) {
// Better use of the blue channel, for show and tell
gl_FragColor.b = min(1.0, glyphCycleSpeed);
gl_FragColor.a = 1.0;
} else {
gl_FragColor.b = symbolY * numFontColumns + symbolX;
gl_FragColor.a = effect;
}
}
`
,
glyphValue
);
gpuCompute.setVariableDependencies( glyphVariable, [ glyphVariable ] );
const brightnessChangeBias = (animationSpeed * fallSpeed) == 0 ? 1 : Math.min(1, Math.abs(animationSpeed * fallSpeed));
let cycleStyleInt;
switch (cycleStyle) {
case "cycleFasterWhenDimmed":
cycleStyleInt = 0;
break;
case "cycleRandomly":
default:
cycleStyleInt = 1;
break;
}
let rippleTypeInt;
switch (rippleType) {
case "box":
rippleTypeInt = 0;
break;
case "circle":
rippleTypeInt = 1;
break;
default:
rippleTypeInt = -1;
}
Object.assign(glyphVariable.material.uniforms, {
time: { type: "f", value: 0 },
deltaTime: { type: "f", value: 0.01 },
animationSpeed: { type: "f", value: animationSpeed },
fallSpeed: { type: "f", value: fallSpeed },
cycleSpeed: {type: "f", value: cycleSpeed },
glyphSequenceLength: { type: "f", value: glyphSequenceLength },
numFontColumns: {type: "f", value: numFontColumns },
raindropLength: {type: "f", value: raindropLength },
brightnessChangeBias: { type: "f", value: brightnessChangeBias },
rippleThickness: { type: "f", value: rippleThickness},
rippleScale: { type: "f", value: rippleScale},
rippleSpeed: { type: "f", value: rippleSpeed},
cursorEffectThreshold: { type: "f", value: cursorEffectThreshold},
brightnessMultiplier: { type: "f", value: brightnessMultiplier},
brightnessOffset: { type: "f", value: brightnessOffset},
glyphHeightToWidth: {type: "f", value: glyphHeightToWidth},
hasSun: { type: "b", value: hasSun },
hasThunder: { type: "b", value: hasThunder },
rippleType: { type: "i", value: rippleTypeInt },
showComputationTexture: { type: "b", value: showComputationTexture },
cycleStyle: { type: "i", value: cycleStyleInt },
});
const error = gpuCompute.init();
if ( error !== null ) {
console.error( error );
}
const glyphRTT = gpuCompute.getCurrentRenderTarget( glyphVariable ).texture;
const mesh = new THREE.Mesh(
new THREE.PlaneBufferGeometry(),
new THREE.RawShaderMaterial({
uniforms: {
glyphs: { type: "t", value: glyphRTT },
msdf: { type: "t", value: fontTexture },
numColumns: {type: "f", value: numColumns},
numFontColumns: {type: "f", value: numFontColumns},
resolution: {type: "v2", value: new THREE.Vector2() },
slant: {type: "v2", value: new THREE.Vector2(Math.cos(slant), Math.sin(slant)) },
glyphHeightToWidth: {type: "f", value: glyphHeightToWidth},
glyphEdgeCrop: {type: "f", value: glyphEdgeCrop},
isPolar: { type: "b", value: isPolar },
showComputationTexture: { type: "b", value: showComputationTexture },
},
vertexShader: `
attribute vec2 uv;
attribute vec3 position;
uniform vec2 resolution;
varying vec2 vUV;
void main() {
vUV = uv;
gl_Position = vec4( resolution * position.xy, 0.0, 1.0 );
}
`,
fragmentShader: `
#define PI 3.14159265359
#ifdef GL_OES_standard_derivatives
#extension GL_OES_standard_derivatives: enable
#endif
precision lowp float;
uniform sampler2D msdf;
uniform sampler2D glyphs;
uniform float numColumns;
uniform float numFontColumns;
uniform vec2 slant;
uniform float glyphHeightToWidth;
uniform float glyphEdgeCrop;
uniform bool isPolar;
uniform bool showComputationTexture;
varying vec2 vUV;
float median(float r, float g, float b) {
return max(min(r, g), min(max(r, g), b));
}
void main() {
vec2 uv = vUV;
if (isPolar) {
uv -= 0.5;
uv *= 0.5;
uv.y -= 0.5;
float radius = length(uv);
float angle = atan(uv.y, uv.x) / (2. * PI) + 0.5;
uv = vec2(angle * 4. - 0.5, 1.25 - radius * 1.5);
} else {
uv = vec2(
(uv.x - 0.5) * slant.x + (uv.y - 0.5) * slant.y,
(uv.y - 0.5) * slant.x - (uv.x - 0.5) * slant.y
) * 0.75 + 0.5;
}
uv.y /= glyphHeightToWidth;
vec4 glyph = texture2D(glyphs, uv);
if (showComputationTexture) {
gl_FragColor = glyph;
return;
}
// Unpack the values from the font texture
float brightness = glyph.r;
float effect = glyph.a;
brightness = max(effect, brightness);
float symbolIndex = glyph.b;
vec2 symbolUV = vec2(mod(symbolIndex, numFontColumns), floor(symbolIndex / numFontColumns));
vec2 glyphUV = fract(uv * numColumns);
glyphUV -= 0.5;
glyphUV *= clamp(1.0 - glyphEdgeCrop, 0.0, 1.0);
glyphUV += 0.5;
vec4 sample = texture2D(msdf, (glyphUV + symbolUV) / numFontColumns);
// The rest is straight up MSDF
float sigDist = median(sample.r, sample.g, sample.b) - 0.5;
float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);
gl_FragColor = vec4(vec3(brightness * alpha), 1.0);
}
`
})
);
mesh.frustumCulled = false;
scene.add( mesh );
let start = NaN;
let last = NaN;
matrixRenderer.pass = new THREE.RenderPass( scene, camera );
matrixRenderer.render = () => {
if (isNaN(start)) {
start = Date.now();
last = 0;
}
const now = Date.now() - start;
if (now - last > 50) {
last = now;
return;
}
const deltaTime = ((now - last > 1000) ? 0 : now - last) / 1000 * animationSpeed;
last = now;
glyphVariable.material.uniforms.time.value = now;
glyphVariable.material.uniforms.deltaTime.value = deltaTime;
gpuCompute.compute();
renderer.render( scene, camera );
};
matrixRenderer.resize = (width, height) => {
if (width > height) {
mesh.material.uniforms.resolution.value.set(2, 2 * width / height);
} else {
mesh.material.uniforms.resolution.value.set(2 * height / width, 2);
}
};
return matrixRenderer;
};

View File

@@ -1,63 +0,0 @@
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.RenderPass = function ( scene, camera, overrideMaterial, clearColor, clearAlpha ) {
THREE.Pass.call( this );
this.scene = scene;
this.camera = camera;
this.overrideMaterial = overrideMaterial;
this.clearColor = clearColor;
this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
this.clear = true;
this.clearDepth = false;
this.needsSwap = false;
};
THREE.RenderPass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), {
constructor: THREE.RenderPass,
render: function ( renderer, writeBuffer, readBuffer, delta, maskActive ) {
var oldAutoClear = renderer.autoClear;
renderer.autoClear = false;
this.scene.overrideMaterial = this.overrideMaterial;
var oldClearColor, oldClearAlpha;
if ( this.clearColor ) {
oldClearColor = renderer.getClearColor().getHex();
oldClearAlpha = renderer.getClearAlpha();
renderer.setClearColor( this.clearColor, this.clearAlpha );
}
if ( this.clearDepth ) {
renderer.clearDepth();
}
renderer.render( this.scene, this.camera, this.renderToScreen ? null : readBuffer, this.clear );
if ( this.clearColor ) {
renderer.setClearColor( oldClearColor, oldClearAlpha );
}
this.scene.overrideMaterial = null;
renderer.autoClear = oldAutoClear;
}
} );

View File

@@ -1,67 +0,0 @@
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ShaderPass = function ( shader, textureID ) {
THREE.Pass.call( this );
this.textureID = ( textureID !== undefined ) ? textureID : "tDiffuse";
if ( shader instanceof THREE.ShaderMaterial ) {
this.uniforms = shader.uniforms;
this.material = shader;
} else if ( shader ) {
this.uniforms = THREE.UniformsUtils.clone( shader.uniforms );
this.material = new THREE.ShaderMaterial( {
defines: Object.assign( {}, shader.defines ),
uniforms: this.uniforms,
vertexShader: shader.vertexShader,
fragmentShader: shader.fragmentShader
} );
}
this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
this.scene = new THREE.Scene();
this.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), null );
this.quad.frustumCulled = false; // Avoid getting clipped
this.scene.add( this.quad );
};
THREE.ShaderPass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), {
constructor: THREE.ShaderPass,
render: function( renderer, writeBuffer, readBuffer, delta, maskActive ) {
if ( this.uniforms[ this.textureID ] ) {
this.uniforms[ this.textureID ].value = readBuffer.texture;
}
this.quad.material = this.material;
if ( this.renderToScreen ) {
renderer.render( this.scene, this.camera );
} else {
renderer.render( this.scene, this.camera, writeBuffer, this.clear );
}
}
} );

View File

@@ -1,384 +0,0 @@
/**
* @author spidersharma / http://eduperiment.com/
*
* Inspired from Unreal Engine
* https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/
*/
THREE.UnrealBloomPass = function ( resolution, strength, radius, threshold ) {
THREE.Pass.call( this );
this.strength = ( strength !== undefined ) ? strength : 1;
this.radius = radius;
this.threshold = threshold;
this.resolution = ( resolution !== undefined ) ? new THREE.Vector2( resolution.x, resolution.y ) : new THREE.Vector2( 256, 256 );
// create color only once here, reuse it later inside the render function
this.clearColor = new THREE.Color( 0, 0, 0 );
// render targets
var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
this.renderTargetsHorizontal = [];
this.renderTargetsVertical = [];
this.nMips = 5;
var resx = Math.round( this.resolution.x / 2 );
var resy = Math.round( this.resolution.y / 2 );
this.renderTargetBright = new THREE.WebGLRenderTarget( resx, resy, pars );
this.renderTargetBright.texture.name = "UnrealBloomPass.bright";
this.renderTargetBright.texture.generateMipmaps = false;
for ( var i = 0; i < this.nMips; i ++ ) {
var renderTarget = new THREE.WebGLRenderTarget( resx, resy, pars );
renderTarget.texture.name = "UnrealBloomPass.h" + i;
renderTarget.texture.generateMipmaps = false;
this.renderTargetsHorizontal.push( renderTarget );
var renderTarget = new THREE.WebGLRenderTarget( resx, resy, pars );
renderTarget.texture.name = "UnrealBloomPass.v" + i;
renderTarget.texture.generateMipmaps = false;
this.renderTargetsVertical.push( renderTarget );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
// luminosity high pass material
if ( THREE.LuminosityHighPassShader === undefined )
console.error( "THREE.UnrealBloomPass relies on THREE.LuminosityHighPassShader" );
var highPassShader = THREE.LuminosityHighPassShader;
this.highPassUniforms = THREE.UniformsUtils.clone( highPassShader.uniforms );
this.highPassUniforms[ "luminosityThreshold" ].value = threshold;
this.highPassUniforms[ "smoothWidth" ].value = 0.01;
this.materialHighPassFilter = new THREE.ShaderMaterial( {
uniforms: this.highPassUniforms,
vertexShader: highPassShader.vertexShader,
fragmentShader: highPassShader.fragmentShader,
defines: {}
} );
// Gaussian Blur Materials
this.separableBlurMaterials = [];
var kernelSizeArray = [ 3, 5, 7, 9, 11 ];
var resx = Math.round( this.resolution.x / 2 );
var resy = Math.round( this.resolution.y / 2 );
for ( var i = 0; i < this.nMips; i ++ ) {
this.separableBlurMaterials.push( this.getSeperableBlurMaterial( kernelSizeArray[ i ] ) );
this.separableBlurMaterials[ i ].uniforms[ "texSize" ].value = new THREE.Vector2( resx, resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
// Composite material
this.compositeMaterial = this.getCompositeMaterial( this.nMips );
this.compositeMaterial.uniforms[ "blurTexture1" ].value = this.renderTargetsVertical[ 0 ].texture;
this.compositeMaterial.uniforms[ "blurTexture2" ].value = this.renderTargetsVertical[ 1 ].texture;
this.compositeMaterial.uniforms[ "blurTexture3" ].value = this.renderTargetsVertical[ 2 ].texture;
this.compositeMaterial.uniforms[ "blurTexture4" ].value = this.renderTargetsVertical[ 3 ].texture;
this.compositeMaterial.uniforms[ "blurTexture5" ].value = this.renderTargetsVertical[ 4 ].texture;
this.compositeMaterial.uniforms[ "bloomStrength" ].value = strength;
this.compositeMaterial.uniforms[ "bloomRadius" ].value = 0.1;
this.compositeMaterial.needsUpdate = true;
var bloomFactors = [ 1.0, 0.8, 0.6, 0.4, 0.2 ];
this.compositeMaterial.uniforms[ "bloomFactors" ].value = bloomFactors;
this.bloomTintColors = [ new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 1, 1, 1 ),
new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 1, 1, 1 ) ];
this.compositeMaterial.uniforms[ "bloomTintColors" ].value = this.bloomTintColors;
// copy material
if ( THREE.CopyShader === undefined ) {
console.error( "THREE.BloomPass relies on THREE.CopyShader" );
}
var copyShader = THREE.CopyShader;
this.copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms );
this.copyUniforms[ "opacity" ].value = 1.0;
this.materialCopy = new THREE.ShaderMaterial( {
uniforms: this.copyUniforms,
vertexShader: copyShader.vertexShader,
fragmentShader: copyShader.fragmentShader,
blending: THREE.AdditiveBlending,
depthTest: false,
depthWrite: false,
transparent: true
} );
this.enabled = true;
this.needsSwap = false;
this.oldClearColor = new THREE.Color();
this.oldClearAlpha = 1;
this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
this.scene = new THREE.Scene();
this.basic = new THREE.MeshBasicMaterial();
this.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), null );
this.quad.frustumCulled = false; // Avoid getting clipped
this.scene.add( this.quad );
};
THREE.UnrealBloomPass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), {
constructor: THREE.UnrealBloomPass,
dispose: function () {
for ( var i = 0; i < this.renderTargetsHorizontal.length; i ++ ) {
this.renderTargetsHorizontal[ i ].dispose();
}
for ( var i = 0; i < this.renderTargetsVertical.length; i ++ ) {
this.renderTargetsVertical[ i ].dispose();
}
this.renderTargetBright.dispose();
},
setSize: function ( width, height ) {
var resx = Math.round( width / 2 );
var resy = Math.round( height / 2 );
this.renderTargetBright.setSize( resx, resy );
for ( var i = 0; i < this.nMips; i ++ ) {
this.renderTargetsHorizontal[ i ].setSize( resx, resy );
this.renderTargetsVertical[ i ].setSize( resx, resy );
this.separableBlurMaterials[ i ].uniforms[ "texSize" ].value = new THREE.Vector2( resx, resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
},
render: function ( renderer, writeBuffer, readBuffer, delta, maskActive ) {
this.oldClearColor.copy( renderer.getClearColor() );
this.oldClearAlpha = renderer.getClearAlpha();
var oldAutoClear = renderer.autoClear;
renderer.autoClear = false;
renderer.setClearColor( this.clearColor, 0 );
if ( maskActive ) renderer.context.disable( renderer.context.STENCIL_TEST );
// Render input to screen
if ( this.renderToScreen ) {
this.quad.material = this.basic;
this.basic.map = readBuffer.texture;
renderer.render( this.scene, this.camera, undefined, true );
}
// 1. Extract Bright Areas
this.highPassUniforms[ "tDiffuse" ].value = readBuffer.texture;
this.highPassUniforms[ "luminosityThreshold" ].value = this.threshold;
this.quad.material = this.materialHighPassFilter;
renderer.render( this.scene, this.camera, this.renderTargetBright, true );
// 2. Blur All the mips progressively
var inputRenderTarget = this.renderTargetBright;
for ( var i = 0; i < this.nMips; i ++ ) {
this.quad.material = this.separableBlurMaterials[ i ];
this.separableBlurMaterials[ i ].uniforms[ "colorTexture" ].value = inputRenderTarget.texture;
this.separableBlurMaterials[ i ].uniforms[ "direction" ].value = THREE.UnrealBloomPass.BlurDirectionX;
renderer.render( this.scene, this.camera, this.renderTargetsHorizontal[ i ], true );
this.separableBlurMaterials[ i ].uniforms[ "colorTexture" ].value = this.renderTargetsHorizontal[ i ].texture;
this.separableBlurMaterials[ i ].uniforms[ "direction" ].value = THREE.UnrealBloomPass.BlurDirectionY;
renderer.render( this.scene, this.camera, this.renderTargetsVertical[ i ], true );
inputRenderTarget = this.renderTargetsVertical[ i ];
}
// Composite All the mips
this.quad.material = this.compositeMaterial;
this.compositeMaterial.uniforms[ "bloomStrength" ].value = this.strength;
this.compositeMaterial.uniforms[ "bloomRadius" ].value = this.radius;
this.compositeMaterial.uniforms[ "bloomTintColors" ].value = this.bloomTintColors;
renderer.render( this.scene, this.camera, this.renderTargetsHorizontal[ 0 ], true );
// Blend it additively over the input texture
this.quad.material = this.materialCopy;
this.copyUniforms[ "tDiffuse" ].value = this.renderTargetsHorizontal[ 0 ].texture;
if ( maskActive ) renderer.context.enable( renderer.context.STENCIL_TEST );
if ( this.renderToScreen ) {
renderer.render( this.scene, this.camera, undefined, false );
} else {
renderer.render( this.scene, this.camera, readBuffer, false );
}
// Restore renderer settings
renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
renderer.autoClear = oldAutoClear;
},
getSeperableBlurMaterial: function ( kernelRadius ) {
return new THREE.ShaderMaterial( {
defines: {
"KERNEL_RADIUS": kernelRadius,
"SIGMA": kernelRadius
},
uniforms: {
"colorTexture": { value: null },
"texSize": { value: new THREE.Vector2( 0.5, 0.5 ) },
"direction": { value: new THREE.Vector2( 0.5, 0.5 ) }
},
vertexShader:
"varying vec2 vUv;\n\
void main() {\n\
vUv = uv;\n\
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
}",
fragmentShader:
"#include <common>\
varying vec2 vUv;\n\
uniform sampler2D colorTexture;\n\
uniform vec2 texSize;\
uniform vec2 direction;\
\
float gaussianPdf(in float x, in float sigma) {\
return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\
}\
void main() {\n\
vec2 invSize = 1.0 / texSize;\
float fSigma = float(SIGMA);\
float weightSum = gaussianPdf(0.0, fSigma);\
vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\
for( int i = 1; i < KERNEL_RADIUS; i ++ ) {\
float x = float(i);\
float w = gaussianPdf(x, fSigma);\
vec2 uvOffset = direction * invSize * x;\
vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\
vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\
diffuseSum += (sample1 + sample2) * w;\
weightSum += 2.0 * w;\
}\
gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\n\
}"
} );
},
getCompositeMaterial: function ( nMips ) {
return new THREE.ShaderMaterial( {
defines: {
"NUM_MIPS": nMips
},
uniforms: {
"blurTexture1": { value: null },
"blurTexture2": { value: null },
"blurTexture3": { value: null },
"blurTexture4": { value: null },
"blurTexture5": { value: null },
"dirtTexture": { value: null },
"bloomStrength": { value: 1.0 },
"bloomFactors": { value: null },
"bloomTintColors": { value: null },
"bloomRadius": { value: 0.0 }
},
vertexShader:
"varying vec2 vUv;\n\
void main() {\n\
vUv = uv;\n\
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
}",
fragmentShader:
"varying vec2 vUv;\
uniform sampler2D blurTexture1;\
uniform sampler2D blurTexture2;\
uniform sampler2D blurTexture3;\
uniform sampler2D blurTexture4;\
uniform sampler2D blurTexture5;\
uniform sampler2D dirtTexture;\
uniform float bloomStrength;\
uniform float bloomRadius;\
uniform float bloomFactors[NUM_MIPS];\
uniform vec3 bloomTintColors[NUM_MIPS];\
\
float lerpBloomFactor(const in float factor) { \
float mirrorFactor = 1.2 - factor;\
return mix(factor, mirrorFactor, bloomRadius);\
}\
\
void main() {\
gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + \
lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + \
lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + \
lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + \
lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );\
}"
} );
}
} );
THREE.UnrealBloomPass.BlurDirectionX = new THREE.Vector2( 1.0, 0.0 );
THREE.UnrealBloomPass.BlurDirectionY = new THREE.Vector2( 0.0, 1.0 );

140
js/bloomPass.js Normal file
View File

@@ -0,0 +1,140 @@
import { makePassFBO, makePyramid, resizePyramid } from "./utils.js";
const pyramidHeight = 5;
const levelStrengths = Array(pyramidHeight)
.fill()
.map((_, index) =>
Math.pow(index / (pyramidHeight * 2) + 0.5, 1 / 3).toPrecision(5)
)
.reverse();
export default (regl, config, input) => {
if (config.effect === "none") {
return {
fbo: input,
resize: () => {},
render: () => {}
};
}
const highPassPyramid = makePyramid(regl, pyramidHeight);
const horizontalBlurPyramid = makePyramid(regl, pyramidHeight);
const verticalBlurPyramid = makePyramid(regl, pyramidHeight);
const fbo = makePassFBO(regl);
const highPass = regl({
frag: `
precision mediump float;
varying vec2 vUV;
uniform sampler2D tex;
uniform float highPassThreshold;
void main() {
float value = texture2D(tex, vUV).r;
if (value < highPassThreshold) {
value = 0.;
}
gl_FragColor = vec4(vec3(value), 1.0);
}
`,
uniforms: {
tex: regl.prop("tex")
},
framebuffer: regl.prop("fbo")
});
const blur = regl({
frag: `
precision mediump float;
varying vec2 vUV;
uniform sampler2D tex;
uniform vec2 direction;
uniform float width, height;
void main() {
vec2 size = width > height ? vec2(width / height, 1.) : vec2(1., height / width);
gl_FragColor =
texture2D(tex, vUV) * 0.442 +
(
texture2D(tex, vUV + direction / max(width, height) * size) +
texture2D(tex, vUV - direction / max(width, height) * size)
) * 0.279;
}
`,
uniforms: {
tex: regl.prop("tex"),
direction: regl.prop("direction"),
height: regl.context("viewportWidth"),
width: regl.context("viewportHeight")
},
framebuffer: regl.prop("fbo")
});
const combineBloom = regl({
frag: `
precision mediump float;
varying vec2 vUV;
${verticalBlurPyramid
.map((_, index) => `uniform sampler2D tex_${index};`)
.join("\n")}
uniform sampler2D tex;
uniform float bloomStrength;
void main() {
vec4 total = vec4(0.);
${verticalBlurPyramid
.map(
(_, index) =>
`total += texture2D(tex_${index}, vUV) * ${levelStrengths[index]};`
)
.join("\n")}
gl_FragColor = total * bloomStrength + texture2D(tex, vUV);
}
`,
uniforms: Object.assign(
{
tex: input
},
Object.fromEntries(
verticalBlurPyramid.map((fbo, index) => [`tex_${index}`, fbo])
)
),
framebuffer: fbo
});
return {
fbo,
resize: (viewportWidth, viewportHeight) => {
resizePyramid(
highPassPyramid,
viewportWidth,
viewportHeight,
config.bloomSize
);
resizePyramid(
horizontalBlurPyramid,
viewportWidth,
viewportHeight,
config.bloomSize
);
resizePyramid(
verticalBlurPyramid,
viewportWidth,
viewportHeight,
config.bloomSize
);
fbo.resize(viewportWidth, viewportHeight);
},
render: () => {
highPassPyramid.forEach(fbo => highPass({ fbo, tex: input }));
horizontalBlurPyramid.forEach((fbo, index) =>
blur({ fbo, tex: highPassPyramid[index], direction: [1, 0] })
);
verticalBlurPyramid.forEach((fbo, index) =>
blur({
fbo,
tex: horizontalBlurPyramid[index],
direction: [0, 1]
})
);
combineBloom();
}
};
};

118
js/colorPass.js Normal file
View File

@@ -0,0 +1,118 @@
import { makePassFBO } from "./utils.js";
const colorizeByPalette = regl =>
regl({
frag: `
precision mediump float;
#define PI 3.14159265359
uniform sampler2D tex;
uniform sampler2D paletteColorData;
uniform float ditherMagnitude;
uniform float time;
varying vec2 vUV;
highp float rand( const in vec2 uv, const in float t ) {
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
return fract(sin(sn) * c + t);
}
void main() {
gl_FragColor = texture2D( paletteColorData, vec2( texture2D( tex, vUV ).r - rand( gl_FragCoord.xy, time ) * ditherMagnitude, 0.0 ) );
}
`,
uniforms: {
ditherMagnitude: 0.05
}
});
const colorizeByStripes = regl =>
regl({
frag: `
precision mediump float;
#define PI 3.14159265359
uniform sampler2D tex;
uniform sampler2D stripeColorData;
uniform float ditherMagnitude;
varying vec2 vUV;
highp float rand( const in vec2 uv ) {
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
return fract(sin(sn) * c);
}
void main() {
float value = texture2D(tex, vUV).r;
vec3 value2 = texture2D(stripeColorData, vUV).rgb - rand( gl_FragCoord.xy ) * ditherMagnitude;
gl_FragColor = vec4(value2 * value, 1.0);
}
`,
uniforms: {
ditherMagnitude: 0.1
}
});
const colorizeByImage = regl =>
regl({
frag: `
precision mediump float;
uniform sampler2D tex;
uniform sampler2D backgroundTex;
varying vec2 vUV;
void main() {
gl_FragColor = vec4(texture2D(backgroundTex, vUV).rgb * (pow(texture2D(tex, vUV).r, 1.5) * 0.995 + 0.005), 1.0);
}
`,
uniforms: {
backgroundTex: regl.prop("backgroundTex")
}
});
const colorizersByEffect = {
plain: colorizeByPalette,
customStripes: colorizeByStripes,
stripes: colorizeByStripes,
image: colorizeByImage
};
export default (regl, config, inputFBO) => {
const fbo = makePassFBO(regl);
if (config.effect === "none") {
return {
fbo: inputFBO,
resize: () => {},
render: () => {}
};
}
const colorize = regl({
uniforms: {
tex: regl.prop("tex")
},
framebuffer: fbo
});
const colorizer = (config.effect in colorizersByEffect
? colorizersByEffect[config.effect]
: colorizeByPalette)(regl);
return {
fbo,
resize: fbo.resize,
render: resources => {
colorize(
{
tex: inputFBO
},
() => colorizer(resources)
);
}
};
};

307
js/config.js Normal file
View File

@@ -0,0 +1,307 @@
const fonts = {
coptic: {
glyphTexURL: "coptic_msdf.png",
glyphSequenceLength: 32,
numFontColumns: 8
},
gothic: {
glyphTexURL: "gothic_msdf.png",
glyphSequenceLength: 27,
numFontColumns: 8
},
matrixcode: {
glyphTexURL: "matrixcode_msdf.png",
glyphSequenceLength: 57,
numFontColumns: 8
}
};
const versions = {
paradise: {
...fonts.coptic,
bloomRadius: 1.15,
bloomStrength: 1.75,
highPassThreshold: 0,
cycleSpeed: 0.05,
cycleStyleName: "cycleFasterWhenDimmed",
cursorEffectThreshold: 1,
brightnessOffset: 0.0,
brightnessMultiplier: 1.0,
fallSpeed: 0.05,
glyphEdgeCrop: 0.0,
glyphHeightToWidth: 1,
hasSun: true,
hasThunder: false,
isPolar: true,
rippleTypeName: "circle",
rippleThickness: 0.2,
rippleScale: 30,
rippleSpeed: 0.2,
numColumns: 30,
palette: [
{ rgb: [0.0, 0.0, 0.0], at: 0.0 },
{ rgb: [0.52, 0.17, 0.05], at: 0.4 },
{ rgb: [0.82, 0.37, 0.12], at: 0.7 },
{ rgb: [1.0, 0.74, 0.29], at: 0.9 },
{ rgb: [1.0, 0.9, 0.8], at: 1.0 }
],
raindropLength: 0.5,
slant: 0
},
nightmare: {
...fonts.gothic,
bloomRadius: 0.8,
bloomStrength: 1,
highPassThreshold: 0.5,
cycleSpeed: 0.02,
cycleStyleName: "cycleFasterWhenDimmed",
cursorEffectThreshold: 1,
brightnessOffset: 0.0,
brightnessMultiplier: 1.0,
fallSpeed: 2.0,
glyphEdgeCrop: 0.0,
glyphHeightToWidth: 1,
hasSun: false,
hasThunder: true,
isPolar: false,
rippleTypeName: null,
rippleThickness: 0.2,
rippleScale: 30,
rippleSpeed: 0.2,
numColumns: 60,
palette: [
{ rgb: [0.0, 0.0, 0.0], at: 0.0 },
{ rgb: [0.52, 0.0, 0.0], at: 0.2 },
{ rgb: [0.82, 0.05, 0.05], at: 0.4 },
{ rgb: [1.0, 0.6, 0.3], at: 0.8 },
{ rgb: [1.0, 1.0, 0.9], at: 1.0 }
],
raindropLength: 0.6,
slant: 360 / 16
},
classic: {
...fonts.matrixcode,
bloomRadius: 0.5,
bloomStrength: 1,
highPassThreshold: 0.3,
cycleSpeed: 1,
cycleStyleName: "cycleFasterWhenDimmed",
cursorEffectThreshold: 1,
brightnessOffset: 0.0,
brightnessMultiplier: 1.0,
fallSpeed: 1,
glyphEdgeCrop: 0.0,
glyphHeightToWidth: 1,
hasSun: false,
hasThunder: false,
isPolar: false,
rippleTypeName: null,
rippleThickness: 0.2,
rippleScale: 30,
rippleSpeed: 0.2,
numColumns: 80,
palette: [
{ rgb: [0 / 255, 0 / 255, 0 / 255], at: 0 / 16 },
{ rgb: [6 / 255, 16 / 255, 8 / 255], at: 1 / 16 },
{ rgb: [11 / 255, 28 / 255, 15 / 255], at: 2 / 16 },
{ rgb: [17 / 255, 41 / 255, 23 / 255], at: 3 / 16 },
{ rgb: [20 / 255, 58 / 255, 31 / 255], at: 4 / 16 },
{ rgb: [23 / 255, 84 / 255, 39 / 255], at: 5 / 16 },
{ rgb: [30 / 255, 113 / 255, 48 / 255], at: 6 / 16 },
{ rgb: [43 / 255, 142 / 255, 60 / 255], at: 7 / 16 },
{ rgb: [57 / 255, 160 / 255, 72 / 255], at: 8 / 16 },
{ rgb: [70 / 255, 175 / 255, 81 / 255], at: 9 / 16 },
{ rgb: [75 / 255, 187 / 255, 85 / 255], at: 10 / 16 },
{ rgb: [78 / 255, 196 / 255, 91 / 255], at: 11 / 16 },
{ rgb: [83 / 255, 203 / 255, 102 / 255], at: 12 / 16 },
{ rgb: [92 / 255, 212 / 255, 114 / 255], at: 13 / 16 },
{ rgb: [109 / 255, 223 / 255, 130 / 255], at: 14 / 16 },
{ rgb: [129 / 255, 232 / 255, 148 / 255], at: 15 / 16 },
{ rgb: [140 / 255, 235 / 255, 157 / 255], at: 16 / 16 }
],
raindropLength: 1,
slant: 0
},
operator: {
...fonts.matrixcode,
bloomRadius: 0.3,
bloomStrength: 0.75,
highPassThreshold: 0.0,
cycleSpeed: 0.05,
cycleStyleName: "cycleRandomly",
cursorEffectThreshold: 0.466,
brightnessOffset: 0.25,
brightnessMultiplier: 0.0,
fallSpeed: 0.6,
glyphEdgeCrop: 0.15,
glyphHeightToWidth: 1.35,
hasSun: false,
hasThunder: false,
isPolar: false,
rippleTypeName: "box",
rippleThickness: 0.2,
rippleScale: 30,
rippleSpeed: 0.2,
numColumns: 108,
palette: [
{ rgb: [0.0, 0.0, 0.0], at: 0.0 },
{ rgb: [0.18, 0.9, 0.35], at: 0.6 },
{ rgb: [0.9, 1.0, 0.9], at: 1.0 }
],
raindropLength: 1.5,
slant: 0
}
};
versions.throwback = versions.operator;
versions["1999"] = versions.classic;
export default (searchString, makePaletteTexture) => {
const urlParams = new URLSearchParams(searchString);
const getParam = (keyOrKeys, defaultValue) => {
if (Array.isArray(keyOrKeys)) {
const keys = keyOrKeys;
const key = keys.find(key => urlParams.has(key));
return key != null ? urlParams.get(key) : defaultValue;
} else {
const key = keyOrKeys;
return urlParams.has(key) ? urlParams.get(key) : defaultValue;
}
};
const versionName = getParam("version", "classic");
const version =
versions[versionName] == null ? versions.classic : versions[versionName];
const config = { ...version };
config.animationSpeed = parseFloat(getParam("animationSpeed", 1));
config.fallSpeed *= parseFloat(getParam("fallSpeed", 1));
config.cycleSpeed *= parseFloat(getParam("cycleSpeed", 1));
config.numColumns = parseInt(getParam("width", config.numColumns));
config.raindropLength = parseFloat(
getParam(["raindropLength", "dropLength"], config.raindropLength)
);
config.glyphSequenceLength = config.glyphSequenceLength;
config.slant =
(parseFloat(getParam(["slant", "angle"], config.slant)) * Math.PI) / 180;
config.slantVec = [Math.cos(config.slant), Math.sin(config.slant)];
config.slantScale =
1 / (Math.abs(Math.sin(2 * config.slant)) * (Math.sqrt(2) - 1) + 1);
config.glyphEdgeCrop = parseFloat(getParam("encroach", config.glyphEdgeCrop));
config.glyphHeightToWidth = parseFloat(
getParam("stretch", config.glyphHeightToWidth)
);
config.cursorEffectThreshold = getParam(
"cursorEffectThreshold",
config.cursorEffectThreshold
);
config.bloomSize = Math.max(
0.01,
Math.min(1, parseFloat(getParam("bloomSize", 0.5)))
);
config.effect = getParam("effect", "plain");
config.brightnessChangeBias =
config.animationSpeed * config.fallSpeed == 0
? 1
: Math.min(1, Math.abs(config.animationSpeed * config.fallSpeed));
config.backgroundImage = getParam(
"url",
"https://upload.wikimedia.org/wikipedia/commons/0/0a/Flammarion_Colored.jpg"
);
config.customStripes = getParam(
"colors",
"0.4,0.15,0.1,0.4,0.15,0.1,0.8,0.8,0.6,0.8,0.8,0.6,1.0,0.7,0.8,1.0,0.7,0.8,"
)
.split(",")
.map(parseFloat);
config.showComputationTexture = config.effect === "none";
switch (config.cycleStyleName) {
case "cycleFasterWhenDimmed":
config.cycleStyle = 0;
break;
case "cycleRandomly":
default:
config.cycleStyle = 1;
break;
}
switch (config.rippleTypeName) {
case "box":
config.rippleType = 0;
break;
case "circle":
config.rippleType = 1;
break;
default:
config.rippleType = -1;
}
const PALETTE_SIZE = 2048;
const paletteColors = Array(PALETTE_SIZE);
const sortedEntries = version.palette
.slice()
.sort((e1, e2) => e1.at - e2.at)
.map(entry => ({
rgb: entry.rgb,
arrayIndex: Math.floor(
Math.max(Math.min(1, entry.at), 0) * (PALETTE_SIZE - 1)
)
}));
sortedEntries.unshift({ rgb: sortedEntries[0].rgb, arrayIndex: 0 });
sortedEntries.push({
rgb: sortedEntries[sortedEntries.length - 1].rgb,
arrayIndex: PALETTE_SIZE - 1
});
sortedEntries.forEach((entry, index) => {
paletteColors[entry.arrayIndex] = entry.rgb.slice();
if (index + 1 < sortedEntries.length) {
const nextEntry = sortedEntries[index + 1];
const diff = nextEntry.arrayIndex - entry.arrayIndex;
for (let i = 0; i < diff; i++) {
const ratio = i / diff;
paletteColors[entry.arrayIndex + i] = [
entry.rgb[0] * (1 - ratio) + nextEntry.rgb[0] * ratio,
entry.rgb[1] * (1 - ratio) + nextEntry.rgb[1] * ratio,
entry.rgb[2] * (1 - ratio) + nextEntry.rgb[2] * ratio
];
}
}
});
config.paletteColorData = makePaletteTexture(
paletteColors.flat().map(i => i * 0xff)
);
let stripeColors = [0, 0, 0];
if (config.effect === "pride") {
config.effect = "stripes";
config.customStripes = [
[1, 0, 0],
[1, 0.5, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[0.8, 0, 1]
].flat();
}
if (config.effect === "customStripes" || config.effect === "stripes") {
const numFlagColors = Math.floor(config.customStripes.length / 3);
stripeColors = config.customStripes.slice(0, numFlagColors * 3);
}
config.stripeColorData = makePaletteTexture(
stripeColors.map(f => Math.floor(f * 0xff))
);
const uniforms = Object.fromEntries(
Object.entries(config).filter(([key, value]) => {
const type = typeof (Array.isArray(value) ? value[0] : value);
return type !== "string" && type !== "object";
})
);
return [config, uniforms];
};

300
js/renderer.js Normal file
View File

@@ -0,0 +1,300 @@
import { makePassFBO } from "./utils.js";
export default (regl, config) => {
const state = Array(2)
.fill()
.map(() =>
regl.framebuffer({
color: regl.texture({
radius: config.numColumns,
wrapT: "clamp",
type: "half float"
}),
depthStencil: false
})
);
const fbo = makePassFBO(regl);
const update = regl({
frag: `
precision highp float;
#define PI 3.14159265359
#define SQRT_2 1.4142135623730951
#define SQRT_5 2.23606797749979
uniform float numColumns;
uniform sampler2D lastState;
uniform bool hasSun;
uniform bool hasThunder;
uniform bool showComputationTexture;
uniform float brightnessChangeBias;
uniform float brightnessMultiplier;
uniform float brightnessOffset;
uniform float cursorEffectThreshold;
uniform float time;
uniform float animationSpeed;
uniform float cycleSpeed;
uniform float fallSpeed;
uniform float raindropLength;
uniform float glyphHeightToWidth;
uniform float glyphSequenceLength;
uniform float numFontColumns;
uniform int cycleStyle;
uniform float rippleScale;
uniform float rippleSpeed;
uniform float rippleThickness;
uniform int rippleType;
float max2(vec2 v) {
return max(v.x, v.y);
}
highp float rand( const in vec2 uv ) {
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
return fract(sin(sn) * c);
}
vec2 rand2(vec2 p) {
return fract(vec2(sin(p.x * 591.32 + p.y * 154.077), cos(p.x * 391.32 + p.y * 49.077)));
}
highp float blast( const in float x, const in float power ) {
return pow(pow(pow(x, power), power), power);
}
float ripple(vec2 uv, float simTime) {
if (rippleType == -1) {
return 0.;
}
float rippleTime = (simTime * 0.5 + 0.2 * sin(simTime)) * rippleSpeed + 1.;
vec2 offset = rand2(vec2(floor(rippleTime), 0.)) - 0.5;
vec2 ripplePos = uv + offset;
float rippleDistance;
if (rippleType == 0) {
rippleDistance = max2(abs(ripplePos) * vec2(1.0, glyphHeightToWidth));
} else if (rippleType == 1) {
rippleDistance = length(ripplePos);
}
float rippleValue = fract(rippleTime) * rippleScale - rippleDistance;
if (rippleValue > 0. && rippleValue < rippleThickness) {
return 0.75;
} else {
return 0.;
}
}
void main() {
vec2 uv = gl_FragCoord.xy / numColumns;
float columnTimeOffset = rand(vec2(gl_FragCoord.x, 0.0));
float columnSpeedOffset = rand(vec2(gl_FragCoord.x + 0.1, 0.0));
vec4 data = texture2D( lastState, uv );
bool isInitializing = length(data) == 0.;
if (isInitializing) {
data = vec4(
rand(uv),
showComputationTexture ? 0.5 : rand(uv),
0.,
0.
);
}
float brightness = data.r;
float glyphCycle = data.g;
float simTime = time * animationSpeed;
float columnTime = (columnTimeOffset * 1000.0 + simTime * 0.5 * fallSpeed) * (0.5 + columnSpeedOffset * 0.5) + (sin(simTime * fallSpeed * columnSpeedOffset) * 0.2);
float glyphTime = (gl_FragCoord.y * 0.01 + columnTime) / raindropLength;
float value = 1.0 - fract((glyphTime + 0.3 * sin(SQRT_2 * glyphTime) + 0.2 * sin(SQRT_5 * glyphTime)));
float newBrightness = 3.0 * log(value * 1.25);
if (hasSun) {
newBrightness = pow(fract(newBrightness * 0.5), 3.0) * uv.y * 2.0;
}
if (hasThunder) {
vec2 distVec = (gl_FragCoord.xy / numColumns - vec2(0.5, 1.0)) * vec2(1.0, 2.0);
float thunder = (blast(sin(SQRT_5 * simTime), 10.0) + blast(sin(SQRT_2 * simTime), 10.0));
thunder *= 30.0 * (1.0 - 1.0 * length(distVec));
newBrightness *= max(0.0, thunder) * 1.0 + 0.7;
if (newBrightness > brightness) {
brightness = newBrightness;
} else {
brightness = mix(brightness, newBrightness, brightnessChangeBias * 0.1);
}
} else if (isInitializing) {
brightness = newBrightness;
} else {
brightness = mix(brightness, newBrightness, brightnessChangeBias);
}
float glyphCycleSpeed = 0.0;
if (cycleStyle == 1) {
glyphCycleSpeed = fract((glyphTime + 0.7 * sin(SQRT_2 * glyphTime) + 1.1 * sin(SQRT_5 * glyphTime))) * 0.75;
} else if (cycleStyle == 0) {
if (brightness > 0.0) glyphCycleSpeed = pow(1.0 - brightness, 4.0);
}
glyphCycle = fract(glyphCycle + 0.005 * animationSpeed * cycleSpeed * glyphCycleSpeed);
float symbol = floor(glyphSequenceLength * glyphCycle);
float symbolX = mod(symbol, numFontColumns);
float symbolY = ((numFontColumns - 1.0) - (symbol - symbolX) / numFontColumns);
float effect = 0.;
effect += ripple(gl_FragCoord.xy / numColumns * 2.0 - 1.0, simTime);
if (brightness >= cursorEffectThreshold) {
effect = 1.0;
}
if (brightness > -1.) {
brightness = brightness * brightnessMultiplier + brightnessOffset;
}
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
gl_FragColor.r = brightness;
gl_FragColor.g = glyphCycle;
if (showComputationTexture) {
// Better use of the blue channel, for show and tell
gl_FragColor.b = min(1.0, glyphCycleSpeed);
gl_FragColor.a = 1.0;
} else {
gl_FragColor.b = symbolY * numFontColumns + symbolX;
gl_FragColor.a = effect;
}
}
`,
uniforms: {
lastState: ({ tick }) => state[tick % 2]
},
framebuffer: ({ tick }) => state[(tick + 1) % 2]
});
const render = regl({
vert: `
attribute vec2 aPosition;
uniform float width;
uniform float height;
varying vec2 vUV;
void main() {
vUV = aPosition / 2.0 + 0.5;
vec2 size = width > height ? vec2(width / height, 1.) : vec2(1., height / width);
gl_Position = vec4( size * aPosition, 0.0, 1.0 );
}
`,
frag: `
#define PI 3.14159265359
#ifdef GL_OES_standard_derivatives
#extension GL_OES_standard_derivatives: enable
#endif
precision lowp float;
uniform sampler2D msdfTex;
uniform sampler2D lastState;
uniform float numColumns;
uniform float numFontColumns;
uniform vec2 slantVec;
uniform float slantScale;
uniform float glyphHeightToWidth;
uniform float glyphEdgeCrop;
uniform bool isPolar;
uniform bool showComputationTexture;
varying vec2 vUV;
float median3(vec3 i) {
return max(min(i.r, i.g), min(max(i.r, i.g), i.b));
}
void main() {
vec2 uv = vUV;
if (isPolar) {
uv -= 0.5;
uv *= 0.5;
uv.y -= 0.5;
float radius = length(uv);
float angle = atan(uv.y, uv.x) / (2. * PI) + 0.5;
uv = vec2(angle * 4. - 0.5, 1.25 - radius * 1.5);
} else {
uv = vec2(
(uv.x - 0.5) * slantVec.x + (uv.y - 0.5) * slantVec.y,
(uv.y - 0.5) * slantVec.x - (uv.x - 0.5) * slantVec.y
) * slantScale + 0.5;
}
uv.y /= glyphHeightToWidth;
vec4 glyph = texture2D(lastState, uv);
if (showComputationTexture) {
gl_FragColor = glyph;
return;
}
// Unpack the values from the font texture
float brightness = glyph.r;
float effect = glyph.a;
brightness = max(effect, brightness);
float symbolIndex = glyph.b;
vec2 symbolUV = vec2(mod(symbolIndex, numFontColumns), floor(symbolIndex / numFontColumns));
vec2 glyphUV = fract(uv * numColumns);
glyphUV -= 0.5;
glyphUV *= clamp(1.0 - glyphEdgeCrop, 0.0, 1.0);
glyphUV += 0.5;
vec3 dist = texture2D(msdfTex, (glyphUV + symbolUV) / numFontColumns).rgb;
// The rest is straight up MSDF
float sigDist = median3(dist) - 0.5;
float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);
gl_FragColor = vec4(vec3(brightness * alpha), 1.0);
}
`,
uniforms: {
msdfTex: regl.prop("msdfTex"),
height: regl.context("viewportWidth"),
width: regl.context("viewportHeight"),
lastState: ({ tick }) => state[tick % 2]
},
framebuffer: fbo
});
return {
resize: fbo.resize,
fbo,
update,
render
};
};

91
js/utils.js Normal file
View File

@@ -0,0 +1,91 @@
const makePassTexture = regl =>
regl.texture({
width: 1,
height: 1,
type: "half float",
wrap: "clamp",
min: "linear",
mag: "linear"
});
const makePassFBO = regl => regl.framebuffer({ color: makePassTexture(regl) });
const makePyramid = (regl, height) =>
Array(height)
.fill()
.map(_ => makePassFBO(regl));
const resizePyramid = (pyramid, vw, vh, scale) =>
pyramid.forEach((fbo, index) =>
fbo.resize(
Math.floor((vw * scale) / 2 ** index),
Math.floor((vh * scale) / 2 ** index)
)
);
const loadImages = async (regl, manifest) => {
const keys = Object.keys(manifest);
const urls = Object.values(manifest);
const images = await Promise.all(urls.map(url => loadImage(regl, url)));
return Object.fromEntries(images.map((image, index) => [keys[index], image]));
};
const loadImage = async (regl, url) => {
if (url == null) {
return null;
}
const image = new Image();
image.crossOrigin = "anonymous";
image.src = url;
await image.decode();
return regl.texture({
data: image,
mag: "linear",
min: "linear",
flipY: true
});
};
const makeFullScreenQuad = (regl, uniforms) =>
regl({
vert: `
precision mediump float;
attribute vec2 aPosition;
varying vec2 vUV;
void main() {
vUV = 0.5 * (aPosition + 1.0);
gl_Position = vec4(aPosition, 0, 1);
}
`,
frag: `
precision mediump float;
varying vec2 vUV;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, vUV);
}
`,
attributes: {
aPosition: [-4, -4, 4, -4, 0, 4]
},
uniforms: {
...uniforms,
time: regl.context("time")
},
depth: { enable: false },
count: 3
});
export {
makePassTexture,
makePassFBO,
makePyramid,
resizePyramid,
loadImage,
loadImages,
makeFullScreenQuad
};