roamwright 0.61.30 → 0.61.31

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.30",
3
+ "version": "0.61.31",
4
4
  "description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
5
5
  "keywords": [
6
6
  "threejs",
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import * as THREE from 'three';
9
+ import { geometryView } from '../geometry/builder.js';
9
10
  import { clamp, TAU } from '../math/scalar.js';
10
11
  import { createHash } from '../math/random.js';
11
12
  import { SHOULDERS } from '../motion/figure-bones.js';
@@ -26,6 +27,7 @@ import {
26
27
  crowdGeometry,
27
28
  crowdRig,
28
29
  } from './crowd-rig.js';
30
+ import { onCardOnly } from './textures.js';
29
31
  import { applyCrowdSkinning, bakeCrowdFrame, castCrowdShadow, createCrowdBatch, flushCrowdBatch } from './crowd-skinning.js';
30
32
 
31
33
  const _cc = new THREE.Color();
@@ -161,6 +163,7 @@ export function createLookPicker({
161
163
  * baked distant walks, lazily raised near look batches, and worker look orders.
162
164
  *
163
165
  * @param {object} config
166
+ * @param {boolean} [config.releaseWalkPixels=false] - Drop baked gait pixels on upload when the world recreates its renderer on context loss.
164
167
  * @param {THREE.Object3D} config.scene Scene receiving instanced crowd meshes.
165
168
  * @param {() => THREE.Material} [config.createColourMaterial] Factory returning a fresh base colour material to patch with crowd skinning.
166
169
  * @param {(look: object, seed: number, near: boolean, bodies: object[]) => object} config.buildFigure Builds a rigged figure from its far body.
@@ -183,6 +186,7 @@ export function createLookPicker({
183
186
  */
184
187
  export function createCrowdBatches({
185
188
  scene,
189
+ releaseWalkPixels = false,
186
190
  createColourMaterial = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.88, side: THREE.DoubleSide }),
187
191
  buildFigure,
188
192
  buildCrowdLook,
@@ -277,7 +281,9 @@ export function createCrowdBatches({
277
281
  }
278
282
 
279
283
  function bakeWalksOnce(fars) {
280
- if (!walkTextures.length) walkTextures = bakeCrowdWalks(fars, lookFigure(0, ...looks[0]), crowdPose);
284
+ if (walkTextures.length) return;
285
+ walkTextures = bakeCrowdWalks(fars, lookFigure(0, ...looks[0]), crowdPose);
286
+ if (releaseWalkPixels) for (const texture of walkTextures) onCardOnly(texture);
281
287
  }
282
288
 
283
289
  function raiseLook(v, batches) {
@@ -295,8 +301,8 @@ export function createCrowdBatches({
295
301
  });
296
302
  v.lod = v.size
297
303
  ? geos.map((geo, level) => {
298
- const batch = createCrowdBatch(scene, geo.clone(), v.size, v.mat, v.casting, 'Crowd ' + v.kind + LEVELS[level], false);
299
- castCrowdShadow(scene, batch, geos[2].clone(), v.casting, v.size);
304
+ const batch = createCrowdBatch(scene, geometryView(geo), v.size, v.mat, v.casting, 'Crowd ' + v.kind + LEVELS[level], false);
305
+ castCrowdShadow(scene, batch, geometryView(geos[2]), v.casting, v.size);
300
306
  batches.push(batch);
301
307
  return batch;
302
308
  })
@@ -415,7 +421,7 @@ export function createCrowdBatches({
415
421
  farCasting = [crowdMaterial('depth', walk), crowdMaterial('distance', walk)],
416
422
  name = 'Crowd ' + (level ? 'remote' : 'distant');
417
423
  return [
418
- createCrowdBatch(scene, far.clone(), people, farMat, farCasting, name + ' outside shadow map', false),
424
+ createCrowdBatch(scene, geometryView(far), people, farMat, farCasting, name + ' outside shadow map', false),
419
425
  createCrowdBatch(scene, far, people, farMat, farCasting, name),
420
426
  ];
421
427
  });
@@ -5,6 +5,7 @@
5
5
  * @module
6
6
  */
7
7
 
8
+ import { geometryView } from '../geometry/builder.js';
8
9
  import { farCrowdFigure } from '../geometry/crowd-far.js';
9
10
  import { registerCrowd } from './crowd-update.js';
10
11
 
@@ -62,10 +63,7 @@ export function createCrowdLifecycle({
62
63
  function batchCrowds() {
63
64
  if (batchManager.batches?.groupCount === crowds.length) return batchManager.batches;
64
65
  prepareCrowds();
65
- const built = batchManager.buildCrowdBatches(
66
- farFigures.map(f => f.clone()),
67
- crowds,
68
- );
66
+ const built = batchManager.buildCrowdBatches(farFigures.map(geometryView), crowds);
69
67
  batchManager.setBatches(built);
70
68
  return built;
71
69
  }
@@ -32,22 +32,21 @@ export const CROWD_FAR_STILL = Math.floor(CROWD_FAR_FRAMES / CROWD_FAR_STILLS.le
32
32
  export { CROWD_BONES, CROWD_CHEST, CROWD_DYE, CROWD_PANTS };
33
33
 
34
34
  /**
35
- * Wraps welded typed arrays from `crowdArrays` into a `THREE.BufferGeometry` ready for instanced crowd skinning.
35
+ * Borrows the welded typed arrays from `crowdArrays` into a `THREE.BufferGeometry` ready for instanced crowd skinning.
36
36
  *
37
37
  * @param {ReturnType<typeof crowdArrays>} arrays Welded crowd arrays.
38
38
  * @returns {THREE.BufferGeometry}
39
39
  */
40
40
  export function crowdGeometry(arrays) {
41
41
  const geo = new THREE.BufferGeometry();
42
- geo.setAttribute('position', new THREE.Float32BufferAttribute(arrays.position, 3));
42
+ geo.setAttribute('position', new THREE.BufferAttribute(arrays.position, 3));
43
43
  geo.setAttribute('normal', new THREE.BufferAttribute(arrays.normal, 3, true));
44
44
  geo.setAttribute('color', new THREE.BufferAttribute(arrays.color, 3, true));
45
- geo.setAttribute('aPalette', new THREE.Uint8BufferAttribute(arrays.aPalette, 1));
46
- geo.setAttribute('aTag', new THREE.Int8BufferAttribute(arrays.aTag, 1));
47
- geo.setAttribute('aJoints', new THREE.Uint8BufferAttribute(arrays.aJoints, 2));
45
+ geo.setAttribute('aPalette', new THREE.BufferAttribute(arrays.aPalette, 1));
46
+ geo.setAttribute('aTag', new THREE.BufferAttribute(arrays.aTag, 1));
47
+ geo.setAttribute('aJoints', new THREE.BufferAttribute(arrays.aJoints, 2));
48
48
  geo.setAttribute('aWeight', new THREE.BufferAttribute(arrays.aWeight, 1, true));
49
- const Index = arrays.index instanceof Uint32Array ? THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute;
50
- geo.setIndex(new Index(arrays.index, 1));
49
+ geo.setIndex(new THREE.BufferAttribute(arrays.index, 1));
51
50
  return geo;
52
51
  }
53
52
 
@@ -0,0 +1,66 @@
1
+ import * as THREE from 'three';
2
+
3
+ const corePalette = new Map();
4
+ const poolPalettes = new WeakMap();
5
+ const tint = new THREE.Color();
6
+ const PALETTE_LIMIT = 64;
7
+
8
+ // Most places use only a handful of lights. A weak entry lets a discarded fitting go,
9
+ // and the limit bounds the keys even for worlds that generate colours continuously.
10
+ function glowMaterial(hex, boost, map, fogFades, shared) {
11
+ tint.set(hex).multiplyScalar(boost);
12
+ let palette, key;
13
+ if (shared) {
14
+ palette = corePalette;
15
+ if (map) {
16
+ palette = poolPalettes.get(map);
17
+ if (!palette) poolPalettes.set(map, (palette = new Map()));
18
+ }
19
+ key = `${tint.r},${tint.g},${tint.b},${fogFades}`;
20
+ const kept = palette.get(key)?.deref();
21
+ if (kept) return kept;
22
+ }
23
+ const material = new THREE.MeshBasicMaterial({ color: tint });
24
+ if (map) {
25
+ material.map = map;
26
+ material.blending = THREE.AdditiveBlending;
27
+ material.depthWrite = false;
28
+ material.transparent = true;
29
+ if (fogFades) material.defines = { FOG_FADES: '' };
30
+ }
31
+ if (shared) {
32
+ if (palette.size >= PALETTE_LIMIT && !palette.has(key)) palette.delete(palette.keys().next().value);
33
+ palette.set(key, new WeakRef(material));
34
+ }
35
+ return material;
36
+ }
37
+
38
+ /**
39
+ * Make an unlit mesh of the supplied shape, sRGB colour and linear brightness, optionally adding it to a group.
40
+ * Equal colours share a material. Pass false for shared when the caller will change the material.
41
+ */
42
+ export function glowMesh(geometry, hex, boost, parent, shared = true) {
43
+ const mesh = new THREE.Mesh(geometry, glowMaterial(hex, boost, null, false, shared));
44
+ parent?.add(mesh);
45
+ return mesh;
46
+ }
47
+
48
+ /** Return the shared additive material for a textured pool of light. Clone it before changing its appearance. */
49
+ export function lightPoolMaterial(hex, strength, map, fogFades) {
50
+ return glowMaterial(hex, strength, map, fogFades, true);
51
+ }
52
+
53
+ const flatShapes = new Map();
54
+
55
+ /** A shared horizontal circle (radius, segments) or rectangle (width, depth) for static water and light fittings. */
56
+ export function flatFittingGeometry(shape, width, detail) {
57
+ const key = `${shape}:${width}:${detail}`;
58
+ let geometry = flatShapes.get(key)?.deref();
59
+ if (!geometry) {
60
+ geometry = shape === 'circle' ? new THREE.CircleGeometry(width, detail) : new THREE.PlaneGeometry(width, detail);
61
+ geometry.rotateX(-Math.PI / 2);
62
+ if (flatShapes.size >= PALETTE_LIMIT && !flatShapes.has(key)) flatShapes.delete(flatShapes.keys().next().value);
63
+ flatShapes.set(key, new WeakRef(geometry));
64
+ }
65
+ return geometry;
66
+ }
@@ -39,6 +39,7 @@ export {
39
39
  addWallLantern,
40
40
  createLightPoolTexture,
41
41
  } from './ruins-fittings.js';
42
+ export { flatFittingGeometry, glowMesh } from './glow-mesh.js';
42
43
  export { GROUND_DRAPE_FRAGMENT, createGroundDrape, createGroundDrapeMaterial } from './ground-drape.js';
43
44
  export { meshStreamBanks } from './stream-banks.js';
44
45
  export { meshSprings } from './stream-springs.js';
@@ -7,6 +7,7 @@
7
7
  import * as THREE from 'three';
8
8
  import { createUnitShapes } from '../geometry/primitives.js';
9
9
  import { buildLampStandGeometry, buildWallLanternGeometry } from '../geometry/ruins-masonry.js';
10
+ import { flatFittingGeometry, glowMesh, lightPoolMaterial } from './glow-mesh.js';
10
11
  import { falloffAt, pixelTexture } from './textures.js';
11
12
 
12
13
  /** Default parameters for additive radial ground light pools built by {@link addLightPool}. */
@@ -44,7 +45,7 @@ export function createLightPoolTexture({ size = LIGHT_POOL.size, falloff = LIGHT
44
45
 
45
46
  /**
46
47
  * Place a soft additive pool of warm light lying flat on the ground at `(x, y, z)` so unlit street
47
- * lanterns read warmly without extra dynamic point lights.
48
+ * lanterns read warmly without extra dynamic point lights. The plane and material are shared. Clone them before editing.
48
49
  *
49
50
  * @param {THREE.Object3D} group - Destination scene or group.
50
51
  * @param {number} x - World X position in metres.
@@ -69,15 +70,8 @@ export function addLightPool(group, x, y, z, radius, options = {}) {
69
70
  fogFades = false,
70
71
  } = options;
71
72
  const map = options.texture ?? (defaultPoolTexture ??= createLightPoolTexture());
72
- const material = new THREE.MeshBasicMaterial({
73
- map,
74
- color: new THREE.Color(hex).multiplyScalar(strength),
75
- blending: THREE.AdditiveBlending,
76
- depthWrite: false,
77
- transparent: true,
78
- });
79
- if (fogFades) material.defines = { FOG_FADES: '' };
80
- const pool = new THREE.Mesh(new THREE.PlaneGeometry(1, 1).rotateX(-Math.PI / 2), material);
73
+ const material = lightPoolMaterial(hex, strength, map, fogFades);
74
+ const pool = new THREE.Mesh(flatFittingGeometry('plane', 1, 1), material);
81
75
  pool.position.set(x, y + lift, z);
82
76
  pool.scale.set(radius * 2, 1, radius * 2);
83
77
  pool.renderOrder = renderOrder;
@@ -140,7 +134,7 @@ export function addStillPool(group, options = {}) {
140
134
  new THREE.MeshStandardMaterial(
141
135
  transparent ? { color, roughness, metalness, transparent: true, opacity } : { color, roughness, metalness },
142
136
  );
143
- const geo = new THREE.CircleGeometry(radius ?? 0.5, segments).rotateX(-Math.PI / 2);
137
+ const geo = flatFittingGeometry('circle', radius ?? 0.5, segments);
144
138
  const water = new THREE.Mesh(geo, mat);
145
139
  water.position.set(origin.x + x, y, origin.z + z);
146
140
  if (radius === null) water.scale.set(width, 1, depth);
@@ -197,13 +191,7 @@ export function addFlame(group, options = {}) {
197
191
  onSite = null,
198
192
  space = 'world',
199
193
  } = options;
200
- const core = makeGlowMesh
201
- ? makeGlowMesh(shapes.sph, color, boost, group)
202
- : (() => {
203
- const m = new THREE.Mesh(shapes.sph, new THREE.MeshBasicMaterial({ color: new THREE.Color(color).multiplyScalar(boost) }));
204
- if (group) group.add(m);
205
- return m;
206
- })();
194
+ const core = (makeGlowMesh ?? glowMesh)(shapes.sph, color, boost, group);
207
195
  core.position.set(origin.x + x, y, origin.z + z);
208
196
  core.scale.set(size * 0.5, size * 1.1, size * 0.5);
209
197
  const lamp = size < lampSize;
@@ -277,13 +265,7 @@ export function addWallLantern(kit, options) {
277
265
  onSite = null,
278
266
  } = options;
279
267
  const lantern = buildWallLanternGeometry(kit, { ...options, shapes });
280
- const horn = makeGlowMesh
281
- ? makeGlowMesh(shapes.cyl6, 0xffb860, 1.15, group)
282
- : (() => {
283
- const m = new THREE.Mesh(shapes.cyl6, new THREE.MeshBasicMaterial({ color: new THREE.Color(0xffb860).multiplyScalar(1.15) }));
284
- group.add(m);
285
- return m;
286
- })();
268
+ const horn = (makeGlowMesh ?? glowMesh)(shapes.cyl6, 0xffb860, 1.15, group);
287
269
  horn.position.set(origin.x + lantern.x, lantern.y - 0.135, origin.z + lantern.z);
288
270
  horn.scale.set(0.14, 0.27, 0.14);
289
271
  onSite?.(origin.x + lantern.x, lantern.y - 0.05, origin.z + lantern.z);
@@ -1,4 +1,5 @@
1
1
  import * as THREE from 'three';
2
+ import { releaseArray } from '../geometry/builder.js';
2
3
 
3
4
  /**
4
5
  * The vertex stage of bedded rock laid over a land in tiles (`createStrataTiles`): it moves each vertex between levels of
@@ -77,6 +78,7 @@ void cliffMorph() {
77
78
  * @param {(options: { level: number, uniforms: object, vertex: string }) => { material: import('three').Material, depth: import('three').Material }} options.material -
78
79
  * The picture's material and shadow-depth material of one level, made for `level` with the shared uniforms and the vertex
79
80
  * stage (`createStrataMaterial`).
81
+ * @param {boolean} [options.releaseAfterUpload=false] - Drop box vertex and index arrays after upload when ground queries use the field alone.
80
82
  * @param {() => number} [options.lodScale=() => 1] - A quality setting that stretches or shrinks every distance.
81
83
  * @param {{ pooled: () => boolean, size: () => number, prepare: Function, run: Function, spread: Function }} [options.pool] -
82
84
  * A worker pool (`createPool`): without one, or once one fails, every box is built on the page.
@@ -109,6 +111,7 @@ export function createStrataCliffs({
109
111
  parent,
110
112
  material,
111
113
  lodScale = () => 1,
114
+ releaseAfterUpload = false,
112
115
  pool = { pooled: () => false, size: () => 0, prepare() {}, run: () => Promise.reject(), spread() {} },
113
116
  budget = {
114
117
  task:
@@ -145,6 +148,7 @@ export function createStrataCliffs({
145
148
  const asked = new Set(); // the boxes being built, by level and key ('1/3:4'), until their meshes stand
146
149
  const answers = []; // boxes the pool has built, to be meshed one a frame: [level, key, arrays]
147
150
  let coarse = null, // the promise of the coarse level's arrays, box by box, once begun
151
+ built = null, // concurrent callers share one build after the coarse arrays have been consumed
148
152
  planned = null, // the promise of the plan: where the rock stands and its tiles
149
153
  mats = null,
150
154
  job = null, // a box the page builds itself, a slice a frame: { lv, key, it }
@@ -162,6 +166,10 @@ export function createStrataCliffs({
162
166
  geo.setIndex(new THREE.BufferAttribute(index, 1));
163
167
  geo.computeBoundingSphere();
164
168
  geo.boundingSphere.radius += 8;
169
+ if (releaseAfterUpload) {
170
+ for (const attribute of Object.values(geo.attributes)) attribute.onUpload(releaseArray);
171
+ geo.index.onUpload(releaseArray);
172
+ }
165
173
  const mesh = new THREE.Mesh(geo, mats[lv].material);
166
174
  mesh.customDepthMaterial = mats[lv].depth;
167
175
  mesh.castShadow = true;
@@ -189,6 +197,7 @@ export function createStrataCliffs({
189
197
  // 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
198
  // the worker that made it (or makes it itself where there are none).
191
199
  function begin() {
200
+ if (planned) return;
192
201
  // 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
202
  // less to copy each time this is sent)
194
203
  if (!onPage) pool.prepare(jobs.preparation, preparation(), preparationCost);
@@ -217,17 +226,31 @@ export function createStrataCliffs({
217
226
  }
218
227
  // The rock's materials and ground; the promise is kept once the coarse level stands, meshed in the order of its boxes.
219
228
  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
- });
229
+ if (built) return built;
230
+ if (!planned) begin();
231
+ if (!mats) {
232
+ const hm = new THREE.DataTexture(heights.data, heights.side + 1, heights.side + 1, THREE.RedFormat, THREE.FloatType);
233
+ hm.needsUpdate = true;
234
+ const sh = new THREE.DataTexture(shown, TILES_SIDE, TILES_SIDE, THREE.RedFormat, THREE.FloatType);
235
+ sh.needsUpdate = true;
236
+ uniforms.uHM.value = hm;
237
+ uniforms.uShown.value = sh;
238
+ mats = [0, 1, 2].map(level => material({ level, uniforms, vertex }));
239
+ onBuilt(ground);
240
+ }
241
+ built = coarse
242
+ .then(([keys, arrays]) => {
243
+ for (let i = 0; i < keys.length; i++) {
244
+ if (!boxes[2].has(keys[i])) meshBox(2, keys[i], arrays[i]);
245
+ arrays[i] = null;
246
+ }
247
+ coarse = null;
248
+ })
249
+ .catch(error => {
250
+ planned = coarse = built = null;
251
+ throw error;
252
+ });
253
+ return built;
231
254
  }
232
255
  // 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
256
  // surface (at the 1 m level) that lies over (x, z) by stepping its ground point until it lands there.
@@ -55,6 +55,8 @@ function canvasTexture(canvas, options = {}) {
55
55
  function onCardOnly(texture) {
56
56
  texture.onUpdate = () => {
57
57
  texture.image.data = null;
58
+ // A hand-built mip chain keeps its own pixel arrays, including another reference to level zero.
59
+ for (const mip of texture.mipmaps) if (ArrayBuffer.isView(mip.data)) mip.data = null;
58
60
  texture.onUpdate = null;
59
61
  };
60
62
  return texture;