roamwright 0.61.28 → 0.61.30

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,152 @@
1
+ /**
2
+ * Typed-array part operations shared with GeometryBuilder: four-byte GPU padding and per-triangle flat face normals.
3
+ * @module
4
+ */
5
+
6
+ const PART_ATTRIBUTES = { position: 3, normal: 3, color: 3, aTag: 1, skinIndex: 4, skinWeight: 4 };
7
+ const OPAQUE = 255;
8
+ const normalByte = component => Math.round(component * 127);
9
+
10
+ /** Pad `count` three-byte vertex entries into four-byte strides using `fourth` for the added lane. */
11
+ export function padded(bytes, count, fourth) {
12
+ const out = new bytes.constructor((count / 3) * 4);
13
+ for (let i = 0, writeOffset = 0; i < count; i += 3, writeOffset += 4) {
14
+ out[writeOffset] = bytes[i];
15
+ out[writeOffset + 1] = bytes[i + 1];
16
+ out[writeOffset + 2] = bytes[i + 2];
17
+ out[writeOffset + 3] = fourth;
18
+ }
19
+ return out;
20
+ }
21
+
22
+ /**
23
+ * Pad three-byte compact normal and colour arrays in `parts` to four bytes per vertex (opaque alpha 255)
24
+ * so GPU buffers align on four-byte strides and share vertex-alpha programs with padded settlement blocks.
25
+ * Already padded or float arrays are returned unchanged.
26
+ *
27
+ * @param {object} parts Typed-array part record from `GB.parts()`.
28
+ * @returns {object}
29
+ */
30
+ export function padParts(parts) {
31
+ const count = parts?.position?.length ?? 0;
32
+ if (!count) return parts;
33
+ const padNormal = parts.normal instanceof Int8Array && parts.normal.length === count;
34
+ const padColor = parts.color instanceof Uint8Array && parts.color.length === count;
35
+ if (!padNormal && !padColor) return parts;
36
+ return {
37
+ ...parts,
38
+ normal: padNormal ? padded(parts.normal, count, 0) : parts.normal,
39
+ color: padColor ? padded(parts.color, count, OPAQUE) : parts.color,
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Replace vertex normals in `parts` with per-triangle unit face normals so faceted geometry renders flat without
45
+ * compiling a separate `FLAT_SHADED` shader program. De-indexes indexed parts so adjacent faces never share normals.
46
+ * Supports float normals as well as three- and four-byte compact `Int8Array` normals.
47
+ *
48
+ * @param {object} parts Typed-array part record from `GB.parts()`.
49
+ * @returns {object}
50
+ */
51
+ export function flatNormals(parts) {
52
+ const srcPos = parts?.position;
53
+ if (!srcPos?.length) return parts;
54
+ let out = parts;
55
+ if (parts.index) {
56
+ const idx = parts.index,
57
+ nVerts = idx.length,
58
+ srcVerts = srcPos.length / 3;
59
+ out = { ...parts, index: undefined };
60
+ delete out.index;
61
+ for (const name in PART_ATTRIBUTES) {
62
+ const array = parts[name];
63
+ if (!array) continue;
64
+ const stride = array.length / srcVerts,
65
+ expanded = new array.constructor(nVerts * stride);
66
+ for (let i = 0; i < nVerts; i++) {
67
+ const from = idx[i] * stride,
68
+ to = i * stride;
69
+ for (let k = 0; k < stride; k++) expanded[to + k] = array[from + k];
70
+ }
71
+ out[name] = expanded;
72
+ }
73
+ }
74
+ const pos = out.position,
75
+ srcNorm = out.normal;
76
+ if (!srcNorm) return out;
77
+ const verts = pos.length / 3,
78
+ stride = srcNorm.length / verts,
79
+ isByte = srcNorm instanceof Int8Array,
80
+ normals = new srcNorm.constructor(srcNorm.length);
81
+ for (let t = 0; t < verts; t += 3) {
82
+ const p0 = t * 3,
83
+ p1 = p0 + 3,
84
+ p2 = p0 + 6;
85
+ const ax = pos[p1] - pos[p0],
86
+ ay = pos[p1 + 1] - pos[p0 + 1],
87
+ az = pos[p1 + 2] - pos[p0 + 2];
88
+ const bx = pos[p2] - pos[p0],
89
+ by = pos[p2 + 1] - pos[p0 + 1],
90
+ bz = pos[p2 + 2] - pos[p0 + 2];
91
+ let nx = ay * bz - az * by,
92
+ ny = az * bx - ax * bz,
93
+ nz = ax * by - ay * bx;
94
+ const len = Math.hypot(nx, ny, nz);
95
+ if (len > 0) {
96
+ nx /= len;
97
+ ny /= len;
98
+ nz /= len;
99
+ } else {
100
+ nx = 0;
101
+ ny = 1;
102
+ nz = 0;
103
+ }
104
+ const wx = isByte ? normalByte(nx) : nx,
105
+ wy = isByte ? normalByte(ny) : ny,
106
+ wz = isByte ? normalByte(nz) : nz;
107
+ for (let k = 0; k < 3; k++) {
108
+ const at = (t + k) * stride;
109
+ normals[at] = wx;
110
+ normals[at + 1] = wy;
111
+ normals[at + 2] = wz;
112
+ if (stride === 4) normals[at + 3] = 0;
113
+ }
114
+ }
115
+ return { ...out, normal: normals };
116
+ }
117
+
118
+ /** Replace non-indexed triangle float and byte normals in place with per-triangle unit face normals. */
119
+ export function flattenInPlace(positions, normals, normalBytes, count) {
120
+ for (let i = 0; i + 8 < count; i += 9) {
121
+ const ax = positions[i + 3] - positions[i],
122
+ ay = positions[i + 4] - positions[i + 1],
123
+ az = positions[i + 5] - positions[i + 2];
124
+ const bx = positions[i + 6] - positions[i],
125
+ by = positions[i + 7] - positions[i + 1],
126
+ bz = positions[i + 8] - positions[i + 2];
127
+ let nx = ay * bz - az * by,
128
+ ny = az * bx - ax * bz,
129
+ nz = ax * by - ay * bx;
130
+ const len = Math.hypot(nx, ny, nz);
131
+ if (len > 0) {
132
+ nx /= len;
133
+ ny /= len;
134
+ nz /= len;
135
+ } else {
136
+ nx = 0;
137
+ ny = 1;
138
+ nz = 0;
139
+ }
140
+ const bxn = normalByte(nx),
141
+ byn = normalByte(ny),
142
+ bzn = normalByte(nz);
143
+ for (let k = 0; k < 9; k += 3) {
144
+ normals[i + k] = nx;
145
+ normals[i + k + 1] = ny;
146
+ normals[i + k + 2] = nz;
147
+ normalBytes[i + k] = bxn;
148
+ normalBytes[i + k + 1] = byn;
149
+ normalBytes[i + k + 2] = bzn;
150
+ }
151
+ }
152
+ }
@@ -1,12 +1,14 @@
1
1
  /**
2
2
  * Stepped pack-crawler motion solver: moves a group of ground crawlers together with a parent anchor, tracking heading
3
3
  * and speed (ignoring teleport jumps), loosely wandering each member around its pack slot, turning smoothly into the
4
- * heading, clamping each body to the terrain below it, and selecting its baked gait moment. Worker-safe arithmetic only
5
- * (no Three.js dependency) and zero per-frame allocations.
4
+ * heading, clamping each body to the terrain below it, and selecting its baked gait moment. Beside the pack,
5
+ * {@link createWallCrawlerMotion} drives crawlers that dash a little way along a vertical wall and wait. Worker-safe
6
+ * arithmetic only (no Three.js dependency) and zero per-frame allocations.
6
7
  * @module
7
8
  */
8
9
 
9
10
  import { wrapRadians } from '../math/periodic.js';
11
+ import { mulberry32 } from '../math/random.js';
10
12
 
11
13
  /**
12
14
  * Default crawler-pack motion parameters (metres, seconds, radians) and a seven-member formation `[side, ahead, scale]`.
@@ -108,3 +110,137 @@ export function createCrawlerPackMotion({
108
110
 
109
111
  return { members, step };
110
112
  }
113
+
114
+ /**
115
+ * Default wall-dashing crawler parameters (metres, seconds) for {@link createWallCrawlerMotion}: each crawler dashes
116
+ * across its wall face for the first share of each leg, then pauses until the next leg begins.
117
+ */
118
+ export const WALL_CRAWLER_DEFAULTS = Object.freeze({
119
+ /** Number of crawlers placed along the opposing walls. */
120
+ count: 16,
121
+ /** Uniform scale applied to the crawler geometry (e.g. a hand-sized spider). */
122
+ size: 0.55,
123
+ /** Horizontal inset kept clear of each passage end in metres. */
124
+ marginX: 0.8,
125
+ /** Vertical inset kept clear of floor and ceiling in metres. */
126
+ marginY: 0.6,
127
+ /** Small offset inward from the wall plane so legs sit on stone without z-fighting, in metres. */
128
+ wallOffset: 0.008,
129
+ /** Minimum horizontal dash amplitude in metres. */
130
+ reachMin: 0.5,
131
+ /** Random span added to horizontal dash amplitude in metres. */
132
+ reachSpan: 1.1,
133
+ /** Minimum leg cadence in legs per second. */
134
+ paceMin: 0.25,
135
+ /** Random span added to leg cadence in legs per second. */
136
+ paceSpan: 0.4,
137
+ /** Initial phase spread in legs. */
138
+ phaseSpan: 30,
139
+ /** Inverse share of each leg spent dashing (`2.2` dashes for ~45% of each leg, then waits). */
140
+ dashRate: 2.2,
141
+ /** Vertical dash amplitude in metres. */
142
+ verticalReach: 0.45,
143
+ });
144
+
145
+ /**
146
+ * Creates a zero-allocation motion controller for crawlers dashing and pausing along vertical passage walls.
147
+ * Each crawler alternates dashes and waits along its wall plane (`z = origin.z ± (halfWidth - wallOffset)`),
148
+ * computing its world position and wall-aligned pitch/roll (`rx`, `rz`) with belly to the stone and head along travel.
149
+ *
150
+ * @param {object} [options]
151
+ * @param {number} [options.count=WALL_CRAWLER_DEFAULTS.count] Number of wall crawlers.
152
+ * @param {{ x: number, z: number }} [options.origin] Local-to-world horizontal origin in metres (defaults to `{ x: 0, z: 0 }`).
153
+ * @param {number} [options.x0=-10] Minimum local X extent along the wall in metres.
154
+ * @param {number} [options.x1=0] Maximum local X extent along the wall in metres.
155
+ * @param {number} [options.y0=0] Floor elevation at the base of the wall in metres.
156
+ * @param {number} [options.height=3.1] Wall height above `y0` in metres.
157
+ * @param {number} [options.halfWidth=1.3] Half-width between opposing walls in metres.
158
+ * @param {number[] | null} [options.sides=null] Optional wall-side signs (`+1` or `-1`) cycled per crawler; omit to alternate `-1, +1`.
159
+ * @param {() => number} [options.random] Repeatable PRNG stream (5 draws per crawler).
160
+ * @param {number} [options.marginX=WALL_CRAWLER_DEFAULTS.marginX] End-of-wall horizontal inset in metres.
161
+ * @param {number} [options.marginY=WALL_CRAWLER_DEFAULTS.marginY] Floor/ceiling vertical inset in metres.
162
+ * @param {number} [options.wallOffset=WALL_CRAWLER_DEFAULTS.wallOffset] Inward clearance from wall plane in metres.
163
+ * @param {number} [options.reachMin=WALL_CRAWLER_DEFAULTS.reachMin] Minimum horizontal dash reach in metres.
164
+ * @param {number} [options.reachSpan=WALL_CRAWLER_DEFAULTS.reachSpan] Random horizontal reach span in metres.
165
+ * @param {number} [options.paceMin=WALL_CRAWLER_DEFAULTS.paceMin] Minimum leg cadence in legs/s.
166
+ * @param {number} [options.paceSpan=WALL_CRAWLER_DEFAULTS.paceSpan] Random cadence span in legs/s.
167
+ * @param {number} [options.phaseSpan=WALL_CRAWLER_DEFAULTS.phaseSpan] Initial leg phase spread.
168
+ * @param {number} [options.dashRate=WALL_CRAWLER_DEFAULTS.dashRate] Speed factor for the active dash share of each leg.
169
+ * @param {number} [options.verticalReach=WALL_CRAWLER_DEFAULTS.verticalReach] Vertical dash amplitude in metres.
170
+ * @returns {{
171
+ * runs: Array<{ x: number, y: number, sg: number, reach: number, pace: number, phase: number, leg: number, startX: number, startY: number, dx: number, dy: number, roll: number, posX: number, posY: number, posZ: number, rx: number, rz: number }>,
172
+ * step: (t: number) => void,
173
+ * }}
174
+ */
175
+ export function createWallCrawlerMotion({
176
+ count = WALL_CRAWLER_DEFAULTS.count,
177
+ origin = { x: 0, z: 0 },
178
+ x0 = -10,
179
+ x1 = 0,
180
+ y0 = 0,
181
+ height = 3.1,
182
+ halfWidth = 1.3,
183
+ sides = null,
184
+ random = mulberry32(31),
185
+ marginX = WALL_CRAWLER_DEFAULTS.marginX,
186
+ marginY = WALL_CRAWLER_DEFAULTS.marginY,
187
+ wallOffset = WALL_CRAWLER_DEFAULTS.wallOffset,
188
+ reachMin = WALL_CRAWLER_DEFAULTS.reachMin,
189
+ reachSpan = WALL_CRAWLER_DEFAULTS.reachSpan,
190
+ paceMin = WALL_CRAWLER_DEFAULTS.paceMin,
191
+ paceSpan = WALL_CRAWLER_DEFAULTS.paceSpan,
192
+ phaseSpan = WALL_CRAWLER_DEFAULTS.phaseSpan,
193
+ dashRate = WALL_CRAWLER_DEFAULTS.dashRate,
194
+ verticalReach = WALL_CRAWLER_DEFAULTS.verticalReach,
195
+ } = {}) {
196
+ const ox = origin.x,
197
+ oz = origin.z,
198
+ wallZ = halfWidth - wallOffset,
199
+ runs = Array.from({ length: count }, (_, i) => {
200
+ const sg = sides ? sides[i % sides.length] : i % 2 ? 1 : -1;
201
+ return {
202
+ x: x0 + marginX + random() * (x1 - x0 - marginX * 2),
203
+ y: y0 + marginY + random() * (height - marginY * 2),
204
+ sg,
205
+ reach: reachMin + random() * reachSpan,
206
+ pace: paceMin + random() * paceSpan,
207
+ phase: random() * phaseSpan,
208
+ leg: -1,
209
+ startX: 0,
210
+ startY: 0,
211
+ dx: 0,
212
+ dy: 0,
213
+ roll: 0,
214
+ posX: 0,
215
+ posY: 0,
216
+ posZ: oz + sg * wallZ,
217
+ rx: (sg * Math.PI) / 2,
218
+ rz: 0,
219
+ };
220
+ });
221
+
222
+ function step(t) {
223
+ for (let i = 0; i < runs.length; i++) {
224
+ const s = runs[i],
225
+ u = t * s.pace + s.phase,
226
+ leg = Math.floor(u),
227
+ f = Math.min(1, (u - leg) * dashRate), // runs for the first part of each leg, then waits
228
+ e = f * f * (3 - 2 * f);
229
+ // Endpoints and wall-plane bearing stay fixed until the next dash begins.
230
+ if (s.leg !== leg) {
231
+ s.leg = leg;
232
+ s.startX = Math.sin(leg * 2.4 + i) * s.reach;
233
+ s.startY = Math.cos(leg * 1.7 + i * 2) * verticalReach;
234
+ s.dx = Math.sin((leg + 1) * 2.4 + i) * s.reach - s.startX;
235
+ s.dy = Math.cos((leg + 1) * 1.7 + i * 2) * verticalReach - s.startY;
236
+ s.roll = s.sg * (Math.atan2(s.dy, s.dx) - Math.PI / 2);
237
+ }
238
+ s.posX = ox + s.x + s.startX + s.dx * e;
239
+ s.posY = s.y + s.startY + s.dy * e;
240
+ s.posZ = oz + s.sg * wallZ;
241
+ s.rz = s.roll;
242
+ }
243
+ }
244
+
245
+ return { runs, step };
246
+ }
package/motion/index.js CHANGED
@@ -19,7 +19,7 @@ export { horsePose } from './animal-bearing.js';
19
19
  export { caninePose } from './animal-canine-bearing.js';
20
20
  export { catPose } from './animal-cat-bearing.js';
21
21
  export { herdArrays } from './animal-herd-cast.js';
22
- export { CRAWLER_PACK_DEFAULTS, createCrawlerPackMotion } from './crawler-pack.js';
22
+ export { CRAWLER_PACK_DEFAULTS, WALL_CRAWLER_DEFAULTS, createCrawlerPackMotion, createWallCrawlerMotion } from './crawler-pack.js';
23
23
  export { createCrawlFlight } from './flier-swarm-flight.js';
24
24
  export { CARPET_DEFAULTS, createCarpetFlight } from './flier-carpet-flight.js';
25
25
  export { createLampSwarmFlight, pickNearestAnchors } from './flier-lamp-swarm.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.28",
3
+ "version": "0.61.30",
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,8 +6,10 @@
6
6
  */
7
7
 
8
8
  import * as THREE from 'three';
9
+ import { spiderGeometry } from '../geometry/crawl-shapes.js';
9
10
  import { GIANT_SPIDER_GAIT, GIANT_SPIDER_LOOK, giantSpiderMoments } from '../geometry/crawler-giant-spider.js';
10
- import { CRAWLER_PACK_DEFAULTS, createCrawlerPackMotion } from '../motion/crawler-pack.js';
11
+ import { TRS } from '../geometry/primitives.js';
12
+ import { CRAWLER_PACK_DEFAULTS, WALL_CRAWLER_DEFAULTS, createCrawlerPackMotion, createWallCrawlerMotion } from '../motion/crawler-pack.js';
11
13
 
12
14
  /**
13
15
  * Builds a `THREE.Group` containing a pack of ground crawlers driven by `createCrawlerPackMotion`, switching each member's
@@ -89,3 +91,44 @@ export function createGiantSpiderPack(options = {}) {
89
91
  });
90
92
  return createCrawlerPack({ ...options, moments });
91
93
  }
94
+
95
+ /**
96
+ * Builds an `InstancedMesh` of wall-dashing crawlers (defaulting to {@link spiderGeometry}) driven by
97
+ * {@link createWallCrawlerMotion}. Calling `crawl(t)` updates every instance matrix in place with zero per-frame allocations.
98
+ *
99
+ * @param {object} [options] Options forwarded to {@link createWallCrawlerMotion}, plus rendering parameters below.
100
+ * @param {THREE.BufferGeometry} [options.geometry] Shared crawler geometry (defaults to `spiderGeometry(shapes, look)`).
101
+ * @param {object} [options.shapes] Unit shapes passed to `spiderGeometry` when `geometry` is omitted.
102
+ * @param {object} [options.look] Linear colours passed to `spiderGeometry` when `geometry` is omitted.
103
+ * @param {THREE.Material} [options.material] Shared material (defaults to vertex-coloured `MeshStandardMaterial`).
104
+ * @param {number} [options.size=WALL_CRAWLER_DEFAULTS.size] Uniform crawler scale factor.
105
+ * @param {Function} [options.transform=TRS] Transform matrix helper (`TRS`).
106
+ * @returns {{ mesh: THREE.InstancedMesh, crawl: (t: number) => void, motion: ReturnType<typeof createWallCrawlerMotion> }}
107
+ */
108
+ export function createWallCrawlers({
109
+ geometry = null,
110
+ shapes,
111
+ look,
112
+ material = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.7, flatShading: true }),
113
+ size = WALL_CRAWLER_DEFAULTS.size,
114
+ transform = TRS,
115
+ ...motionOptions
116
+ } = {}) {
117
+ const motion = createWallCrawlerMotion(motionOptions),
118
+ { runs } = motion,
119
+ geo = geometry ?? spiderGeometry(shapes, look),
120
+ mesh = new THREE.InstancedMesh(geo, material, runs.length);
121
+ mesh.frustumCulled = false;
122
+
123
+ const crawl = t => {
124
+ motion.step(t);
125
+ for (let i = 0; i < runs.length; i++) {
126
+ const s = runs[i];
127
+ // Lying on the wall: belly to the stone, head pointing along the dash.
128
+ mesh.setMatrixAt(i, transform(s.posX, s.posY, s.posZ, size, size, size, 0, s.rx, s.rz));
129
+ }
130
+ mesh.instanceMatrix.needsUpdate = true;
131
+ };
132
+
133
+ return { mesh, crawl, motion };
134
+ }
@@ -109,6 +109,8 @@ export function createLongFlierCompany({
109
109
  opacity: 0.3,
110
110
  depthWrite: false,
111
111
  side: THREE.DoubleSide,
112
+ // Flat translucent wing blades have no closed back/front overlap, so one pass avoids a duplicate FLIP_SIDED program.
113
+ forceSinglePass: true,
112
114
  }),
113
115
  key + ':wings',
114
116
  time,
@@ -179,46 +179,51 @@ export function createFlock({
179
179
  }) {
180
180
  const bird = !!look,
181
181
  geometry = bird ? birdGeometry(look) : plainBirdGeometry(),
182
- flap = bird ? new THREE.InstancedBufferAttribute(new Float32Array(n * 2), 2) : null;
183
- if (flap) geometry.setAttribute('aFlap', flap.setUsage(THREE.DynamicDrawUsage));
182
+ verts = geometry.attributes.position.count,
183
+ flap = new THREE.InstancedBufferAttribute(new Float32Array(n * 2), 2);
184
+ if (bird) flap.setUsage(THREE.DynamicDrawUsage);
185
+ geometry.setAttribute('aFlap', flap);
186
+ if (!geometry.attributes.color) geometry.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(verts * 3).fill(1), 3));
187
+ if (!geometry.attributes.aUnder) geometry.setAttribute('aUnder', new THREE.Float32BufferAttribute(new Float32Array(verts * 4), 4));
184
188
  const coloured = bird && !!look.colours,
185
- under = bird && !!look.under,
186
189
  material = new THREE.MeshStandardMaterial({
187
190
  color: coloured ? 0xffffff : bird ? plumage(color, least) : color,
188
- vertexColors: coloured,
191
+ vertexColors: true,
189
192
  roughness: (bird && look.gloss) || roughness,
190
193
  side: THREE.DoubleSide,
191
194
  flatShading: true,
192
195
  });
193
196
  material.onBeforeCompile = sh => {
194
197
  sh.uniforms.uTime = time;
195
- if (bird) sh.uniforms.uBeat = { value: look.beat * TAU };
198
+ sh.uniforms.uBeat = { value: bird ? look.beat * TAU : 0 };
199
+ sh.uniforms.uPlain = { value: bird ? 0 : 1 };
196
200
  sh.vertexShader = sh.vertexShader
197
201
  .replace(
198
202
  '#include <common>',
199
- '#include <common>\nattribute float aW; uniform float uTime;' +
200
- (bird ? ' attribute vec2 aFlap; uniform float uBeat;' : '') +
201
- (under ? UNDER_HEAD : ''),
203
+ '#include <common>\nattribute float aW; uniform float uTime; attribute vec2 aFlap; uniform float uBeat; uniform float uPlain;' +
204
+ UNDER_HEAD,
202
205
  )
203
206
  .replace(
204
207
  '#include <begin_vertex>',
205
- bird
206
- ? '#include <begin_vertex>' + BEAT + (under ? '\n vUnder = aUnder;' : '')
207
- : `/* glsl */
208
+ `/* glsl */
208
209
  #include <begin_vertex>
209
- #ifdef USE_INSTANCING
210
- float ph = instanceMatrix[3].x * 0.31 + instanceMatrix[3].z * 0.17;
211
- #else
212
- float ph = 0.0;
213
- #endif
214
- transformed.y += aW * sin(uTime * 5.5 + ph) * 0.75;`,
210
+ if (uPlain > 0.5) {
211
+ #ifdef USE_INSTANCING
212
+ float ph = instanceMatrix[3].x * 0.31 + instanceMatrix[3].z * 0.17;
213
+ #else
214
+ float ph = 0.0;
215
+ #endif
216
+ transformed.y += aW * sin(uTime * 5.5 + ph) * 0.75;
217
+ } else {${BEAT}
218
+ }
219
+ vUnder = aUnder;`,
215
220
  );
216
- if (under)
217
- sh.fragmentShader = sh.fragmentShader
218
- .replace('#include <common>', '#include <common>\nvarying vec4 vUnder;')
219
- .replace('#include <color_fragment>', '#include <color_fragment>' + UNDER);
221
+ sh.fragmentShader = sh.fragmentShader
222
+ .replace('#include <common>', '#include <common>\nvarying vec4 vUnder;')
223
+ .replace('#include <color_fragment>', '#include <color_fragment>' + UNDER);
220
224
  };
221
- material.customProgramCacheKey = () => 'flock:' + key + (coloured ? ':coloured' : '') + (under ? ':under' : '');
225
+ const cacheKey = key === 'bird' || key === 'plain' ? 'flock' : 'flock:' + key;
226
+ material.customProgramCacheKey = () => cacheKey;
222
227
  const mesh = new THREE.InstancedMesh(geometry, material, n);
223
228
  mesh.frustumCulled = false;
224
229
  const birds = [];
@@ -51,16 +51,16 @@ export function createHeightProbe(renderer, scene, { layer, size, above, below,
51
51
  }
52
52
 
53
53
  function depth() {
54
- return (depthMaterial ??= new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking }));
54
+ return (depthMaterial ??= new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide }));
55
55
  }
56
56
 
57
- // Prepare the same depth override as a measurement. The probe includes every visible light
58
- // on its reserved layer, and preserves scene fog when rendering the override.
57
+ // Prepare the same depth override as a measurement (double-sided and without fog so depth
58
+ // programs are shared with sky-occlusion passes).
59
59
  function warm(root, warmStandIns) {
60
60
  const previous = view.layers.mask;
61
61
  view.layers.enableAll();
62
62
  try {
63
- const geometry = warmStandIns(root, object => solidMesh(object) && depth(), view, undefined, scene.fog, true);
63
+ const geometry = warmStandIns(root, object => solidMesh(object) && depth(), view, undefined, null, true);
64
64
  return useQueries ? Promise.all([geometry, depthResult().warm()]) : geometry;
65
65
  } finally {
66
66
  view.layers.mask = previous;
@@ -80,6 +80,7 @@ export function createHeightProbe(renderer, scene, { layer, size, above, below,
80
80
  mip = renderer.getActiveMipmapLevel();
81
81
  const alpha = renderer.getClearAlpha(),
82
82
  background = scene.background,
83
+ fog = scene.fog,
83
84
  override = scene.overrideMaterial;
84
85
  const { autoUpdate, needsUpdate } = renderer.shadowMap;
85
86
  renderer.getClearColor(clear);
@@ -88,6 +89,7 @@ export function createHeightProbe(renderer, scene, { layer, size, above, below,
88
89
  scene.traverse(select);
89
90
  scene.overrideMaterial = depth();
90
91
  scene.background = null;
92
+ scene.fog = null;
91
93
  renderer.shadowMap.autoUpdate = renderer.shadowMap.needsUpdate = false;
92
94
  renderer.setRenderTarget(target);
93
95
  renderer.setClearColor(0xffffff, 1);
@@ -99,6 +101,7 @@ export function createHeightProbe(renderer, scene, { layer, size, above, below,
99
101
  renderer.setClearColor(clear, alpha);
100
102
  scene.overrideMaterial = override;
101
103
  scene.background = background;
104
+ scene.fog = fog;
102
105
  renderer.shadowMap.autoUpdate = autoUpdate;
103
106
  renderer.shadowMap.needsUpdate = needsUpdate;
104
107
  for (let i = 0; i < prevLayers.length; i += 2) prevLayers[i].layers.mask = prevLayers[i + 1];
@@ -1,9 +1,10 @@
1
1
  // A house kit's arrays as meshes: one mesh to a kind, instanced copies of them, or the cells of a cut kit as batches that
2
2
  // cull cell by cell and are written to the graphics card a frame's share at a time.
3
3
  import * as THREE from 'three';
4
- import { geometryOf } from '../geometry/builder.js';
4
+ import { geometryOf, padParts } from '../geometry/builder.js';
5
5
  import { KIT_KEYS } from '../geometry/house-kit-frame.js';
6
6
  import { markStill } from './still-casters.js';
7
+ import { whiteInstanceColor } from './material-lod.js';
7
8
  import { createHandOver } from '../runtime/hand-over.js';
8
9
 
9
10
  const SYNC_HAND_OVER = createHandOver({ painted: () => Promise.resolve(), frameShare: () => Infinity });
@@ -63,7 +64,8 @@ export function createHouseKitMaterials({
63
64
  * @param {() => boolean} [o.worldDrawn] Whether the world has been drawn yet: until it has, steps written to the card
64
65
  * run all at once (behind a loading bar) rather than paced.
65
66
  * @param {object} [o.handOver] The renderer's hand-over (`createHandOver`): `paced`, `drain` and `heldBytes`; defaults to a synchronous hand-over.
66
- * @returns {object} `materials` (the resolved material map), `kitStatic(kit, parent, materialOf)`, `kitMeshes(parts, parent, materialOf)`,
67
+ * @param {boolean} [o.padded=false] Pad three-byte compact normal and colour arrays of static kit meshes and cells to four bytes per vertex, matching padded settlement-quarter blocks so both share one WebGL program per material.
68
+ * @returns {object} `materials` (the resolved material map), `kitStatic(kit, parent, materialOf, pad)`, `kitMeshes(parts, parent, materialOf, pad)`,
67
69
  * `instancedOf(meshes, n, group)`, `kitInstanced(kit, n, group)`, `cellPieces(cellsOfKinds, parent, far, detail, materialOf)`,
68
70
  * `pieceSwitch(batch, id)`, and `toCard(steps, signal)`.
69
71
  */
@@ -73,23 +75,25 @@ export function createHouseKitMeshes({
73
75
  instancedMaterial = m => m,
74
76
  worldDrawn = () => true,
75
77
  handOver = SYNC_HAND_OVER,
78
+ padded = false,
79
+ tinted = false,
76
80
  } = {}) {
77
81
  const { drain, heldBytes, paced } = handOver,
78
82
  ownMaterial = k => materials[k];
79
83
 
80
84
  // A filled kit as meshes, one to a kind, and the kit let go; materialOf(kind) gives each kind's material, where a place has
81
85
  // stone of its own.
82
- function kitStatic(B, parent, materialOf) {
83
- const parts = KIT_KEYS.map(k => B[k].parts(true));
86
+ function kitStatic(B, parent, materialOf, pad = padded) {
87
+ const parts = KIT_KEYS.map(k => B[k].parts(true, pad));
84
88
  for (const k of KIT_KEYS) B[k].release();
85
- return kitMeshes(parts, parent, materialOf);
89
+ return kitMeshes(parts, parent, materialOf, pad);
86
90
  }
87
91
  // A kit's arrays (GB.parts, a kind to each of KIT_KEYS) as meshes, one to a kind that has any.
88
- function kitMeshes(parts, parent, materialOf = ownMaterial) {
92
+ function kitMeshes(parts, parent, materialOf = ownMaterial, pad = padded) {
89
93
  const out = [];
90
94
  KIT_KEYS.forEach((k, kind) => {
91
95
  if (!parts[kind].position.length) return;
92
- const m = new THREE.Mesh(geometryOf(parts[kind]), materialOf(k));
96
+ const m = new THREE.Mesh(geometryOf(pad ? padParts(parts[kind]) : parts[kind]), materialOf(k));
93
97
  m.castShadow = k !== 'glass' && k !== 'trim' && k !== 'stain';
94
98
  if (m.castShadow) markStill(m); // put in place once (still-casters.js)
95
99
  m.receiveShadow = k !== 'stain';
@@ -105,6 +109,7 @@ export function createHouseKitMeshes({
105
109
  function instancedOf(meshes, n, group) {
106
110
  return meshes.map(mesh => {
107
111
  const many = new THREE.InstancedMesh(mesh.geometry, instancedMaterial(mesh.material), n);
112
+ if (tinted) whiteInstanceColor(many);
108
113
  many.frustumCulled = false;
109
114
  many.castShadow = many.receiveShadow = true;
110
115
  many.count = 0;
@@ -114,8 +119,8 @@ export function createHouseKitMeshes({
114
119
  return many;
115
120
  });
116
121
  }
117
- // A filled kit as instanced meshes of up to n under group (instancedOf); the kit is let go.
118
- const kitInstanced = (B, n, group) => instancedOf(kitStatic(B, new THREE.Group()), n, group);
122
+ // A filled kit as instanced meshes of up to n under group (instancedOf); kept unpadded so instanced props share 3-byte colour programs with other instanced meshes.
123
+ const kitInstanced = (B, n, group) => instancedOf(kitStatic(B, new THREE.Group(), undefined, false), n, group);
119
124
  // Runs steps that write to the card (cellPieces, or a place's near detail made of them): no faster than the hand-over lets a
120
125
  // frame take once the world is drawn, and all at once while the page is still loading behind its bar, where pacing would
121
126
  // only lengthen the wait. The promise gives what the steps return.
@@ -147,7 +152,7 @@ export function createHouseKitMeshes({
147
152
  batches[small] = batch;
148
153
  }
149
154
  for (const c of cells) {
150
- const geometry = geometryOf(c.parts, c.sphere),
155
+ const geometry = geometryOf(padded ? padParts(c.parts) : c.parts, c.sphere),
151
156
  bytes = bytesOf(geometry),
152
157
  batch = batches[c.small],
153
158
  id = batch.add(geometry);
@@ -43,6 +43,7 @@ export { GROUND_DRAPE_FRAGMENT, createGroundDrape, createGroundDrapeMaterial } f
43
43
  export { meshStreamBanks } from './stream-banks.js';
44
44
  export { meshSprings } from './stream-springs.js';
45
45
  export { layRoads } from './road-ribbons.js';
46
+ export { DEFAULT_TRAFFIC_OXEN, OXEN_DRAWING, createRoadTrafficRenderer } from './road-traffic.js';
46
47
  export { createAvenueHandover, farRoadPavingMaterial, layPavedRoad, layRoadAvenue } from './paved-road.js';
47
48
  export { PAVED_GROUND_LIMITS, createPavedGroundMaterial } from './paved-ground.js';
48
49
  export { TUFT_SHADER, createGrassTuft, createTuftMaterial } from './plant-tuft.js';
@@ -89,7 +90,7 @@ export { buildCamel } from './animal-camel-figure.js';
89
90
  export { buildCanine } from './animal-canine-figure.js';
90
91
  export { createFlierShapes, createSwarm, FLY_WINGS } from './flier-swarm.js';
91
92
  export { CARPET_LEVELS, canineStrideSteps, createCanineStrideCast, createCarpetSwarm } from './flier-carpet.js';
92
- export { createCrawlerPack, createGiantSpiderPack } from './crawler-pack.js';
93
+ export { createCrawlerPack, createGiantSpiderPack, createWallCrawlers } from './crawler-pack.js';
93
94
  export { updateNearGroups } from './detail-range.js';
94
95
  export { createPenFlocks, packPenAnimals } from './pen-flocks.js';
95
96
  export { createLongFlierCompany } from './flier-long-body-company.js';
@@ -18,6 +18,8 @@ export function createLampWashMaterial({ night, cacheKey = 'lamp-wash' }) {
18
18
  depthWrite: false,
19
19
  fog: false,
20
20
  side: THREE.DoubleSide, // the fans wind either way, as the wall faces
21
+ // Additive blending is commutative regardless of face order, so one pass avoids a duplicate FLIP_SIDED compile.
22
+ forceSinglePass: true,
21
23
  polygonOffset: true,
22
24
  polygonOffsetFactor: -2,
23
25
  polygonOffsetUnits: -2,