forked from Rezmason/matrix
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrainPass.js
More file actions
407 lines (369 loc) · 12.4 KB
/
Copy pathrainPass.js
File metadata and controls
407 lines (369 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import {
loadImage,
loadText,
makePassFBO,
makePassTexture,
makeDoubleBuffer,
makePass,
fullscreenPassVertGLSL,
fullscreenPassAttributes,
fullscreenPassVertexCount,
} from "./utils.js";
const extractEntries = (src, keys) => Object.fromEntries(Array.from(Object.entries(src)).filter(([key]) => keys.includes(key)));
const rippleTypes = {
box: 0,
circle: 1,
};
// These compute buffers are used to compute the properties of cells in the grid.
// They take turns being the source and destination of a "compute" shader.
// The half float data type is crucial! It lets us store almost any real number,
// whereas the default type limits us to integers between 0 and 255.
// These double buffers are smaller than the screen, because their pixels correspond
// with cells in the grid, and the cells' glyphs are much larger than a pixel.
const makeComputeDoubleBuffer = (regl, height, width) =>
makeDoubleBuffer(regl, {
width,
height,
wrapT: "clamp",
type: "half float",
data: Array(width * height * 4).fill(0),
});
const numVerticesPerQuad = 2 * 3;
const tlVert = [0, 0];
const trVert = [0, 1];
const blVert = [1, 0];
const brVert = [1, 1];
const quadVertices = [tlVert, trVert, brVert, tlVert, brVert, blVert];
export default ({ regl, config, lkg }) => {
const { mat2, mat4, vec2, vec3 } = glMatrix;
// The volumetric mode multiplies the number of columns
// to reach the desired density, and then overlaps them
const volumetric = config.volumetric;
const density = volumetric && config.effect !== "none" ? config.density : 1;
const [numRows, numColumns] = [config.numColumns, Math.floor(config.numColumns * density)];
// The volumetric mode requires us to create a grid of quads,
// rather than a single quad for our geometry
const [numQuadRows, numQuadColumns] = volumetric ? [numRows, numColumns] : [1, 1];
const numQuads = numQuadRows * numQuadColumns;
const quadSize = [1 / numQuadColumns, 1 / numQuadRows];
// Various effect-related values
const rippleType = config.rippleTypeName in rippleTypes ? rippleTypes[config.rippleTypeName] : -1;
const slantVec = [Math.cos(config.slant), Math.sin(config.slant)];
const slantScale = 1 / (Math.abs(Math.sin(2 * config.slant)) * (Math.sqrt(2) - 1) + 1);
const showDebugView = config.effect === "none";
const glyphTransform = mat2.fromScaling(mat2.create(), vec2.fromValues(config.glyphFlip ? -1 : 1, 1));
mat2.rotate(glyphTransform, glyphTransform, (config.glyphRotation * Math.PI) / 180);
const commonUniforms = {
...extractEntries(config, ["animationSpeed", "glyphHeightToWidth", "glyphSequenceLength", "glyphTextureGridSize"]),
numColumns,
numRows,
showDebugView,
};
const introDoubleBuffer = makeComputeDoubleBuffer(regl, 1, numColumns);
const rainPassIntro = loadText("shaders/glsl/rainPass.intro.frag.glsl");
const introUniforms = {
...commonUniforms,
...extractEntries(config, ["fallSpeed", "skipIntro"]),
};
const raindropDoubleBuffer = makeComputeDoubleBuffer(regl, numRows, numColumns);
const rainPassRaindrop = loadText("shaders/glsl/rainPass.raindrop.frag.glsl");
const raindropUniforms = {
...commonUniforms,
...extractEntries(config, ["brightnessDecay", "fallSpeed", "raindropLength", "loops", "skipIntro"]),
};
const symbolDoubleBuffer = makeComputeDoubleBuffer(regl, numRows, numColumns);
const rainPassSymbol = loadText("shaders/glsl/rainPass.symbol.frag.glsl");
const symbolUniforms = {
...commonUniforms,
...extractEntries(config, ["cycleSpeed", "cycleFrameSkip", "loops", "glyphRandomFlip"]),
};
const effectDoubleBuffer = makeComputeDoubleBuffer(regl, numRows, numColumns);
const rainPassEffect = loadText("shaders/glsl/rainPass.effect.frag.glsl");
const effectUniforms = {
...commonUniforms,
...extractEntries(config, ["hasThunder", "rippleScale", "rippleSpeed", "rippleThickness", "loops"]),
rippleType,
};
const quadPositions = Array(numQuadRows)
.fill()
.map((_, y) =>
Array(numQuadColumns)
.fill()
.map((_, x) => Array(numVerticesPerQuad).fill([x, y])),
);
// We render the code into an FBO using MSDFs: https://github.com/Chlumsky/msdfgen
const glyphMSDF = loadImage(regl, config.glyphMSDFURL);
const glintMSDF = loadImage(regl, config.glintMSDFURL);
const baseTexture = loadImage(regl, config.baseTextureURL, true);
const glintTexture = loadImage(regl, config.glintTextureURL, true);
const rainPassVert = loadText("shaders/glsl/rainPass.vert.glsl");
const rainPassFrag = loadText("shaders/glsl/rainPass.frag.glsl");
// Volumetric rendering benefits from a depth buffer so nearer glyphs can occlude
// farther ones. In 2D mode we keep the lighter-weight color-only FBO.
const output = volumetric
? regl.framebuffer({
color: makePassTexture(regl, config.useHalfFloat),
depth: true,
})
: makePassFBO(regl, config.useHalfFloat);
const renderUniforms = {
...commonUniforms,
...extractEntries(config, [
// vertex
"forwardSpeed",
"glyphVerticalSpacing",
// fragment
"baseBrightness",
"baseContrast",
"glintBrightness",
"glintContrast",
"hasBaseTexture",
"hasGlintTexture",
"brightnessThreshold",
"brightnessOverride",
"isolateCursor",
"isolateGlint",
"glyphEdgeCrop",
"isPolar",
"glyphRandomFlip",
]),
glyphTransform,
density,
numQuadColumns,
numQuadRows,
quadSize,
slantScale,
slantVec,
volumetric,
};
let intro;
let raindrop;
let symbol;
let effect;
let renderDepth;
let render;
// Bind all rain GLSL as static strings after fetch. `regl.prop("frag")` with a
// missing/undefined source becomes shaderSource(undefined) → GLSL `undefined` at line 0.
const rainProgramsReady = Promise.all([
rainPassIntro.loaded,
rainPassRaindrop.loaded,
rainPassSymbol.loaded,
rainPassEffect.loaded,
rainPassVert.loaded,
rainPassFrag.loaded,
]).then(() => {
const need = (label, s) => {
if (typeof s !== "string" || !s.trim()) {
throw new Error(`[Matrix] ${label} shader missing after load (${s?.length ?? "n/a"} chars).`);
}
return s;
};
const introFrag = need("rainPass.intro.frag", rainPassIntro.text());
const raindropFrag = need("rainPass.raindrop.frag", rainPassRaindrop.text());
const symbolFrag = need("rainPass.symbol.frag", rainPassSymbol.text());
const effectFrag = need("rainPass.effect.frag", rainPassEffect.text());
const vertSource = need("rainPass.vert", rainPassVert.text());
const fragSource = need("rainPass.frag", rainPassFrag.text());
intro = regl({
vert: fullscreenPassVertGLSL,
frag: introFrag,
attributes: fullscreenPassAttributes,
count: fullscreenPassVertexCount,
depth: { enable: false },
uniforms: {
...introUniforms,
time: regl.context("time"),
tick: regl.context("tick"),
previousIntroState: introDoubleBuffer.back,
},
framebuffer: introDoubleBuffer.front,
});
raindrop = regl({
vert: fullscreenPassVertGLSL,
frag: raindropFrag,
attributes: fullscreenPassAttributes,
count: fullscreenPassVertexCount,
depth: { enable: false },
uniforms: {
...raindropUniforms,
time: regl.context("time"),
tick: regl.context("tick"),
introState: introDoubleBuffer.front,
previousRaindropState: raindropDoubleBuffer.back,
},
framebuffer: raindropDoubleBuffer.front,
});
symbol = regl({
vert: fullscreenPassVertGLSL,
frag: symbolFrag,
attributes: fullscreenPassAttributes,
count: fullscreenPassVertexCount,
depth: { enable: false },
uniforms: {
...symbolUniforms,
time: regl.context("time"),
tick: regl.context("tick"),
raindropState: raindropDoubleBuffer.front,
previousSymbolState: symbolDoubleBuffer.back,
},
framebuffer: symbolDoubleBuffer.front,
});
effect = regl({
vert: fullscreenPassVertGLSL,
frag: effectFrag,
attributes: fullscreenPassAttributes,
count: fullscreenPassVertexCount,
depth: { enable: false },
uniforms: {
...effectUniforms,
time: regl.context("time"),
tick: regl.context("tick"),
raindropState: raindropDoubleBuffer.front,
previousEffectState: effectDoubleBuffer.back,
},
framebuffer: effectDoubleBuffer.front,
});
const renderOptions = {
vert: vertSource,
frag: fragSource,
uniforms: {
...renderUniforms,
time: regl.context("time"),
raindropState: raindropDoubleBuffer.front,
symbolState: symbolDoubleBuffer.front,
effectState: effectDoubleBuffer.front,
glyphMSDF: glyphMSDF.texture,
glintMSDF: glintMSDF.texture,
baseTexture: baseTexture.texture,
glintTexture: glintTexture.texture,
msdfPxRange: 4.0,
glyphMSDFSize: () => [glyphMSDF.width(), glyphMSDF.height()],
glintMSDFSize: () => [glintMSDF.width(), glintMSDF.height()],
camera: regl.prop("camera"),
transform: regl.prop("transform"),
screenSize: regl.prop("screenSize"),
},
viewport: regl.prop("viewport"),
attributes: {
aPosition: quadPositions,
aCorner: Array(numQuads).fill(quadVertices),
},
count: numQuads * numVerticesPerQuad,
framebuffer: output,
};
if (volumetric) {
renderDepth = regl({
...renderOptions,
colorMask: [false, false, false, false],
depth: {
enable: true,
mask: true,
func: "less",
},
});
}
render = regl({
...renderOptions,
blend: {
enable: true,
func: {
src: "one",
dst: "one",
},
},
depth: volumetric
? {
enable: true,
mask: false,
func: "equal",
}
: {
enable: false,
},
});
});
// Camera and transform math for the volumetric mode
const screenSize = [1, 1];
const transform = mat4.create();
if (volumetric && config.isometric) {
mat4.rotateX(transform, transform, (Math.PI * 1) / 8);
mat4.rotateY(transform, transform, (Math.PI * 1) / 4);
mat4.translate(transform, transform, vec3.fromValues(0, 0, -1));
mat4.scale(transform, transform, vec3.fromValues(1, 1, 2));
} else if (lkg.enabled) {
mat4.translate(transform, transform, vec3.fromValues(0, 0, -1.1));
mat4.scale(transform, transform, vec3.fromValues(1, 1, 1));
mat4.scale(transform, transform, vec3.fromValues(0.15, 0.15, 0.15));
} else {
mat4.translate(transform, transform, vec3.fromValues(0, 0, -1));
}
const camera = mat4.create();
const vantagePoints = [];
return makePass(
{
primary: output,
},
Promise.all([glyphMSDF.loaded, glintMSDF.loaded, baseTexture.loaded, glintTexture.loaded, rainProgramsReady]),
(w, h) => {
output.resize(w, h);
const aspectRatio = w / h;
const [numTileColumns, numTileRows] = [lkg.tileX, lkg.tileY];
const numVantagePoints = numTileRows * numTileColumns;
const tileWidth = Math.floor(w / numTileColumns);
const tileHeight = Math.floor(h / numTileRows);
vantagePoints.length = 0;
for (let row = 0; row < numTileRows; row++) {
for (let column = 0; column < numTileColumns; column++) {
const index = column + row * numTileColumns;
const camera = mat4.create();
if (volumetric && config.isometric) {
if (aspectRatio > 1) {
mat4.ortho(camera, -1.5 * aspectRatio, 1.5 * aspectRatio, -1.5, 1.5, -1000, 1000);
} else {
mat4.ortho(camera, -1.5, 1.5, -1.5 / aspectRatio, 1.5 / aspectRatio, -1000, 1000);
}
} else if (lkg.enabled) {
mat4.perspective(camera, (Math.PI / 180) * lkg.fov, lkg.quiltAspect, 0.0001, 1000);
const distanceToTarget = -1; // TODO: Get from somewhere else
let vantagePointAngle = (Math.PI / 180) * lkg.viewCone * (index / (numVantagePoints - 1) - 0.5);
if (isNaN(vantagePointAngle)) {
vantagePointAngle = 0;
}
const xOffset = distanceToTarget * Math.tan(vantagePointAngle);
mat4.translate(camera, camera, vec3.fromValues(xOffset, 0, 0));
camera[8] = -xOffset / (distanceToTarget * Math.tan((Math.PI / 180) * 0.5 * lkg.fov) * lkg.quiltAspect); // Is this right??
} else {
mat4.perspective(camera, (Math.PI / 180) * 90, aspectRatio, 0.0001, 1000);
}
const viewport = {
x: column * tileWidth,
y: row * tileHeight,
width: tileWidth,
height: tileHeight,
};
vantagePoints.push({ camera, viewport });
}
}
[screenSize[0], screenSize[1]] = aspectRatio > 1 ? [1, aspectRatio] : [1 / aspectRatio, 1];
},
(shouldRender) => {
intro({});
raindrop({});
symbol({});
effect({});
if (shouldRender) {
regl.clear({
depth: 1,
color: [0, 0, 0, 1],
framebuffer: output,
});
for (const vantagePoint of vantagePoints) {
if (volumetric) {
renderDepth({ ...vantagePoint, transform, screenSize });
}
render({ ...vantagePoint, transform, screenSize });
}
}
},
);
};