roamwright 0.2.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CONTRIBUTING.md +3 -1
  2. package/README.md +19 -21
  3. package/geometry/bedding.js +141 -0
  4. package/geometry/builder-cells.js +42 -0
  5. package/geometry/builder-frame.js +47 -0
  6. package/geometry/builder.js +189 -177
  7. package/geometry/cell-mask.js +25 -0
  8. package/geometry/creased-sheet.js +34 -34
  9. package/geometry/ear.js +36 -36
  10. package/geometry/erosion.js +65 -42
  11. package/geometry/face-grid.js +65 -65
  12. package/geometry/foliage.js +47 -0
  13. package/geometry/hair-gathers.js +41 -41
  14. package/geometry/hair-locks.js +41 -41
  15. package/geometry/hair-patch.js +18 -18
  16. package/geometry/hair-shell.js +31 -31
  17. package/geometry/head-profile.js +15 -15
  18. package/geometry/head-shape.js +77 -77
  19. package/geometry/heightfield.js +27 -18
  20. package/geometry/index-parts.js +60 -0
  21. package/geometry/instance-visibility.js +41 -0
  22. package/geometry/instances.js +35 -12
  23. package/geometry/outline-grid.js +7 -7
  24. package/geometry/part-ranges.js +18 -0
  25. package/geometry/path-field.js +63 -33
  26. package/geometry/placement.js +52 -52
  27. package/geometry/point-buckets.js +50 -0
  28. package/geometry/primitives.js +63 -47
  29. package/geometry/sagging-tube.js +27 -27
  30. package/geometry/sampled-surface.js +109 -77
  31. package/geometry/scatter-grid.js +46 -6
  32. package/geometry/sculpt.js +93 -93
  33. package/geometry/shore-grid.js +77 -34
  34. package/geometry/strata-field.js +92 -92
  35. package/geometry/strata-tiles.js +91 -91
  36. package/geometry/stream.js +70 -48
  37. package/geometry/terrain-chunks.js +101 -92
  38. package/geometry/terrain-extension.js +6 -6
  39. package/index.js +5 -0
  40. package/math/cell-edge.js +16 -16
  41. package/math/cell-key.js +6 -0
  42. package/math/circle-clearances.js +19 -0
  43. package/math/cloth-textures.js +6 -6
  44. package/math/cloud-textures.js +20 -20
  45. package/math/color.js +14 -14
  46. package/math/curve.js +22 -22
  47. package/math/mountain-ranges.js +216 -165
  48. package/math/noise.js +101 -49
  49. package/math/particle-noise.js +28 -28
  50. package/math/periodic.js +5 -5
  51. package/math/random.js +24 -15
  52. package/math/rectangles.js +52 -0
  53. package/math/rock-texture.js +7 -7
  54. package/math/scalar.js +5 -5
  55. package/math/surface-textures.js +54 -54
  56. package/motion/arm-reach.js +24 -24
  57. package/motion/ballistic-arc.js +11 -0
  58. package/motion/biped-cycle.js +44 -0
  59. package/motion/biped-leg.js +37 -0
  60. package/motion/biped-stride.js +98 -122
  61. package/motion/contact-transition.js +33 -0
  62. package/motion/crowd-alarms.js +39 -39
  63. package/motion/crowd-routine.js +94 -65
  64. package/motion/daily-clock.js +9 -9
  65. package/motion/deck-surface.js +38 -0
  66. package/motion/ground-lookahead.js +29 -0
  67. package/motion/instance-sight.js +8 -8
  68. package/motion/player.js +36 -28
  69. package/motion/quadruped.js +155 -155
  70. package/motion/spaces.js +32 -32
  71. package/motion/weather.js +73 -24
  72. package/motion/wind.js +32 -13
  73. package/package.json +8 -4
  74. package/rendering/caster-motion.js +5 -5
  75. package/rendering/cell-lod.js +147 -82
  76. package/rendering/cloud-dome.js +28 -28
  77. package/rendering/cloud-field.js +2 -2
  78. package/rendering/compilation-schedule.js +68 -11
  79. package/rendering/contact-shadows.js +2 -2
  80. package/rendering/context.js +12 -0
  81. package/rendering/crowd-skinning.js +13 -13
  82. package/rendering/crust.js +18 -12
  83. package/rendering/daylight.js +3 -3
  84. package/rendering/detail-range.js +28 -0
  85. package/rendering/dispose-meshes.js +18 -0
  86. package/rendering/dof.js +9 -9
  87. package/rendering/eye-adapt.js +14 -14
  88. package/rendering/far-shadow.js +8 -8
  89. package/rendering/flocks.js +78 -78
  90. package/rendering/garment-material.js +17 -17
  91. package/rendering/glow-lines.js +13 -13
  92. package/rendering/hair-strands.js +20 -20
  93. package/rendering/height-probe.js +149 -19
  94. package/rendering/label-layout.js +46 -0
  95. package/rendering/label-range.js +38 -0
  96. package/rendering/light-budget.js +52 -52
  97. package/rendering/light-shafts.js +23 -23
  98. package/rendering/local-lights.js +15 -4
  99. package/rendering/material-lod.js +49 -49
  100. package/rendering/particle-emitters.js +90 -90
  101. package/rendering/particles.js +78 -67
  102. package/rendering/piece-batch.js +91 -26
  103. package/rendering/planar-reflection.js +38 -38
  104. package/rendering/post-shaders.js +17 -13
  105. package/rendering/post.js +71 -71
  106. package/rendering/rain-streaks.js +67 -0
  107. package/rendering/road-surface.js +11 -11
  108. package/rendering/sea-shaders.js +11 -11
  109. package/rendering/shader-warmup.js +29 -16
  110. package/rendering/shadow-alignment.js +4 -4
  111. package/rendering/shadow-depth.js +7 -7
  112. package/rendering/sky-occlusion.js +16 -16
  113. package/rendering/sky.js +16 -6
  114. package/rendering/stage-lights.js +6 -6
  115. package/rendering/static-point-shadow.js +3 -3
  116. package/rendering/still-casters.js +1 -1
  117. package/rendering/strata-material.js +10 -10
  118. package/rendering/stream-flow.js +10 -10
  119. package/rendering/taa.js +26 -26
  120. package/rendering/talus.js +15 -15
  121. package/rendering/terrain-rock.js +7 -7
  122. package/rendering/texture-fills.js +8 -8
  123. package/rendering/textures.js +28 -28
  124. package/rendering/wakes.js +24 -24
  125. package/rendering/water-material.js +36 -23
  126. package/rendering/world-matrices.js +38 -38
  127. package/runtime/diagnostic-log.js +2 -2
  128. package/runtime/first-use.js +33 -28
  129. package/runtime/frame-budget.js +49 -0
  130. package/runtime/frame-pacing.js +33 -0
  131. package/runtime/gpu-timing.js +13 -10
  132. package/runtime/grid-cache.js +1 -1
  133. package/runtime/grid-rows.js +44 -5
  134. package/runtime/hand-over.js +41 -23
  135. package/runtime/pool.js +58 -16
  136. package/runtime/quality-fit.js +1 -1
  137. package/runtime/search.js +22 -22
  138. package/runtime/spatial-audio.js +13 -13
  139. package/runtime/withdrawable-task.js +35 -0
  140. package/runtime/worker.js +7 -0
@@ -43,9 +43,9 @@ class Runs {
43
43
  while (i < this.gaps.length && this.gaps[i][0] < start) i++;
44
44
  this.gaps.splice(i, 0, [start, count]);
45
45
  for (const at of [i, i - 1]) {
46
- const a = this.gaps[at],
47
- b = this.gaps[at + 1];
48
- if (a && b && a[0] + a[1] === b[0]) this.gaps.splice(at, 2, [a[0], a[1] + b[1]]);
46
+ const firstGap = this.gaps[at],
47
+ nextGap = this.gaps[at + 1];
48
+ if (firstGap && nextGap && firstGap[0] + firstGap[1] === nextGap[0]) this.gaps.splice(at, 2, [firstGap[0], firstGap[1] + nextGap[1]]);
49
49
  }
50
50
  }
51
51
  }
@@ -56,6 +56,16 @@ class Runs {
56
56
  * context. Shadow hooks optionally integrate a cache of static point shadows.
57
57
  * Supply static triangle geometry with matching layouts and indexing to each
58
58
  * batch. Attributes use contiguous Float32Array, Int8Array or Uint8Array data.
59
+ * @returns A mesh constructor. Create one instance per batch material.
60
+ * @example
61
+ * ```js
62
+ * const Batch = createPieceBatch({ renderer, camera });
63
+ * const batch = new Batch(material);
64
+ * scene.add(batch);
65
+ * const id = batch.add(geometry);
66
+ * batch.setView(id, batch.materialView(highlightMaterial));
67
+ * batch.setView(id);
68
+ * ```
59
69
  */
60
70
  export function createPieceBatch({ renderer, camera, markStill = () => {}, isStill = () => false, keptAway = () => false }) {
61
71
  const _clip = new THREE.Matrix4(),
@@ -67,7 +77,8 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
67
77
  const DEPTH_STEP = 1 / 16,
68
78
  DEPTH_FROM = -1024,
69
79
  PIECES_MOST = 65536;
70
- let _keys = new Float64Array(64);
80
+ const keyBuffers = []; // one scratch buffer per power of two, shared by all passes
81
+ let _keys;
71
82
  // The i-th of `seen` pieces in order, nearest first (farthest first, from the end of the keys, where `far`)
72
83
  const nthSeen = (i, seen, far) => _seen[_keys[far ? seen - 1 - i : i] % PIECES_MOST];
73
84
  let multi; // the multi-draw extension, or null where the browser has none (the pieces are then drawn one by one)
@@ -76,6 +87,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
76
87
  // vertices, indices: how many to make room for at first (a batch that is filled once says exactly how many); fit: LOOSE or TIGHT
77
88
  constructor(material, vertices = 0, indices = 0, fit = LOOSE) {
78
89
  super(new THREE.BufferGeometry(), material);
90
+ this.isPieceBatch = true;
79
91
  this.room = { vertices, indices };
80
92
  this.fit = fit;
81
93
  this.held = { vertices: 0, indices: 0 }; // what the buffers have room for
@@ -85,6 +97,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
85
97
  this.layout = null; // [name, array type, item size, normalized] of each attribute, from the first piece
86
98
  this.indices = null; // an indexed batch keeps its indices here as well, to fill a larger buffer from when it grows
87
99
  this.pieces = []; // by id: { vertexStart, vertexCount, start, count, sphere, shown, depth }, or null where one was removed
100
+ this.views = new Map(); // child meshes drawing pieces with alternate materials from these same buffers
88
101
  this.spare = []; // ids to give out again
89
102
  this.starts = new Int32Array(16); // the pieces after the first that the pass being drawn sees: where each begins (in bytes, if indexed)
90
103
  this.counts = new Int32Array(16);
@@ -103,7 +116,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
103
116
  index = geometry.index,
104
117
  gl = renderer.getContext();
105
118
  if (!this.layout) {
106
- this.layout = Object.entries(geometry.attributes).map(([name, a]) => [name, a.array.constructor, a.itemSize, a.normalized]);
119
+ this.layout = Object.entries(geometry.attributes).map(([name, attribute]) => [name, attribute.array.constructor, attribute.itemSize, attribute.normalized]);
107
120
  if (index) this.indices = new Uint32Array(0);
108
121
  }
109
122
  const { vertexStart, start } = this.claim(vertexCount, count);
@@ -117,6 +130,43 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
117
130
  if (!geometry.boundingSphere) geometry.computeBoundingSphere();
118
131
  return this.record({ vertexStart, vertexCount, start, count, sphere: geometry.boundingSphere.clone() });
119
132
  }
133
+ // A second material pass over a disjoint subset of this batch, sharing its buffers and
134
+ // transform. Only setView changes membership. Empty views skip drawing altogether.
135
+ materialView(material) {
136
+ const mesh = new THREE.Mesh(this.geometry, material);
137
+ const members = new Set();
138
+ this.views.set(mesh, members);
139
+ mesh.visible = false;
140
+ mesh.matrixAutoUpdate = false;
141
+ mesh.layers.mask = this.layers.mask;
142
+ mesh.castShadow = this.castShadow;
143
+ mesh.receiveShadow = this.receiveShadow;
144
+ mesh.boundingSphere = this.boundingSphere.clone();
145
+ mesh.raycast = this.raycast;
146
+ mesh.onBeforeRender = (_r, _s, viewer) => this.choose(viewer, mesh, members);
147
+ mesh.onAfterRender = (_r, _s, _c, _g, drawnWith) => this.drawRest(drawnWith);
148
+ mesh.onBeforeShadow = (_r, _o, _c, viewer, _g, drawnWith) => this.chooseShadow(viewer, drawnWith, mesh, members);
149
+ mesh.onAfterShadow = (_r, _o, _c, _v, _g, drawnWith) => this.drawRest(drawnWith);
150
+ super.add(mesh);
151
+ return mesh;
152
+ }
153
+ setView(id, mesh = null) {
154
+ const piece = this.pieces[id];
155
+ if (piece.view === mesh) return;
156
+ const members = mesh && this.views.get(mesh);
157
+ if (mesh && !members) throw new Error('Material view belongs to another batch');
158
+ if (piece.view) {
159
+ const previous = this.views.get(piece.view);
160
+ previous.delete(piece);
161
+ piece.view.visible = previous.size > 0;
162
+ }
163
+ piece.view = mesh;
164
+ if (mesh) {
165
+ members.add(piece);
166
+ mesh.visible = true;
167
+ }
168
+ this.changes++;
169
+ }
120
170
  // Moves a piece into another batch of the same layout (one drawn in another material), copied from buffer to buffer on the card;
121
171
  // returns its id there
122
172
  move(id, to) {
@@ -164,7 +214,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
164
214
  // A piece whose vertices are in place: its id
165
215
  record(piece) {
166
216
  const id = this.spare.length ? this.spare.pop() : this.pieces.length;
167
- this.pieces[id] = { ...piece, shown: true, depth: 0 };
217
+ this.pieces[id] = { ...piece, shown: true, depth: 0, view: null };
168
218
  this.changes++;
169
219
  this.used.vertices += piece.vertexCount;
170
220
  if (this.indices) this.used.indices += piece.count;
@@ -173,6 +223,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
173
223
  }
174
224
  remove(id) {
175
225
  const piece = this.pieces[id];
226
+ if (piece.view) this.setView(id);
176
227
  this.pieces[id] = null;
177
228
  this.spare.push(id);
178
229
  this.changes++;
@@ -207,18 +258,22 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
207
258
  }
208
259
  // The bounds of all pieces, by which Three decides whether the batch is in view at all; with no piece it never is
209
260
  bound() {
210
- const all = new THREE.Sphere(new THREE.Vector3(), -1);
261
+ const all = (this.geometry.boundingSphere ??= new THREE.Sphere());
262
+ all.makeEmpty();
211
263
  for (const piece of this.pieces) if (piece) all.union(piece.sphere);
212
264
  if (all.isEmpty()) all.radius = -Infinity;
213
- this.geometry.boundingSphere = all;
214
- this.boundingSphere = all.clone();
265
+ (this.boundingSphere ??= new THREE.Sphere()).copy(all);
266
+ for (const mesh of this.views.keys()) {
267
+ mesh.geometry = this.geometry;
268
+ mesh.boundingSphere.copy(all);
269
+ }
215
270
  }
216
271
  // Three sorts the opaque things of a pass nearest first by the centre of this sphere, so that what stands in front hides what is
217
272
  // behind before it is shaded: the batch is placed where its nearest piece in the viewer's picture stands, as that piece's own mesh
218
273
  // was, with a radius that still holds every piece (the sphere is also what Three culls the whole batch by)
219
- sortBy(nearest) {
274
+ sortBy(nearest, mesh) {
220
275
  const all = this.geometry.boundingSphere,
221
- at = this.boundingSphere;
276
+ at = mesh.boundingSphere;
222
277
  at.center.copy(nearest.sphere.center);
223
278
  at.radius = all.radius + at.center.distanceTo(all.center);
224
279
  }
@@ -237,9 +292,12 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
237
292
  // Packs the pieces together, one after another, into buffers `room` times what they fill, once they fill less than `use`
238
293
  // of the ones they are in (a buffer only ever grows, and pieces are let go): what each piece holds is copied across on the card,
239
294
  // and its indices are written again from the copy kept here; a batch with no piece left gives its room back. Returns whether it did either.
295
+ needsPack(use = this.fit.use) {
296
+ return this.held.vertices >= PACK_LEAST && this.used.vertices < this.held.vertices * use;
297
+ }
240
298
  pack() {
241
299
  const { vertices: filled, indices: filledIndices } = this.used;
242
- if (this.held.vertices < PACK_LEAST || filled >= this.held.vertices * this.fit.use) return false;
300
+ if (!this.needsPack()) return false;
243
301
  if (!filled) {
244
302
  this.empty();
245
303
  return true;
@@ -313,6 +371,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
313
371
  }
314
372
  gl.bindBuffer(gl.COPY_WRITE_BUFFER, null);
315
373
  this.geometry.boundingSphere = old.boundingSphere;
374
+ for (const mesh of this.views.keys()) mesh.geometry = this.geometry;
316
375
  this.discard(old);
317
376
  }
318
377
  // Frees the batch's buffers on the card, once it is let go
@@ -328,23 +387,26 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
328
387
  }
329
388
  // The pieces a camera sees, nearest first (farthest first in a see-through material): the first becomes the range Three draws,
330
389
  // the others are listed for the multi-draw that follows it
331
- choose(viewer) {
390
+ choose(viewer, mesh = this, pieces = this.pieces) {
332
391
  _view.setFromProjectionMatrix(_clip.multiplyMatrices(viewer.projectionMatrix, viewer.matrixWorldInverse).multiply(this.matrixWorld));
333
392
  const e = _clip.elements;
334
393
  let seen = 0;
335
- for (const piece of this.pieces) {
336
- if (!piece || !piece.shown || !_view.intersectsSphere(piece.sphere)) continue;
337
- const c = piece.sphere.center;
338
- piece.depth = e[2] * c.x + e[6] * c.y + e[10] * c.z + e[14];
394
+ for (const piece of pieces) {
395
+ if (!piece || (mesh === this && piece.view) || !piece.shown || !_view.intersectsSphere(piece.sphere)) continue;
396
+ const centre = piece.sphere.center;
397
+ piece.depth = e[2] * centre.x + e[6] * centre.y + e[10] * centre.z + e[14];
339
398
  _seen[seen++] = piece;
340
399
  }
341
- if (seen > _keys.length) _keys = new Float64Array(2 ** Math.ceil(Math.log2(seen)));
342
- for (let i = 0; i < seen; i++) _keys[i] = Math.max(0, Math.floor((_seen[i].depth - DEPTH_FROM) / DEPTH_STEP)) * PIECES_MOST + i;
343
- _keys.fill(Infinity, seen);
344
- _keys.sort();
345
- const far = this.material.transparent,
346
- first = seen ? nthSeen(0, seen, far) : null;
347
- if (first && camera === viewer && !this.material.transparent) this.sortBy(first);
400
+ if (seen > 1) {
401
+ const size = Math.ceil(Math.log2(seen));
402
+ _keys = keyBuffers[size] ??= new Float64Array(2 ** size);
403
+ for (let i = 0; i < seen; i++) _keys[i] = Math.max(0, Math.floor((_seen[i].depth - DEPTH_FROM) / DEPTH_STEP)) * PIECES_MOST + i;
404
+ _keys.fill(Infinity, seen);
405
+ _keys.sort();
406
+ }
407
+ const far = mesh.material.transparent,
408
+ first = seen > 1 ? nthSeen(0, seen, far) : seen ? _seen[0] : null;
409
+ if (first && camera === viewer && !far) this.sortBy(first, mesh);
348
410
  if (first) this.geometry.setDrawRange(first.start, first.count);
349
411
  else this.geometry.setDrawRange(0, -1); // a range Three takes for nothing to draw
350
412
  this.rest = Math.max(0, seen - 1);
@@ -394,8 +456,11 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
394
456
  }
395
457
  // In a point light's shadow it is drawn only where it casts there, and not where a cached point shadow already contains its current revision
396
458
  onBeforeShadow(_renderer, _object, _camera, shadowCamera, _geometry, drawnWith) {
397
- if (!drawnWith.isMeshDistanceMaterial || (this.pointShadow && !(isStill(this) && keptAway(this, this.changes))))
398
- this.choose(shadowCamera);
459
+ this.chooseShadow(shadowCamera, drawnWith, this, this.pieces);
460
+ }
461
+ chooseShadow(shadowCamera, drawnWith, mesh, pieces) {
462
+ if (!drawnWith.isMeshDistanceMaterial || (this.pointShadow && !(isStill(mesh) && keptAway(mesh, this.changes))))
463
+ this.choose(shadowCamera, mesh, pieces);
399
464
  else {
400
465
  this.geometry.setDrawRange(0, -1);
401
466
  this.rest = 0;
@@ -32,7 +32,7 @@ export function createPlanarReflection({ camera, renderer, scene, drawnSize, wat
32
32
  x1 = -1,
33
33
  y0 = 1,
34
34
  y1 = -1;
35
- for (let c = 0; c < cells.length; c += 2) {
35
+ for (let cellOffset = 0; cellOffset < cells.length; cellOffset += 2) {
36
36
  let left = true, // is the whole cell off one side of the picture?
37
37
  right = true,
38
38
  below = true,
@@ -54,12 +54,12 @@ export function createPlanarReflection({ camera, renderer, scene, drawnSize, wat
54
54
  by = Math.max(by, y);
55
55
  };
56
56
  for (let k = 0; k < 4; k++)
57
- _corner[k].set(cells[c] + (k === 1 || k === 2 ? cellSize : 0), level, cells[c + 1] + (k > 1 ? cellSize : 0), 1).applyMatrix4(view);
57
+ _corner[k].set(cells[cellOffset] + (k === 1 || k === 2 ? cellSize : 0), level, cells[cellOffset + 1] + (k > 1 ? cellSize : 0), 1).applyMatrix4(view);
58
58
  for (let k = 0; k < 4; k++) {
59
- const a = _corner[k],
60
- b = _corner[(k + 1) % 4];
61
- if (a.w > IN_FRONT) take(a);
62
- if (a.w > IN_FRONT !== b.w > IN_FRONT) take(_cut.lerpVectors(a, b, (IN_FRONT - a.w) / (b.w - a.w))); // where the edge passes the camera's plane
59
+ const corner = _corner[k],
60
+ nextCorner = _corner[(k + 1) % 4];
61
+ if (corner.w > IN_FRONT) take(corner);
62
+ if (corner.w > IN_FRONT !== nextCorner.w > IN_FRONT) take(_cut.lerpVectors(corner, nextCorner, (IN_FRONT - corner.w) / (nextCorner.w - corner.w))); // where the edge passes the camera's plane
63
63
  }
64
64
  if (bx < ax || left || right || below || above) continue;
65
65
  x0 = Math.min(x0, ax);
@@ -76,30 +76,30 @@ export function createPlanarReflection({ camera, renderer, scene, drawnSize, wat
76
76
  // Fits the mirror's camera and target to `part`: whole pixels of the target, and a projection that fills just those, so each
77
77
  // reflected thing lands on the pixel it would have in the whole picture.
78
78
  function fitToPart(projection, target) {
79
- const w = target.width,
80
- h = target.height,
81
- px0 = Math.floor(((part.x0 + 1) / 2) * w),
82
- px1 = Math.ceil(((part.x1 + 1) / 2) * w),
83
- py0 = Math.floor(((part.y0 + 1) / 2) * h),
84
- py1 = Math.ceil(((part.y1 + 1) / 2) * h),
85
- x0 = (2 * px0) / w - 1,
86
- x1 = (2 * px1) / w - 1,
87
- y0 = (2 * py0) / h - 1,
88
- y1 = (2 * py1) / h - 1,
89
- e = projection.elements;
79
+ const width = target.width,
80
+ height = target.height,
81
+ px0 = Math.floor(((part.x0 + 1) / 2) * width),
82
+ px1 = Math.ceil(((part.x1 + 1) / 2) * width),
83
+ py0 = Math.floor(((part.y0 + 1) / 2) * height),
84
+ py1 = Math.ceil(((part.y1 + 1) / 2) * height),
85
+ x0 = (2 * px0) / width - 1,
86
+ x1 = (2 * px1) / width - 1,
87
+ y0 = (2 * py0) / height - 1,
88
+ y1 = (2 * py1) / height - 1,
89
+ projectionElements = projection.elements;
90
90
  for (let col = 0; col < 16; col += 4) {
91
- e[col] = (2 * e[col] - (x0 + x1) * e[col + 3]) / (x1 - x0);
92
- e[col + 1] = (2 * e[col + 1] - (y0 + y1) * e[col + 3]) / (y1 - y0);
91
+ projectionElements[col] = (2 * projectionElements[col] - (x0 + x1) * projectionElements[col + 3]) / (x1 - x0);
92
+ projectionElements[col + 1] = (2 * projectionElements[col + 1] - (y0 + y1) * projectionElements[col + 3]) / (y1 - y0);
93
93
  }
94
94
  target.viewport.set(px0, py0, px1 - px0, py1 - py0);
95
95
  target.scissor.set(px0, py0, px1 - px0, py1 - py0);
96
96
  }
97
97
  function sizeMirror() {
98
98
  // half the size the world is drawn at each way: where the quality fit draws it smaller and upscales it, the mirror shrinks with it
99
- const [w, h] = drawnSize();
100
- if (mirror.rt) mirror.rt.setSize(Math.max(minSize, Math.round(w * scale)), Math.max(minSize, Math.round(h * scale)));
99
+ const [width, height] = drawnSize();
100
+ if (mirror.rt) mirror.rt.setSize(Math.max(minSize, Math.round(width * scale)), Math.max(minSize, Math.round(height * scale)));
101
101
  }
102
- function renderMirror(u, wl, k, unseen, frame) {
102
+ function renderMirror(u, waterLevel, k, unseen, frame) {
103
103
  const M = mirror, cp = camera.position;
104
104
  if (M.off) k = 0; // debug switch, for measuring what the mirror costs
105
105
  u.uReflOn.value = k;
@@ -110,28 +110,28 @@ export function createPlanarReflection({ camera, renderer, scene, drawnSize, wat
110
110
  u.uRefl.value = M.rt.texture;
111
111
  sizeMirror();
112
112
  }
113
- const c = M.cam,
114
- o = M.o.set(0, wl, 0);
113
+ const reflectionCamera = M.cam,
114
+ o = M.o.set(0, waterLevel, 0);
115
115
  M.a.subVectors(o, cp).reflect(M.n).negate().add(o);
116
- c.position.copy(M.a);
116
+ reflectionCamera.position.copy(M.a);
117
117
  M.rot.extractRotation(camera.matrixWorld);
118
118
  M.b.set(0, 0, -1).applyMatrix4(M.rot).add(cp);
119
119
  M.a.subVectors(o, M.b).reflect(M.n).negate().add(o);
120
- c.up.set(0, 1, 0).applyMatrix4(M.rot).reflect(M.n);
121
- c.lookAt(M.a);
122
- c.near = camera.near;
123
- c.far = camera.far;
124
- c.updateMatrixWorld();
125
- c.projectionMatrix.copy(camera.projectionMatrix);
120
+ reflectionCamera.up.set(0, 1, 0).applyMatrix4(M.rot).reflect(M.n);
121
+ reflectionCamera.lookAt(M.a);
122
+ reflectionCamera.near = camera.near;
123
+ reflectionCamera.far = camera.far;
124
+ reflectionCamera.updateMatrixWorld();
125
+ reflectionCamera.projectionMatrix.copy(camera.projectionMatrix);
126
126
  u.uReflM.value
127
127
  .set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1)
128
- .multiply(c.projectionMatrix)
129
- .multiply(c.matrixWorldInverse);
130
- const whole = !findWaterPart(M.m.multiplyMatrices(c.projectionMatrix, c.matrixWorldInverse), wl); // no cell found where water was seen: draw it all
128
+ .multiply(reflectionCamera.projectionMatrix)
129
+ .multiply(reflectionCamera.matrixWorldInverse);
130
+ const whole = !findWaterPart(M.m.multiplyMatrices(reflectionCamera.projectionMatrix, reflectionCamera.matrixWorldInverse), waterLevel); // no cell found where water was seen: draw it all
131
131
  // tilt the near plane onto the water, so nothing under the surface gets into the mirror
132
- M.plane.setFromNormalAndCoplanarPoint(M.n, M.o.set(0, wl - 0.05, 0)).applyMatrix4(c.matrixWorldInverse);
132
+ M.plane.setFromNormalAndCoplanarPoint(M.n, M.o.set(0, waterLevel - 0.05, 0)).applyMatrix4(reflectionCamera.matrixWorldInverse);
133
133
  const cl = M.clip.set(M.plane.normal.x, M.plane.normal.y, M.plane.normal.z, M.plane.constant),
134
- pe = c.projectionMatrix.elements,
134
+ pe = reflectionCamera.projectionMatrix.elements,
135
135
  q = M.q;
136
136
  q.x = (Math.sign(cl.x) + pe[8]) / pe[0];
137
137
  q.y = (Math.sign(cl.y) + pe[9]) / pe[5];
@@ -155,11 +155,11 @@ export function createPlanarReflection({ camera, renderer, scene, drawnSize, wat
155
155
  renderer.clear();
156
156
  renderer.setClearColor(_colour, alpha);
157
157
  if (!whole) {
158
- fitToPart(c.projectionMatrix, M.rt);
158
+ fitToPart(reflectionCamera.projectionMatrix, M.rt);
159
159
  M.rt.scissorTest = true;
160
160
  renderer.setRenderTarget(M.rt);
161
161
  }
162
- renderer.render(scene, c);
162
+ renderer.render(scene, reflectionCamera);
163
163
  } finally {
164
164
  renderer.setClearColor(_colour, alpha);
165
165
  renderer.setRenderTarget(previous, face, mip);
@@ -57,7 +57,7 @@ const AO_FS = `/* glsl */ uniform sampler2D tDepth; uniform vec2 uNF, uTan, uPx;
57
57
  // Additive blending can overflow the half-float buffer; one infinite or invalid pixel would be smeared by bloom into a black square,
58
58
  // so both the bloom's input and the final pass make every pixel finite and cap it.
59
59
  const SANE =
60
- 'vec3 sane(vec3 c){ if (!(c.r >= 0.0)) c.r = 0.0; if (!(c.g >= 0.0)) c.g = 0.0; if (!(c.b >= 0.0)) c.b = 0.0; return min(c, vec3(48.0)); }';
60
+ 'vec3 sane(vec3 sampleColor){ if (!(sampleColor.r >= 0.0)) sampleColor.r = 0.0; if (!(sampleColor.g >= 0.0)) sampleColor.g = 0.0; if (!(sampleColor.b >= 0.0)) sampleColor.b = 0.0; return min(sampleColor, vec3(48.0)); }';
61
61
 
62
62
  // Bloom: what is brighter than BLOOM.threshold is blurred at five sizes, from half the frame down to a thirty-second, each level blurred
63
63
  // across and then down with a wider Gaussian (the same blur and weights as Three's UnrealBloomPass), and the final pass adds the five.
@@ -79,12 +79,12 @@ const BLUR_FS = `/* glsl */ uniform sampler2D tSrc; uniform vec2 uStep; uniform
79
79
  // The grade after tone mapping: saturation, a touch of contrast, cool shadows and warm lights, the vignette. Shared by the final
80
80
  // pass and the names drawn after it, so both are graded alike.
81
81
  const GRADE = `/* glsl */ uniform float uVig, uSat;
82
- vec3 gradeTail(vec3 c, vec2 uv){
83
- float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
84
- c = mix(vec3(l), c, uSat);
85
- c = mix(c, c * c * (3.0 - 2.0 * c), 0.16);
86
- c *= mix(vec3(0.95, 0.985, 1.06), vec3(1.045, 1.0, 0.95), smoothstep(0.0, 0.75, l));
87
- vec2 q = uv - 0.5; return c * (1.0 - uVig * smoothstep(0.22, 1.0, dot(q, q) * 2.3)); }`;
82
+ vec3 gradeTail(vec3 sceneColor, vec2 uv){
83
+ float l = dot(sceneColor, vec3(0.2126, 0.7152, 0.0722));
84
+ sceneColor = mix(vec3(l), sceneColor, uSat);
85
+ sceneColor = mix(sceneColor, sceneColor * sceneColor * (3.0 - 2.0 * sceneColor), 0.16);
86
+ sceneColor *= mix(vec3(0.95, 0.985, 1.06), vec3(1.045, 1.0, 0.95), smoothstep(0.0, 0.75, l));
87
+ vec2 q = uv - 0.5; return sceneColor * (1.0 - uVig * smoothstep(0.22, 1.0, dot(q, q) * 2.3)); }`;
88
88
  // A pixel's own noise of half a step of the 8-bit screen, against banding.
89
89
  const DITHER = '(fract(sin(dot(gl_FragCoord.xy + uTime, vec2(12.9898, 78.233))) * 43758.5453) - 0.5) / 255.0';
90
90
 
@@ -94,7 +94,11 @@ const DOF_COC = `/* glsl */ float cocAt(float z){ return min(uDof.y * abs(z - uD
94
94
  const DOF_MIX = `/* glsl */
95
95
  if (uDof.w > 0.0) { soft = texture2D(tDof, vUv).rgb; softShare = smoothstep(0.8, 2.5, cocAt(viewDepth(vUv))) * uDof.w; }`;
96
96
  // ACES fitted curve by Stephen Hill, from Baking Lab (licenses/baking-lab.txt), as used in Three.js (licenses/three.txt).
97
- const ACES = `/* glsl */ vec3 fit(vec3 v){ vec3 a = v * (v + 0.0245786) - 0.000090537; vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081; return a / b; }
97
+ const ACES = `/* glsl */ vec3 fit(vec3 exposedColor){
98
+ vec3 numerator = exposedColor * (exposedColor + 0.0245786) - 0.000090537;
99
+ vec3 denominator = exposedColor * (0.983729 * exposedColor + 0.4329510) + 0.238081;
100
+ return numerator / denominator;
101
+ }
98
102
  vec3 acesCurve(vec3 c){
99
103
  const mat3 mi = mat3(vec3(0.59719, 0.07600, 0.02840), vec3(0.35458, 0.90834, 0.13383), vec3(0.04823, 0.01566, 0.83777));
100
104
  const mat3 mo = mat3(vec3(1.60475, -0.10208, -0.00327), vec3(-0.53108, 1.10813, -0.07276), vec3(-0.07367, -0.00605, 1.07602));
@@ -173,11 +177,11 @@ ${STEADY}
173
177
  // Edge adaptation and sharpening follow AMD FidelityFX Super Resolution 1 (licenses/fidelityfx-fsr.txt).
174
178
  // A sharpening held within its neighbours (as FSR 1's RCAS): e is pushed away from the four round it (b above, d left, f right, h below)
175
179
  // by up to sharp (0 to 1), only as far as keeps it inside their range, so edges come back crisp without halos.
176
- const SHARPEN = `/* glsl */ vec3 sharpen(vec3 b, vec3 d, vec3 e, vec3 f, vec3 h, float sharp){
177
- vec3 mn = min(min(b, d), min(f, h)), mx = max(max(b, d), max(f, h));
178
- vec3 lobes = max(-min(mn, e) / (4.0 * mx + 1e-5), (1.0 - max(mx, e)) / (4.0 * mn - 4.0 - 1e-5));
180
+ const SHARPEN = `/* glsl */ vec3 sharpen(vec3 upperColor, vec3 leftColor, vec3 centerColor, vec3 rightColor, vec3 lowerColor, float sharp){
181
+ vec3 neighbourMin = min(min(upperColor, leftColor), min(rightColor, lowerColor)), neighbourMax = max(max(upperColor, leftColor), max(rightColor, lowerColor));
182
+ vec3 lobes = max(-min(neighbourMin, centerColor) / (4.0 * neighbourMax + 1e-5), (1.0 - max(neighbourMax, centerColor)) / (4.0 * neighbourMin - 4.0 - 1e-5));
179
183
  float lobe = max(-0.1875, min(max(lobes.r, max(lobes.g, lobes.b)), 0.0)) * sharp;
180
- return (lobe * (b + d + f + h) + e) / (4.0 * lobe + 1.0); }`;
184
+ return (lobe * (upperColor + leftColor + rightColor + lowerColor) + centerColor) / (4.0 * lobe + 1.0); }`;
181
185
  // The present pass, with temporal anti-aliasing: the running picture sharpened a little (a running picture is a little softer than one
182
186
  // frame; where the upscale follows, its own sharpening does this), tone-mapped, graded and encoded for the screen, with its noise and
183
187
  // the depth.
@@ -200,7 +204,7 @@ const PRESENT_FS = `/* glsl */ uniform sampler2D tSrc, tDepth; uniform vec2 uPx;
200
204
  // Works on the graded picture, where steps of light are as the eye sees them.
201
205
  const EASU_FS = `/* glsl */ uniform sampler2D tSrc; uniform vec2 uSrcSize; varying vec2 vUv;
202
206
  vec3 tap(vec2 p){ return texture2D(tSrc, (p + 0.5) / uSrcSize).rgb; }
203
- float luma(vec3 c){ return c.g + 0.5 * (c.r + c.b); }
207
+ float luma(vec3 color){ return color.g + 0.5 * (color.r + color.b); }
204
208
  // the edge at one of the four central texels, from its four neighbours, weighted by the sample's nearness to it: its direction, and how
205
209
  // much it is an edge (a step on one side only) rather than a thin line or noise (steps both ways)
206
210
  void edge(inout vec2 dir, inout float len, float w, float up, float left, float mid, float right, float down){