roamwright 0.58.0 → 0.59.0

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.
@@ -0,0 +1,333 @@
1
+ import * as THREE from 'three';
2
+
3
+ /**
4
+ * The vertex stage of bedded rock laid over a land in tiles (`createStrataTiles`): it moves each vertex between levels of
5
+ * detail as the eye nears (geomorphing, so nothing jumps and neighbouring tiles at different levels meet without cracks), makes
6
+ * the rock ride on whatever level the terrain chunk under it is drawing (so it is never swallowed or left floating), and hides
7
+ * a tile's vertices in every mesh but the one that draws its level. One program draws every level (`uLevel`, the material's
8
+ * own): a coarser level's mesh lacks the finer levels' attributes, which only the finer levels' branches read.
9
+ *
10
+ * The uniforms are {@link createStrataCliffs}'s `uniforms`, shared by its three materials.
11
+ *
12
+ * @param {object} options
13
+ * @param {number} options.half - Half the land's size in metres; the land is centred on the origin.
14
+ * @param {number} options.heightSide - Cells along each side of the land's height grid; its texture holds one point more.
15
+ * @param {number} options.heightSpacing - Metres between two points of the height grid.
16
+ * @param {number} options.chunkMetres - Metres along a side of the terrain's finest chunks, which are drawn coarser with distance.
17
+ * @param {number} options.tilesSide - Rock tiles along each side of the land.
18
+ * @returns {string} GLSL for the head of a vertex shader: the attributes, `cliffMorph()` and the scratch it fills.
19
+ */
20
+ export function strataVertexGLSL({ half, heightSide, heightSpacing, chunkMetres, tilesSide }) {
21
+ return `/* glsl */
22
+ attribute vec3 aParam; attribute vec4 aRock; attribute float aYY;
23
+ attribute vec3 aM1, aN1, aM2, aN2;
24
+ uniform vec3 uEye, uLodD; uniform vec2 uR; uniform sampler2D uShown, uHM; uniform int uLevel;
25
+ vec3 cP, cN; float cHide;
26
+ float cliffH(ivec2 c) { return texelFetch(uHM, clamp(c, ivec2(0), ivec2(${heightSide})), 0).r; }
27
+ float cliffTri(vec2 p, int s) {
28
+ vec2 g = (p + ${half.toFixed(1)}) / (${heightSpacing.toFixed(6)} * float(s)), i = floor(g), t = g - i; ivec2 a = ivec2(i) * s;
29
+ float h00 = cliffH(a), h10 = cliffH(a + ivec2(s, 0)), h01 = cliffH(a + ivec2(0, s)), h11 = cliffH(a + ivec2(s, s));
30
+ return t.x + t.y <= 1.0 ? h00 + (h10 - h00) * t.x + (h01 - h00) * t.y : h11 + (h01 - h11) * (1.0 - t.x) + (h10 - h11) * (1.0 - t.y);
31
+ }
32
+ void cliffMorph() {
33
+ if (uLevel == 0) {
34
+ float d = distance(uEye, aM2), m0 = smoothstep(uR.x * 0.65, uR.x, d), m1 = smoothstep(uR.y * 0.65, uR.y, d);
35
+ cP = mix(mix(position, aM1, m0), aM2, m1); cN = normalize(mix(mix(normal, aN1, m0), aN2, m1));
36
+ } else if (uLevel == 1) {
37
+ float m1 = smoothstep(uR.y * 0.65, uR.y, distance(uEye, aM1));
38
+ cP = mix(position, aM1, m1); cN = normalize(mix(normal, aN1, m1));
39
+ } else {
40
+ cP = position; cN = normal;
41
+ }
42
+ float ch = ${chunkMetres.toFixed(4)}; // the terrain chunk under this point, and the level it is drawn at, as the terrain chooses it
43
+ vec2 cc = (floor((aParam.xy + ${half.toFixed(1)}) / ch) + 0.5) * ch - ${half.toFixed(1)}, dd = max(abs(uEye.xz - cc) - ch * 0.5, 0.0);
44
+ float dl = length(vec3(dd, max(0.0, uEye.y - 120.0) * 0.6));
45
+ int s = dl < uLodD.x ? 1 : dl < uLodD.y ? 2 : dl < uLodD.z ? 4 : 8;
46
+ if (s > 1) cP.y += cliffTri(aParam.xy, s) - cliffTri(aParam.xy, 1);
47
+ int t = int(aParam.z + 0.5);
48
+ cHide = abs(texelFetch(uShown, ivec2(t % ${tilesSide}, t / ${tilesSide}), 0).r - float(uLevel)) > 0.5 ? 1.0 : 0.0;
49
+ }`;
50
+ }
51
+
52
+ /**
53
+ * The rock of a land in tiles at three levels of detail, chosen by each tile's distance from the eye: the finest within
54
+ * `reach[0]`, the middle one within `reach[1]`, the coarse one beyond. The coarse level of every tile is built when the land
55
+ * begins (by a worker pool where there is one, else on the page) and meshed as it comes back; the finer levels are built when
56
+ * first needed, a few boxes asked of the pool at once or, on the page, a slice of a box a frame within a frame budget. A mesh
57
+ * holds many tiles: a small table says which level each tile shows, and the vertex stage hides a tile's vertices in every mesh
58
+ * but the one that draws its level. Fine meshes long out of reach are let go.
59
+ *
60
+ * Every level casts the shadow of the tiles it shows (the depth material hides the rest as the picture's does). The meshes are
61
+ * drawn before the terrain and leave a mirror's layer alone (layer 1).
62
+ *
63
+ * @param {object} options
64
+ * @param {ReturnType<import('../geometry/strata-tiles.js').createStrataTiles>} options.tiles - The rock's tiles and boxes of
65
+ * tiles (`createStrataTiles`).
66
+ * @param {ReturnType<import('../geometry/strata-field.js').createStrataField>} options.field - The rock's shape
67
+ * (`createStrataField`): where it stands and the surface point of each level.
68
+ * @param {number} options.half - Half the land's size in metres; the land is centred on the origin.
69
+ * @param {{ data: Float32Array, side: number, spacing: number }} options.heights - The ground's heights as the page has them
70
+ * once coloured (one value per point of a square grid of `side` cells, `spacing` metres apart), read by the vertex stage.
71
+ * @param {(x: number, z: number) => number} options.terrain - The terrain's height at a place, in metres.
72
+ * @param {number[]} [options.reach=[45, 160]] - Metres from the eye within which the finest and the middle levels are drawn.
73
+ * @param {{ reach: number[], chunkMetres: number }} [options.terrainDetail] - The terrain's own levels: the distances in metres
74
+ * at which its chunks are drawn coarser, and the metres of its finest chunk.
75
+ * @param {{ position: import('three').Vector3 }} options.camera - The eye.
76
+ * @param {import('three').Object3D} options.parent - What the meshes join.
77
+ * @param {(options: { level: number, uniforms: object, vertex: string }) => { material: import('three').Material, depth: import('three').Material }} options.material -
78
+ * The picture's material and shadow-depth material of one level, made for `level` with the shared uniforms and the vertex
79
+ * stage (`createStrataMaterial`).
80
+ * @param {() => number} [options.lodScale=() => 1] - A quality setting that stretches or shrinks every distance.
81
+ * @param {{ pooled: () => boolean, size: () => number, prepare: Function, run: Function, spread: Function }} [options.pool] -
82
+ * A worker pool (`createPool`): without one, or once one fails, every box is built on the page.
83
+ * @param {{ task: Function }} [options.budget] - A frame budget (`createFrameBudget`) that spreads the page's building over frames.
84
+ * @param {{ preparation: string, plan: string, box: string }} [options.jobs] - The pool's job names: the preparation that gives a
85
+ * worker the ground, the plan a worker hands back, and a box of tiles at a level.
86
+ * @param {() => object} [options.preparation] - What a worker is given by the preparation job: the ground as the page has it,
87
+ * and what the rock is planned from.
88
+ * @param {number} [options.preparationCost=8] - The preparation's weight among the pool's ordinary jobs.
89
+ * @param {() => void} [options.planHere] - Plans the rock on the page: where it stands and its tiles.
90
+ * @param {(plan: object) => void} [options.takePlan] - Takes a worker's plan on the page.
91
+ * @param {number} [options.mostAsked=4] - Boxes asked of the pool at once while flying.
92
+ * @param {(ground: (x: number, z: number) => number) => void} [options.onBuilt] - Called once the materials are made, with the
93
+ * ground to stand on over the rock ({@link createStrataCliffs}'s `ground`).
94
+ * @returns {{ preparation: string, begin: Function, planned: Function, build: Function, update: Function, busy: Function,
95
+ * ground: Function, uniforms: object, vertex: string }} `begin()`: shapes the rock and begins the coarse level of every tile, as
96
+ * soon as the ground is coloured; `planned()`: the promise of the plan; `build()`: the promise of the coarse level's meshes,
97
+ * begun once the plan stands; `update()`: each frame's choice of levels and slice of building; `busy()`: whether a box is
98
+ * being built; `ground(x, z)`: the rock's surface where a cliff stands proud of the terrain, else the terrain's height.
99
+ */
100
+ export function createStrataCliffs({
101
+ tiles,
102
+ field,
103
+ half,
104
+ heights,
105
+ terrain,
106
+ reach = [45, 160],
107
+ terrainDetail = { reach: [330, 680, 1250], chunkMetres: 64 * heights.spacing },
108
+ camera,
109
+ parent,
110
+ material,
111
+ lodScale = () => 1,
112
+ pool = { pooled: () => false, size: () => 0, prepare() {}, run: () => Promise.reject(), spread() {} },
113
+ budget = {
114
+ task:
115
+ step =>
116
+ (...args) => (step(...args), true),
117
+ }, // without a frame budget, a box is built whole
118
+ jobs = { preparation: 'strata ground', plan: 'strata plan', box: 'strata box' },
119
+ preparation = () => ({}),
120
+ preparationCost = 8,
121
+ planHere = () => {},
122
+ takePlan = () => {},
123
+ mostAsked = 4,
124
+ onBuilt = () => {},
125
+ }) {
126
+ const { tileSize: TILE, tilesSide: TILES_SIDE, boxArrays, boxKey, boxNow, tilesIn } = tiles;
127
+ const { cliffMask, cliffPoint } = field;
128
+ const boxes = [new Map(), new Map(), new Map()]; // built meshes per level, by box
129
+ const vertex = strataVertexGLSL({
130
+ half,
131
+ heightSide: heights.side,
132
+ heightSpacing: heights.spacing,
133
+ chunkMetres: terrainDetail.chunkMetres,
134
+ tilesSide: TILES_SIDE,
135
+ });
136
+ const uniforms = {
137
+ uEye: { value: new THREE.Vector3() },
138
+ uR: { value: new THREE.Vector2() },
139
+ uLodD: { value: new THREE.Vector3() },
140
+ uShown: { value: null },
141
+ uHM: { value: null },
142
+ };
143
+ const shown = new Float32Array(TILES_SIDE * TILES_SIDE).fill(3);
144
+ const tileById = new Map();
145
+ const asked = new Set(); // the boxes being built, by level and key ('1/3:4'), until their meshes stand
146
+ const answers = []; // boxes the pool has built, to be meshed one a frame: [level, key, arrays]
147
+ let coarse = null, // the promise of the coarse level's arrays, box by box, once begun
148
+ planned = null, // the promise of the plan: where the rock stands and its tiles
149
+ mats = null,
150
+ job = null, // a box the page builds itself, a slice a frame: { lv, key, it }
151
+ onPage = !pool.pooled(); // true once boxes are built on the page alone (no workers, or one could not build a box)
152
+
153
+ // A box's mesh from its arrays (createStrataTiles), and its tiles' heights for choosing their level.
154
+ function meshBox(lv, key, { attributes, index, bounds }) {
155
+ for (let i = 0; i < bounds.length; i += 3) {
156
+ const t = tileById.get(bounds[i]);
157
+ t.y0 = Math.min(t.y0, bounds[i + 1]);
158
+ t.y1 = Math.max(t.y1, bounds[i + 2]);
159
+ }
160
+ const geo = new THREE.BufferGeometry();
161
+ for (const [name, [array, size]] of Object.entries(attributes)) geo.setAttribute(name, new THREE.BufferAttribute(array, size));
162
+ geo.setIndex(new THREE.BufferAttribute(index, 1));
163
+ geo.computeBoundingSphere();
164
+ geo.boundingSphere.radius += 8;
165
+ const mesh = new THREE.Mesh(geo, mats[lv].material);
166
+ mesh.customDepthMaterial = mats[lv].depth;
167
+ mesh.castShadow = true;
168
+ mesh.receiveShadow = true;
169
+ mesh.layers.set(1);
170
+ mesh.matrixAutoUpdate = false;
171
+ mesh.visible = false;
172
+ mesh.renderOrder = -1; // drawn before the terrain, so the ground it covers is not shaded for nothing
173
+ parent.add(mesh);
174
+ boxes[lv].set(key, { key, mesh, list: tilesIn(lv, key) });
175
+ }
176
+ // A box built on the page, as a generator that yields now and then so the work spreads over frames.
177
+ function* buildBox(lv, key) {
178
+ meshBox(lv, key, yield* boxArrays(lv, tilesIn(lv, key)));
179
+ }
180
+ // A box's arrays from the pool, or from the page where the pool cannot build it.
181
+ function askPool(lv, key) {
182
+ return pool.run(jobs.box, { lv, key }, [], jobs.preparation).catch(() => {
183
+ onPage = true;
184
+ return boxNow(lv, key);
185
+ });
186
+ }
187
+
188
+ // Shapes the rock and begins the coarse level of every tile: as soon as the ground is coloured, so that the pool's workers
189
+ // plan the rock and build those boxes while the page goes on with the land's other builders. The page takes the plan from
190
+ // the worker that made it (or makes it itself where there are none).
191
+ function begin() {
192
+ // what a worker shapes the rock from, as the page has it now (a worker works the normals and slopes out from the heights:
193
+ // less to copy each time this is sent)
194
+ if (!onPage) pool.prepare(jobs.preparation, preparation(), preparationCost);
195
+ planned = onPage
196
+ ? Promise.resolve(planHere())
197
+ : pool.run(jobs.plan, null, [], jobs.preparation).then(
198
+ plan => takePlan(plan),
199
+ () => {
200
+ onPage = true;
201
+ planHere();
202
+ },
203
+ );
204
+ // what stands on the plan beside the rock may be placed side by side: a second worker holds it
205
+ if (!onPage) pool.spread(jobs.preparation, pool.size() > 2 ? 2 : 1);
206
+ coarse = planned.then(() => {
207
+ for (const t of tiles.tiles) tileById.set(t.id, t);
208
+ const keys = [...new Set(tiles.tiles.map(t => boxKey(t, 2)))];
209
+ return Promise.all(keys.map(key => (onPage ? boxNow(2, key) : askPool(2, key)))).then(arrays => [keys, arrays]);
210
+ });
211
+ }
212
+ // Kept once the plan of the rock is on the page: what reads it (the rock's own meshes and ground, and whatever else is kept
213
+ // off it) waits for it.
214
+ function plannedOnce() {
215
+ if (!planned) begin();
216
+ return planned;
217
+ }
218
+ // The rock's materials and ground; the promise is kept once the coarse level stands, meshed in the order of its boxes.
219
+ function build() {
220
+ const hm = new THREE.DataTexture(heights.data, heights.side + 1, heights.side + 1, THREE.RedFormat, THREE.FloatType);
221
+ hm.needsUpdate = true;
222
+ const sh = new THREE.DataTexture(shown, TILES_SIDE, TILES_SIDE, THREE.RedFormat, THREE.FloatType);
223
+ sh.needsUpdate = true;
224
+ uniforms.uHM.value = hm;
225
+ uniforms.uShown.value = sh;
226
+ mats = [0, 1, 2].map(level => material({ level, uniforms, vertex }));
227
+ onBuilt(ground);
228
+ return coarse.then(([keys, arrays]) => {
229
+ keys.forEach((key, i) => meshBox(2, key, arrays[i]));
230
+ });
231
+ }
232
+ // The ground is the rock where a cliff stands proud of the terrain, so nobody walks inside it: find the point of the rock
233
+ // surface (at the 1 m level) that lies over (x, z) by stepping its ground point until it lands there.
234
+ const gp = { p: [0, 0, 0] };
235
+ function ground(x, z) {
236
+ const t = terrain(x, z);
237
+ if (cliffMask(x, z) < 0.005) return t;
238
+ let qx = x,
239
+ qz = z;
240
+ for (let i = 0; i < 4; i++) {
241
+ cliffPoint(qx, qz, 1, gp);
242
+ qx += x - gp.p[0];
243
+ qz += z - gp.p[2];
244
+ }
245
+ return Math.max(t, gp.p[1]);
246
+ }
247
+
248
+ // Each frame: which level each tile wants by its distance, which it can show (a finer level may still be building), and a
249
+ // slice of building.
250
+ const eye = new THREE.Vector3();
251
+ // A tile's box at each level, worked out once: the key is text, and was made anew for every tile at every frame
252
+ const keyOf = (t, lv) => (t.keys ??= [boxKey(t, 0), boxKey(t, 1), boxKey(t, 2)])[lv];
253
+ // Whether every tile of a box lies beyond `reach` (a loop: a closure for every box at every frame made garbage)
254
+ function allBeyond(list, reach) {
255
+ for (let i = 0; i < list.length; i++) if (list[i].d <= reach) return false;
256
+ return true;
257
+ }
258
+ function update() {
259
+ if (!mats) return;
260
+ eye.copy(camera.position);
261
+ uniforms.uEye.value.copy(eye);
262
+ const scale = lodScale(),
263
+ r0 = reach[0] * scale,
264
+ r1 = reach[1] * scale,
265
+ [near, middle, far] = terrainDetail.reach;
266
+ uniforms.uR.value.set(r0, r1);
267
+ uniforms.uLodD.value.set(near * scale, middle * scale, far * scale);
268
+ let need = null,
269
+ needD = 1e9,
270
+ changed = false;
271
+ for (const b of boxes[0].values()) b.mesh.visible = false;
272
+ for (const b of boxes[1].values()) b.mesh.visible = false;
273
+ for (const b of boxes[2].values()) b.mesh.visible = false;
274
+ for (const t of tiles.tiles) {
275
+ const dx = Math.max(t.x0 - 6 - eye.x, 0, eye.x - t.x0 - TILE - 6),
276
+ dz = Math.max(t.z0 - 6 - eye.z, 0, eye.z - t.z0 - TILE - 6),
277
+ dy = Math.max(t.y0 - 6 - eye.y, 0, eye.y - t.y1 - 6);
278
+ const d = Math.sqrt(dx * dx + dy * dy + dz * dz),
279
+ want = d < r0 ? 0 : d < r1 ? 1 : 2;
280
+ let lv = want;
281
+ while (lv < 2 && !boxes[lv].has(keyOf(t, lv))) {
282
+ if (d < needD && !asked.has(lv + '/' + keyOf(t, lv))) {
283
+ need = { lv, key: keyOf(t, lv) };
284
+ needD = d;
285
+ }
286
+ lv++;
287
+ }
288
+ if (shown[t.id] !== lv) {
289
+ shown[t.id] = lv;
290
+ changed = true;
291
+ }
292
+ boxes[lv].get(keyOf(t, lv)).mesh.visible = true;
293
+ t.d = d;
294
+ }
295
+ if (changed) uniforms.uShown.value.needsUpdate = true;
296
+ buildNeeded(need);
297
+ for (let lv = 0; lv < 2; lv++)
298
+ for (const b of boxes[lv].values()) {
299
+ // release fine meshes long out of reach
300
+ if (allBeyond(b.list, lv ? r1 + 250 : r0 + 120)) {
301
+ b.mesh.removeFromParent();
302
+ b.mesh.geometry.dispose();
303
+ boxes[lv].delete(b.key);
304
+ }
305
+ }
306
+ }
307
+ // Builds the finer boxes the tiles near the eye need: asked of the pool, a few at once, and meshed one a frame as they come
308
+ // back; or on the page, a few milliseconds a frame.
309
+ function buildNeeded(need) {
310
+ if (need && (onPage ? !job : asked.size < mostAsked)) {
311
+ const { lv, key } = need;
312
+ asked.add(lv + '/' + key);
313
+ if (onPage) job = { lv, key, it: buildBox(lv, key) };
314
+ else askPool(lv, key).then(arrays => answers.push([lv, key, arrays]));
315
+ }
316
+ if (answers.length) installAnswer();
317
+ while (job && buildNextTile());
318
+ }
319
+ const installAnswer = budget.task(() => {
320
+ const answer = answers.shift();
321
+ meshBox(...answer);
322
+ asked.delete(answer[0] + '/' + answer[1]);
323
+ });
324
+ const buildNextTile = budget.task(() => {
325
+ if (job.it.next().done) {
326
+ asked.delete(job.lv + '/' + job.key);
327
+ job = null;
328
+ }
329
+ });
330
+ const busy = () => asked.size > 0;
331
+
332
+ return { preparation: jobs.preparation, begin, planned: plannedOnce, build, update, busy, ground, uniforms, vertex };
333
+ }
@@ -0,0 +1,58 @@
1
+ import * as THREE from 'three';
2
+ import { SRGB2LIN } from '../math/color.js';
3
+ import { TRS } from '../geometry/primitives.js';
4
+
5
+ /** Broken stone weathered grey, in linear light (0.25 read near white in the sun, 0.17 near black). */
6
+ export const TALUS_STONE = [0.22, 0.203, 0.182];
7
+
8
+ /**
9
+ * Put a talus in the world: the stones `planTalusStones` planned, each cell and kind as a near and a far copy of one
10
+ * shape that share their places, tints and bounds, for a level of detail that swaps between them (`cells`).
11
+ *
12
+ * @param {object} options
13
+ * @param {Map<string, number[]>} options.plan - `planTalusStones`'s.
14
+ * @param {{ stone: [import('three').BufferGeometry, import('three').BufferGeometry], block: [import('three').BufferGeometry, import('three').BufferGeometry] }} options.shapes -
15
+ * Each kind's stone, near and far (a coarse copy for afar).
16
+ * @param {import('three').Material} options.material - What draws them, with room for each copy's own colour.
17
+ * @param {import('three').Object3D} options.parent - What the meshes join.
18
+ * @param {object[]} options.cells - The list a level of detail reads; a cell `{ mesh, lo, full, cx, cz, r, until }` is added
19
+ * to it for each pair of meshes.
20
+ * @param {(cell: number, out: number[]) => number[]} options.groundTint - Writes the ground's sRGB colour of the grid's cell
21
+ * `cell` into `out`: a stone takes a little of the ground's colour.
22
+ * @param {number[]} [options.stone=TALUS_STONE] - The stone's own colour, linear.
23
+ * @param {number} [options.until=320] - Metres from the eye beyond which the near copies are not drawn.
24
+ */
25
+ export function meshTalusStones({ plan, shapes, material, parent, cells, groundTint, stone = TALUS_STONE, until = 320 }) {
26
+ const colour = new THREE.Color(), // scratch value of this call
27
+ tint = [0, 0, 0];
28
+ for (const [key, list] of plan) {
29
+ const [near, far] = shapes[key.endsWith('block') ? 'block' : 'stone'];
30
+ const mesh = new THREE.InstancedMesh(near, material, list.length),
31
+ lo = new THREE.InstancedMesh(far, material, list.length);
32
+ for (let i = 0; i < list.length; i++) {
33
+ const [x, y, z, s, turn, tiltX, tiltZ, shade, cell] = list[i];
34
+ mesh.setMatrixAt(i, TRS(x, y, z, s, s * (0.62 + 0.3 * shade), s * (0.75 + 0.3 * tiltX + 0.3), turn, tiltX, tiltZ));
35
+ groundTint(cell, tint);
36
+ // the grey of the cliff, a little of the ground's colour in it
37
+ mesh.setColorAt(
38
+ i,
39
+ colour.setRGB(
40
+ (0.75 * stone[0] + 0.25 * SRGB2LIN[tint[0]]) * shade,
41
+ (0.75 * stone[1] + 0.25 * SRGB2LIN[tint[1]]) * shade,
42
+ (0.75 * stone[2] + 0.25 * SRGB2LIN[tint[2]]) * shade,
43
+ ),
44
+ );
45
+ }
46
+ mesh.computeBoundingSphere();
47
+ mesh.castShadow = mesh.receiveShadow = true;
48
+ lo.instanceMatrix = mesh.instanceMatrix;
49
+ lo.instanceColor = mesh.instanceColor;
50
+ lo.boundingSphere = mesh.boundingSphere;
51
+ lo.receiveShadow = true;
52
+ lo.visible = false;
53
+ mesh.matrixAutoUpdate = lo.matrixAutoUpdate = false;
54
+ parent.add(mesh, lo);
55
+ const { center, radius } = mesh.boundingSphere;
56
+ cells.push({ mesh, lo, full: list.length, cx: center.x, cz: center.z, r: radius, until });
57
+ }
58
+ }
@@ -0,0 +1,76 @@
1
+ import * as THREE from 'three';
2
+ import { lerp } from '../math/scalar.js';
3
+ import { geometryView } from '../geometry/builder.js';
4
+ import { TRS } from '../geometry/primitives.js';
5
+ import { STREAM_BANKS } from '../geometry/stream-banks.js';
6
+
7
+ /**
8
+ * The tints of a stream bank's stones and driftwood, in linear light: stone at the waterline, stone above it, and bleached wood.
9
+ */
10
+ export const STREAM_BANK_COLOURS = Object.freeze({ wet: [0.2, 0.2, 0.19], dry: [0.38, 0.36, 0.32], driftwood: [0.42, 0.4, 0.36] });
11
+
12
+ /**
13
+ * Put a stream's banks in the world from `planStreamBanks`'s plan: one mesh of stones and one of driftwood to each river
14
+ * that has them, each stone a copy of one rock stretched along its bed and tinted from dry to wet, each trunk a copy of one
15
+ * cylinder lying along its bar.
16
+ *
17
+ * @param {object} options
18
+ * @param {{ stones: number[], logs: number[] }[]} options.plans - `planStreamBanks`'s, a river to an entry.
19
+ * @param {{ geometry: import('three').BufferGeometry, material: import('three').Material }} options.stone - The rock a stone is a
20
+ * copy of, and what draws it with room for each copy's own colour.
21
+ * @param {{ geometry: import('three').BufferGeometry, material: import('three').Material }} options.log - The cylinder a trunk is
22
+ * a copy of, and what draws it.
23
+ * @param {import('three').Object3D} options.parent - What the meshes join.
24
+ * @param {{ wet: number[], dry: number[], driftwood: number[] }} [options.colours=STREAM_BANK_COLOURS] - The tints, linear.
25
+ * @param {number} [options.long=STREAM_BANKS.long] - How many times as long as it is across a stone stands.
26
+ */
27
+ export function meshStreamBanks({ plans, stone, log, parent, colours = STREAM_BANK_COLOURS, long = STREAM_BANKS.long }) {
28
+ const colour = new THREE.Color(), // scratch value of this call
29
+ { wet, dry, driftwood } = colours;
30
+ for (const { stones, logs } of plans) {
31
+ const count = stones.length / 9;
32
+ if (!count) continue;
33
+ const mesh = new THREE.InstancedMesh(geometryView(stone.geometry), stone.material, count);
34
+ for (let i = 0; i < count; i++) {
35
+ const at = i * 9,
36
+ x = stones[at],
37
+ y = stones[at + 1],
38
+ z = stones[at + 2],
39
+ size = stones[at + 3],
40
+ turn = stones[at + 4],
41
+ tilt = stones[at + 5],
42
+ wetness = stones[at + 6],
43
+ shade = stones[at + 7],
44
+ tall = stones[at + 8];
45
+ mesh.setMatrixAt(i, TRS(x, y, z, size * long, size * tall, size, turn, tilt, tilt * 0.6));
46
+ mesh.setColorAt(
47
+ i,
48
+ colour.setRGB(lerp(dry[0], wet[0], wetness) * shade, lerp(dry[1], wet[1], wetness) * shade, lerp(dry[2], wet[2], wetness) * shade),
49
+ );
50
+ }
51
+ mesh.castShadow = mesh.receiveShadow = true;
52
+ mesh.matrixAutoUpdate = false;
53
+ mesh.computeBoundingSphere();
54
+ parent.add(mesh);
55
+ const drift = logs.length / 7;
56
+ if (!drift) continue;
57
+ // driftwood: a bleached trunk lying along the bar, its root end towards the current
58
+ const wood = new THREE.InstancedMesh(geometryView(log.geometry), log.material, drift);
59
+ for (let i = 0; i < drift; i++) {
60
+ const at = i * 7,
61
+ x = logs[at],
62
+ y = logs[at + 1],
63
+ z = logs[at + 2],
64
+ length = logs[at + 3],
65
+ turn = logs[at + 4],
66
+ thick = logs[at + 5],
67
+ shade = logs[at + 6];
68
+ wood.setMatrixAt(i, TRS(x, y, z, thick, length, thick, turn, Math.PI / 2 + 0.06, 0));
69
+ wood.setColorAt(i, colour.setRGB(driftwood[0], driftwood[1], driftwood[2]).multiplyScalar(shade));
70
+ }
71
+ wood.castShadow = wood.receiveShadow = true;
72
+ wood.matrixAutoUpdate = false;
73
+ wood.computeBoundingSphere();
74
+ parent.add(wood);
75
+ }
76
+ }