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.
@@ -8,27 +8,30 @@ const SCATTER = 'fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056,
8
8
  // A copy of a material that draws only a share of its pixels (share.value, from 0 to 1), scattered evenly: a house built in detail dissolves in over its far version instead of jumping into place, and out again
9
9
  // when it is let go. One copy to a material and share (a land's own stone has its own); all share one program.
10
10
  const fadings = new WeakMap();
11
+ const rawFading = new WeakMap();
11
12
  export function fadingOf(base, share) {
12
- let variants = fadings.get(base);
13
- if (!variants) fadings.set(base, (variants = new Map()));
13
+ const raw = rawFading.get(base) ?? base;
14
+ let variants = fadings.get(raw);
15
+ if (!variants) fadings.set(raw, (variants = new Map()));
14
16
  let variant = variants.get(share);
15
17
  if (variant) return variant;
16
- variants.set(share, (variant = base.clone()));
18
+ variants.set(share, (variant = raw.clone()));
19
+ rawFading.set(variant, raw);
17
20
  variant.onBeforeCompile = (shader, renderer) => {
18
- base.onBeforeCompile(shader, renderer);
21
+ raw.onBeforeCompile(shader, renderer);
19
22
  shader.uniforms.uShare = share;
20
23
  shader.fragmentShader = shader.fragmentShader
21
24
  .replace('#include <common>', '#include <common>\nuniform float uShare;')
22
25
  .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\nif (${SCATTER} > uShare) discard;`);
23
26
  };
24
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':dissolving';
27
+ variant.customProgramCacheKey = () => raw.customProgramCacheKey() + ':dissolving';
25
28
  return variant;
26
29
  }
27
30
  // A copy of a material that draws only what lies nearer the eye than `reach.value` metres or, with `beyond`, only what lies
28
31
  // further: a thing's near version and its far one hand over pixel by pixel across a band `band` metres deep about that distance,
29
32
  // each drawing the pixels of the screen-fixed scatter (SCATTER) the other leaves, a share that follows the pixel's distance. No
30
33
  // pixel is drawn by both, none by neither, and no stretch of the thing changes all at once. One copy to a material, reach, side
31
- // and band; the two sides share one program each.
34
+ // and band; both sides and all bands share one program via `uBeyond` and `uHalfBand`.
32
35
  const reaching = new WeakMap();
33
36
  export function reachOf(base, reach, beyond = false, band = 1) {
34
37
  let variants = reaching.get(base);
@@ -37,59 +40,64 @@ export function reachOf(base, reach, beyond = false, band = 1) {
37
40
  let sides = variants.get(reach);
38
41
  if (!sides) variants.set(reach, (sides = {}));
39
42
  if (sides[key]) return sides[key];
40
- const variant = (sides[key] = base.clone());
43
+ const variant = (sides[key] = base.clone()),
44
+ beyondUniform = { value: beyond ? 1 : 0 },
45
+ halfBandUniform = { value: band * 0.5 };
41
46
  variant.onBeforeCompile = (shader, renderer) => {
42
47
  base.onBeforeCompile(shader, renderer);
43
48
  shader.uniforms.uReach = reach;
49
+ shader.uniforms.uBeyond = beyondUniform;
50
+ shader.uniforms.uHalfBand = halfBandUniform;
44
51
  shader.fragmentShader = shader.fragmentShader
45
- .replace('#include <common>', '#include <common>\nuniform float uReach;')
52
+ .replace('#include <common>', '#include <common>\nuniform float uReach;\nuniform float uBeyond;\nuniform float uHalfBand;')
46
53
  .replace(
47
54
  '#include <clipping_planes_fragment>',
48
- `#include <clipping_planes_fragment>\n${handedOver(beyond, nearShare('length(vViewPosition)', band))}`,
55
+ `#include <clipping_planes_fragment>\n{ float rwNear = 1.0 - smoothstep(uReach - uHalfBand, uReach + uHalfBand, length(vViewPosition));\n${handedOver('rwNear')} }`,
49
56
  );
50
57
  };
51
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + (beyond ? ':beyond-reach:' : ':within-reach:') + band;
58
+ variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':reach';
52
59
  return variant;
53
60
  }
54
61
  // The same for the instances of an InstancedMesh, each handed over whole and in its own time, using its geometry's `aNear` (an instanced attribute, 0 to 1) is the near version's share of the instance's
55
62
  // pixels, which its builder moves from the one end to the other over a moment once the viewer comes within or goes beyond its
56
63
  // reach. An instance its version does not draw at all has its vertices put out of sight. handOverShadow gives the near or far
57
64
  // version's shadow body, which casts wherever its version draws anything: while an instance is handed over both cast, and their
58
- // shadows, of one shape in two levels of detail, lie over each other.
65
+ // shadows, of one shape in two levels of detail, lie over each other. Both sides share one colour and one shadow program via `uBeyond`.
59
66
  const handing = new WeakMap();
60
67
  export function handOverOf(base, beyond = false) {
61
68
  let variants = handing.get(base);
62
69
  if (!variants) handing.set(base, (variants = {}));
63
70
  if (variants[beyond]) return variants[beyond];
64
- const variant = (variants[beyond] = base.clone());
71
+ const variant = (variants[beyond] = base.clone()),
72
+ beyondUniform = { value: beyond ? 1 : 0 };
65
73
  variant.onBeforeCompile = (shader, renderer) => {
66
74
  base.onBeforeCompile(shader, renderer);
67
- handOverVertices(shader, beyond);
75
+ handOverVertices(shader, beyondUniform);
68
76
  shader.fragmentShader = shader.fragmentShader
69
- .replace('#include <common>', '#include <common>\nvarying float vNearShare;')
70
- .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\n${handedOver(beyond, 'vNearShare')}`);
77
+ .replace('#include <common>', '#include <common>\nvarying float vNearShare;\nuniform float uBeyond;')
78
+ .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\n${handedOver('vNearShare')}`);
71
79
  };
72
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + (beyond ? ':handed-far' : ':handed-near');
80
+ variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':handed';
73
81
  return variant;
74
82
  }
75
83
  export function handOverShadow(beyond = false) {
76
- const variant = new THREE.MeshDepthMaterial();
77
- variant.onBeforeCompile = shader => handOverVertices(shader, beyond);
78
- variant.customProgramCacheKey = () => (beyond ? 'handed-far-depth' : 'handed-near-depth');
84
+ const variant = new THREE.MeshDepthMaterial(),
85
+ beyondUniform = { value: beyond ? 1 : 0 };
86
+ variant.onBeforeCompile = shader => handOverVertices(shader, beyondUniform);
87
+ variant.customProgramCacheKey = () => 'handed-depth';
79
88
  return variant;
80
89
  }
81
- // The near version's share, 1 short of the band about uReach and 0 past it, at a distance (a GLSL expression) from the eye
82
- const nearShare = (distance, band) => `1.0 - smoothstep(uReach - ${(band / 2).toFixed(2)}, uReach + ${(band / 2).toFixed(2)}, ${distance})`;
83
- // The fragment's test: the near version keeps the scatter's pixels under its share, the far version the rest
84
- const handedOver = (beyond, share) => `if (${SCATTER} ${beyond ? '<' : '>='} ${share}) discard;`;
90
+ // The fragment's test: the near version (`uBeyond <= 0.5`) keeps the scatter's pixels under its share, the far version the rest
91
+ const handedOver = share => `if (uBeyond > 0.5 ? (${SCATTER} < ${share}) : (${SCATTER} >= ${share})) discard;`;
85
92
  // Hands an instance's share (aNear) to the fragments (vNearShare), and puts the vertices of an instance its version does not draw
86
93
  // at all out of sight.
87
- function handOverVertices(shader, beyond) {
94
+ function handOverVertices(shader, beyondUniform) {
95
+ shader.uniforms.uBeyond = beyondUniform;
88
96
  shader.vertexShader = shader.vertexShader
89
- .replace('#include <common>', '#include <common>\nattribute float aNear;\nvarying float vNearShare;')
97
+ .replace('#include <common>', '#include <common>\nattribute float aNear;\nvarying float vNearShare;\nuniform float uBeyond;')
90
98
  .replace(
91
99
  '#include <project_vertex>',
92
- `#include <project_vertex>\nvNearShare = aNear;\nif (aNear ${beyond ? '>= 1.0' : '<= 0.0'}) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);`,
100
+ `#include <project_vertex>\nvNearShare = aNear;\nif (uBeyond > 0.5 ? (aNear >= 1.0) : (aNear <= 0.0)) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);`,
93
101
  );
94
102
  }
95
103
  // The same material for meshes of another kind (kind: 'plain', 'instanced', or 'tinted' for instances with a colour each), drawn as
@@ -107,3 +115,19 @@ export function twinMaterial(base, kind) {
107
115
  }
108
116
  return variants[kind];
109
117
  }
118
+
119
+ /**
120
+ * Attach a unit-white `instanceColor` buffer `(1, 1, 1)` to an `InstancedMesh` so untinted instanced meshes
121
+ * share `USE_INSTANCING_COLOR` WebGL programs with tinted batches of the same material without changing shading.
122
+ *
123
+ * @template {THREE.InstancedMesh} T
124
+ * @param {T} mesh
125
+ * @returns {T}
126
+ */
127
+ export function whiteInstanceColor(mesh) {
128
+ if (!mesh.instanceColor) {
129
+ const count = mesh.instanceMatrix.count;
130
+ mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(count * 3).fill(1), 3);
131
+ }
132
+ return mesh;
133
+ }
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Road convoy rendering and lifecycle controller paired with `createRoadTraffic`: registers convoy travellers
3
+ * into a world's crowd system, lazily raises instanced horses, oxen, carts and wagons when the viewer approaches,
4
+ * warms vehicle shaders before first draw, and updates every convoy member per frame with zero allocations.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { mulberry32 } from '../math/random.js';
10
+ import { ROAD_TRAFFIC, createRoadTraffic } from '../motion/road-traffic.js';
11
+
12
+ /**
13
+ * Default ox coat colours (sRGB hex) assigned randomly to draught teams pulling carts and wagons.
14
+ */
15
+ export const DEFAULT_TRAFFIC_OXEN = Object.freeze([0x8a6a4a, 0x6a5040, 0xb0a090, 0x5a4232, 0x9a8a70]);
16
+
17
+ /**
18
+ * Number of draught oxen harnessed to each vehicle kind.
19
+ */
20
+ export const OXEN_DRAWING = Object.freeze({ cart: 1, wagon: 2 });
21
+
22
+ /**
23
+ * Builds a road-traffic convoy renderer and per-frame updater for one land or space.
24
+ *
25
+ * Each entry `[roadId, convoyKind]` places a convoy from `specs[convoyKind]` along `roads`, registers its walkers and
26
+ * riders with `addCrowd`, and lazily invokes `loadAssets()` once the camera comes within `raise` metres of any convoy.
27
+ * Vehicle groups are warmed through `warmShaders` on the first frame a cart or wagon is seen.
28
+ *
29
+ * @param {object} options
30
+ * @param {Array<[string, string]>} options.entries Pairs `[roadId, convoyKind]` to populate on the land's roads.
31
+ * @param {Record<string, { pace: number, body?: string, members: Array<[string, number, number]> }>} options.specs Convoy templates keyed by `convoyKind`.
32
+ * @param {Array<{ id: string, pts: Array<[number, number]> }>} options.roads Road polylines with ids matching `entries`.
33
+ * @param {(x: number, z: number) => number} options.ground Surface elevation sampler in metres.
34
+ * @param {THREE.Group} options.group Parent group receiving the lazily raised convoy mounts, herd and vehicles group.
35
+ * @param {THREE.Camera} options.camera Viewer camera whose position controls lazy raise and draw distance.
36
+ * @param {(people: object[], tones: number[], cx: number, cz: number, near: number, kind: string, beasts: unknown, spaceId: string) => object} options.addCrowd Crowd registration callback that converts traveller specs into live crowd figures in place.
37
+ * @param {() => Promise<{ makeHerd?: Function, makeMounts?: Function, orderBeasts?: Function, makeVehicles?: Function }> | { makeHerd?: Function, makeMounts?: Function, orderBeasts?: Function, makeVehicles?: Function }} [options.loadAssets=() => ({})] Lazy loader returning the beast and vehicle instancing builders; a vehicle or beast with no builder is not drawn.
38
+ * @param {string} [options.spaceId='world'] Space identifier forwarded to `addCrowd`.
39
+ * @param {() => number} [options.random] Repeatable PRNG stream for convoy spacing, traveller variation and coat picks.
40
+ * @param {number[]} [options.tones] Garment palette (sRGB hex) forwarded to `addCrowd`.
41
+ * @param {((crowd: object, bodyId: string) => void) | null} [options.nameBody=null] Optional nameplate binder for convoys whose spec sets `body`.
42
+ * @param {(rank: number) => boolean} [options.isTravelling] Daily schedule predicate receiving convoy `rank` in `[0, 1)`.
43
+ * @param {(x: number, y: number, z: number, radius: number, shadow: boolean, exact: boolean) => boolean} [options.inView] Frustum/visibility test for individual convoy members.
44
+ * @param {(group: THREE.Group) => Promise<void>} [options.warmShaders] Async shader warm-up hook called before vehicle meshes enter the scene.
45
+ * @param {Array<number | THREE.Color>} [options.oxCoats=DEFAULT_TRAFFIC_OXEN] Draught ox coat colours.
46
+ * @param {number} [options.drawn=ROAD_TRAFFIC.drawn] Distance in metres from `camera` within which beasts and vehicles draw.
47
+ * @param {number} [options.raise=ROAD_TRAFFIC.raise] Distance in metres from `camera` that triggers `loadAssets()`.
48
+ * @param {number} [options.minSpan=30] Minimum usable road length (after trimming both ends) in metres.
49
+ * @param {object} [options.trafficOptions] Optional parameters forwarded to `createRoadTraffic`.
50
+ * @returns {{ tick: (dt: number) => void, convoys: object[], dispose: () => void } | null}
51
+ */
52
+ export function createRoadTrafficRenderer({
53
+ entries,
54
+ specs,
55
+ roads,
56
+ ground,
57
+ group,
58
+ camera,
59
+ addCrowd,
60
+ loadAssets = () => ({}),
61
+ spaceId = 'world',
62
+ random = mulberry32(61),
63
+ tones = [0x8a6a48, 0x6a5a44, 0x7a6a4a],
64
+ nameBody = null,
65
+ isTravelling = () => true,
66
+ inView = () => true,
67
+ warmShaders = () => Promise.resolve(),
68
+ oxCoats = DEFAULT_TRAFFIC_OXEN,
69
+ drawn: drawnRange = ROAD_TRAFFIC.drawn,
70
+ raise: raiseRange = ROAD_TRAFFIC.raise,
71
+ minSpan = 30,
72
+ trafficOptions = {},
73
+ }) {
74
+ if (!entries?.length) return null;
75
+
76
+ const { road: roadOf, setOut, traveller: travellerOf, placeOn, goOn } = createRoadTraffic(trafficOptions),
77
+ trim = trafficOptions.trim ?? ROAD_TRAFFIC.trim,
78
+ team = ROAD_TRAFFIC.team,
79
+ shafts = ROAD_TRAFFIC.shafts,
80
+ drawnSq = drawnRange * drawnRange,
81
+ raiseSq = raiseRange * raiseRange,
82
+ oxen = oxCoats.map(c => (c && c.isColor ? c : new THREE.Color(c))),
83
+ byId = new Map(),
84
+ onRoad = new Map(), // convoys per road so each sets out spaced along it
85
+ convoys = [],
86
+ folk = [], // travellers of every unnamed convoy share one crowd
87
+ named = [], // each convoy with a spec `body` gets its own crowd for its nameplate
88
+ counts = { cart: 0, wagon: 0, rider: 0, walker: 0, ox: 0 };
89
+
90
+ for (let i = 0; i < entries.length; i++) {
91
+ const id = entries[i][0];
92
+ onRoad.set(id, (onRoad.get(id) ?? 0) + 1);
93
+ }
94
+ const placed = new Map();
95
+ for (let i = 0; i < entries.length; i++) {
96
+ const [id, kind] = entries[i],
97
+ r = roads.find(q => q.id === id),
98
+ k = placed.get(id) ?? 0;
99
+ placed.set(id, k + 1);
100
+ if (!r) continue;
101
+ if (!byId.has(id)) byId.set(id, roadOf(r.pts, ground));
102
+ const road = byId.get(id),
103
+ spec = specs[kind],
104
+ span = road.way.length - 2 * trim;
105
+ if (!spec || span < minSpan) continue;
106
+ const c = setOut(road, spec.pace, { order: k, count: onRoad.get(id), random });
107
+ c.spec = spec;
108
+ c.members = [];
109
+ let front = -Infinity,
110
+ back = Infinity;
111
+ for (let j = 0; j < spec.members.length; j++) {
112
+ const ahead = spec.members[j][1];
113
+ if (ahead > front) front = ahead;
114
+ if (ahead < back) back = ahead;
115
+ }
116
+ c.front = front;
117
+ c.back = back;
118
+ const people = spec.body ? [] : folk;
119
+ if (spec.body) named.push({ people, body: spec.body });
120
+ for (let j = 0; j < spec.members.length; j++) {
121
+ const [what, ahead, side] = spec.members[j],
122
+ m = { what, ahead, side, figure: null, people, at: 0, coat: (random() * 97) | 0, tint: oxen[(random() * oxen.length) | 0] };
123
+ c.members.push(m);
124
+ if (what === 'walker' || what === 'rider') {
125
+ m.at = people.length;
126
+ people.push((m.figure = travellerOf(what, spec.pace, random)));
127
+ }
128
+ counts[what] = (counts[what] ?? 0) + 1;
129
+ counts.ox += OXEN_DRAWING[what] ?? 0;
130
+ }
131
+ convoys.push(c);
132
+ }
133
+ if (!convoys.length) return null;
134
+
135
+ if (folk.length) addCrowd(folk, tones, 0, 0, Infinity, 'plain', null, spaceId);
136
+ for (let i = 0; i < named.length; i++) {
137
+ const crowd = addCrowd(named[i].people, tones, 0, 0, Infinity, 'plain', null, spaceId);
138
+ if (nameBody) nameBody(crowd, named[i].body);
139
+ }
140
+ // Each crowd replaced its traveller entries with live crowd figures: keep direct references.
141
+ for (let i = 0; i < convoys.length; i++) {
142
+ const members = convoys[i].members;
143
+ for (let j = 0; j < members.length; j++) if (members[j].figure) members[j].figure = members[j].people[members[j].at];
144
+ }
145
+ const everyone = folk.concat(...named.map(n => n.people));
146
+
147
+ let drawn = null,
148
+ asked = false,
149
+ disposed = false;
150
+
151
+ const raise = async () => {
152
+ const { makeHerd, makeMounts, orderBeasts, makeVehicles } = await loadAssets();
153
+ if (disposed) return;
154
+ const beasts = orderBeasts ? orderBeasts() : null,
155
+ convoy = new THREE.Group(),
156
+ vehicles = new THREE.Group(),
157
+ carts = counts.cart && makeVehicles ? makeVehicles(vehicles, counts.cart, 'cart', random) : null,
158
+ wagons = counts.wagon && makeVehicles ? makeVehicles(vehicles, counts.wagon, 'wagon', random) : null;
159
+ await beasts;
160
+ if (disposed) return;
161
+ let preparing;
162
+ drawn = {
163
+ convoy,
164
+ mounts: counts.rider && makeMounts ? makeMounts(convoy, counts.rider, 0) : null,
165
+ herd: counts.ox && makeHerd ? makeHerd(convoy, counts.ox) : null,
166
+ carts,
167
+ wagons,
168
+ vehiclesReady: false,
169
+ prepareVehicles() {
170
+ // A passing rider can raise the convoy while every cart is outside the view.
171
+ preparing ??= warmShaders(vehicles).then(() => {
172
+ if (disposed) return;
173
+ convoy.add(vehicles);
174
+ drawn.vehiclesReady = true;
175
+ });
176
+ },
177
+ };
178
+ group.add(convoy);
179
+ // A rider is drawn from the frame there is a horse under them (`out: -1` lets the crowd show them at once).
180
+ for (let i = 0; i < everyone.length; i++) {
181
+ const f = everyone[i];
182
+ if (f.mounted) {
183
+ f.home = undefined;
184
+ f.out = -1;
185
+ }
186
+ }
187
+ everyone.length = 0; // release the setup-only traveller list once riders are revealed
188
+ };
189
+
190
+ function drawVehicle(c, m, p) {
191
+ if (!drawn.vehiclesReady) {
192
+ drawn.prepareVehicles();
193
+ return;
194
+ }
195
+ const { x, y, z, yaw } = p;
196
+ // a builder a world left out draws nothing of its kind: the people still walk
197
+ if (m.what === 'cart') {
198
+ drawn.carts?.vehicle(x, y, z, yaw, c.travel);
199
+ const ox = placeOn(c, m.ahead + shafts, m.side);
200
+ drawn.herd?.beast(ox.x, ox.y, ox.z, ox.yaw, c.v, c.travel, m.tint, 1);
201
+ return;
202
+ }
203
+ drawn.wagons?.vehicle(x, y, z, yaw, c.travel);
204
+ for (let side = -1; side <= 1; side += 2) {
205
+ const ox = placeOn(c, m.ahead + team.ahead, m.side + team.apart * side);
206
+ drawn.herd?.beast(ox.x, ox.y, ox.z, ox.yaw, c.v, c.travel + side * 0.3, m.tint, 1);
207
+ }
208
+ }
209
+
210
+ function moveMembers(c) {
211
+ const show = drawn && c.near,
212
+ members = c.members;
213
+ for (let i = 0; i < members.length; i++) {
214
+ const m = members[i],
215
+ p = placeOn(c, m.ahead, m.side),
216
+ seen = show && inView(p.x, p.y + 1, p.z, 3.4, false, true);
217
+ if (m.figure) {
218
+ const g = m.figure;
219
+ g.ax = p.x;
220
+ g.az = p.z;
221
+ g.yaw = p.yaw;
222
+ g.speed = c.v; // walking at the convoy's pace, or standing (0)
223
+ g.travel = c.travel + g.ph;
224
+ if (m.what === 'rider' && seen) drawn.mounts?.horse(p.x, p.y, p.z, p.yaw, c.v, c.travel + g.ph, m.coat, g.s, 0);
225
+ } else if (seen) drawVehicle(c, m, p);
226
+ }
227
+ }
228
+
229
+ function tick(dt) {
230
+ if (disposed) return;
231
+ const cx = camera.position.x,
232
+ cz = camera.position.z;
233
+ if (drawn) {
234
+ drawn.mounts?.begin();
235
+ drawn.herd?.begin();
236
+ drawn.carts?.begin();
237
+ drawn.wagons?.begin();
238
+ }
239
+ for (let i = 0; i < convoys.length; i++) {
240
+ const c = convoys[i],
241
+ head = placeOn(c, 0, 0),
242
+ d2 = (head.x - cx) ** 2 + (head.z - cz) ** 2;
243
+ if (!asked && d2 < raiseSq) {
244
+ asked = true;
245
+ raise();
246
+ }
247
+ c.near = d2 < drawnSq;
248
+ goOn(c, dt, convoys, isTravelling(c.rank));
249
+ moveMembers(c);
250
+ }
251
+ if (drawn) {
252
+ drawn.mounts?.end();
253
+ drawn.herd?.end();
254
+ drawn.carts?.end();
255
+ drawn.wagons?.end();
256
+ }
257
+ }
258
+
259
+ function dispose() {
260
+ disposed = true;
261
+ if (drawn?.convoy) group.remove(drawn.convoy);
262
+ drawn = null;
263
+ everyone.length = 0;
264
+ convoys.length = 0;
265
+ }
266
+
267
+ return { tick, convoys, dispose };
268
+ }
@@ -9,6 +9,7 @@ import * as THREE from 'three';
9
9
  import { TAU, clamp } from '../math/scalar.js';
10
10
  import { evaluateBallisticLodge, sampleBallisticFlight, solveBallisticLodge } from '../motion/ballistic-arc.js';
11
11
  import { buildArrowGeometry, buildKnifeGeometry, buildQuarrelGeometry } from '../geometry/projectile-shapes.js';
12
+ import { whiteInstanceColor } from './material-lod.js';
12
13
 
13
14
  const SHUDDER_SECONDS = 0.28,
14
15
  HIDDEN_MATRIX = new THREE.Matrix4().makeScale(0, 0, 0),
@@ -52,6 +53,7 @@ export function createProjectilePool({
52
53
  onGroundHit = null,
53
54
  maxPerKind = 32,
54
55
  layer = 1,
56
+ tinted = false,
55
57
  } = {}) {
56
58
  const _to = new THREE.Vector3(),
57
59
  _pos = new THREE.Vector3(),
@@ -100,6 +102,7 @@ export function createProjectilePool({
100
102
 
101
103
  function makePoolMesh(geo, material) {
102
104
  const m = new THREE.InstancedMesh(geo, material, maxPerKind + 1);
105
+ if (tinted) whiteInstanceColor(m);
103
106
  m.setMatrixAt(0, HIDDEN_MATRIX);
104
107
  m.count = 1;
105
108
  m.frustumCulled = false;
@@ -61,7 +61,12 @@ export function createTowns({ shapes, farMaterial, gableMaterial, towns = [] })
61
61
  for (let i = 0; i < list.length; i++) if (!wall || (list[i].wall || 0) === k) count++;
62
62
  if (!count) continue;
63
63
  // every town draws the same unit shapes, each part through a view of its own (geometryView)
64
- const im = new THREE.InstancedMesh(geometryView(shapes[type]), material, count);
64
+ const geo = geometryView(shapes[type]);
65
+ if (material.vertexColors && !geo.attributes.color) {
66
+ const verts = geo.attributes.position.count;
67
+ geo.setAttribute('color', new THREE.BufferAttribute(new Uint8Array(verts * 3).fill(255), 3, true));
68
+ }
69
+ const im = new THREE.InstancedMesh(geo, material, count);
65
70
  let n = 0;
66
71
  for (let i = 0; i < list.length; i++) {
67
72
  const b = list[i];
@@ -6,12 +6,12 @@
6
6
  import * as THREE from 'three';
7
7
  import { dim } from '../math/color.js';
8
8
  import { sstep } from '../math/scalar.js';
9
- import { GB, meshOf } from '../geometry/builder.js';
9
+ import { GB, meshOf, padParts } from '../geometry/builder.js';
10
10
  import { C } from '../geometry/primitives.js';
11
11
  import { shipLines } from '../geometry/ship-lines.js';
12
12
  import { gripOf, oarMatrix, oarPorts, oarPose } from '../geometry/ship-oars.js';
13
13
  import { YARD_APART } from '../geometry/ship-rig.js';
14
- import { twinMaterial } from './material-lod.js';
14
+ import { twinMaterial, whiteInstanceColor } from './material-lod.js';
15
15
 
16
16
  const _stretch = new THREE.Matrix4(),
17
17
  _m = new THREE.Matrix4();
@@ -34,6 +34,8 @@ const runHere = (job, inputOf, here) => Promise.resolve().then(here);
34
34
  * @param {(job: string, inputOf: () => object, here: () => object) => Promise<object>} [options.runOrHere] - Runs a job on a
35
35
  * worker pool, or `here()` on the page where there is none (as `createPool().runOrHere`). The page by default.
36
36
  * @param {string} [options.job] - The pool's job that answers `{ spec, options }` with `kit.shipParts(spec, options)`.
37
+ * @param {boolean} [options.padded=false] - Pad compact byte normals and colours on static ship meshes to 4 bytes per vertex
38
+ * so they align on 4-byte GPU strides and share vertex-alpha programs with padded settlement blocks.
37
39
  * @returns {{ buildShip: Function, orderShip: Function, shipOf: Function, raiseOars: Function }} buildShip(spec, options) a
38
40
  * ship now; orderShip(spec, options) the promise of her, built by the pool; shipOf(spec, options, parts) one from her arrays;
39
41
  * raiseOars(parent, spec, lines) her oars to pull. A ship is `{ group, set, setOther, furl, yard, stow, half, lines,
@@ -42,7 +44,7 @@ const runHere = (job, inputOf, here) => Promise.resolve().then(here);
42
44
  * `moving` (oars left out, to be rowed), `tacks` (lateen sails set on both sides), `yardApart` (the lateen yard built apart,
43
45
  * hoisted or stowed), `riding` (the riding light, a group to take in when she puts out).
44
46
  */
45
- export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere = runHere, job = 'ship' }) {
47
+ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere = runHere, job = 'ship', padded = false, tinted = false }) {
46
48
  // The spec a boat with a lateen yard is built from when the yard is to stand apart from her hull (`yardApart`: a boat that
47
49
  // both sails and lies): the yard, the sail furled on it and its hoisted ropes are left out of her own builders, and shipOf
48
50
  // builds them of their own in both poses.
@@ -58,7 +60,7 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
58
60
  function shipOf(spec, { far = false, yardApart = false }, parts) {
59
61
  const group = new THREE.Group(),
60
62
  lines = shipLines(spec),
61
- mesh = (p, mat, shadow = !far, parent = group) => (p ? meshOf(p, mat, parent, shadow) : null);
63
+ mesh = (p, mat, shadow = !far, parent = group) => (p ? meshOf(padded ? padParts(p) : p, mat, parent, shadow) : null);
62
64
  mesh(parts.wood, materials.wood);
63
65
  mesh(parts.rope, materials.cloth, false); // rope and iron cast none: a line a few centimetres thick is finer than the shadow map, and its shadow falls as dark smears
64
66
  mesh(parts.glass, materials.glass, false);
@@ -88,8 +90,8 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
88
90
  if (parts.ride) {
89
91
  ship.ridingLight = new THREE.Group();
90
92
  group.add(ship.ridingLight);
91
- meshOf(parts.ride.glass, materials.glass, ship.ridingLight, false);
92
- meshOf(parts.ride.iron, materials.cloth, ship.ridingLight, !far);
93
+ mesh(parts.ride.glass, materials.glass, false, ship.ridingLight);
94
+ mesh(parts.ride.iron, materials.cloth, !far, ship.ridingLight);
93
95
  }
94
96
  if (!spec.open) {
95
97
  const ladder = 1.5, // metres of deck over which a ladder climbs
@@ -118,7 +120,8 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
118
120
  const ports = oarPorts(spec, lines),
119
121
  colour = dim(C(spec.deckTone), 0.85),
120
122
  instanced = (gb, count) => {
121
- const mesh = new THREE.InstancedMesh(gb.build(), twinMaterial(materials.wood, 'instanced'), count);
123
+ const mesh = new THREE.InstancedMesh(gb.build(), twinMaterial(materials.wood, tinted ? 'tinted' : 'instanced'), count);
124
+ if (tinted) whiteInstanceColor(mesh);
122
125
  mesh.castShadow = mesh.receiveShadow = true;
123
126
  mesh.frustumCulled = false; // its instances spread wider than its geometry's bounds
124
127
  parent.add(mesh);
@@ -8,6 +8,7 @@ import { C, TRS } from '../geometry/primitives.js';
8
8
  import { litShare } from '../math/lit-share.js';
9
9
  import { sstep, TAU } from '../math/scalar.js';
10
10
  import { createLightPoints } from './light-points.js';
11
+ import { whiteInstanceColor } from './material-lod.js';
11
12
  import { falloffAt, pixelTexture } from './textures.js';
12
13
 
13
14
  /** The iron of a lamp's post and lantern, and its burner. */
@@ -107,6 +108,7 @@ export function createStreetLamps({
107
108
  seed = i => (i * 0.618034) % 1,
108
109
  points: more = {},
109
110
  iron = LAMP_IRON,
111
+ tinted = false,
110
112
  }) {
111
113
  const n = lamps.length;
112
114
  const post = new GB();
@@ -120,7 +122,8 @@ export function createStreetLamps({
120
122
  post.add(U.box, C(iron.post), TRS(Math.cos(a) * 0.19, 3.28, Math.sin(a) * 0.19, 0.035, 0.46, 0.035));
121
123
  } // four bars between them,
122
124
  post.add(U.cyl6, C(iron.burner), TRS(0, 3.3, 0, 0.045, MANTLE.burner, 0.045)); // and the burner the mantle sits on
123
- const posts = new THREE.InstancedMesh(geometryOf(indexParts(post.parts(!post.wide))), postMaterial, n);
125
+ const posts = new THREE.InstancedMesh(geometryOf(indexParts(post.flatten().parts(!post.wide))), postMaterial, n);
126
+ if (tinted) whiteInstanceColor(posts);
124
127
  const pos = new Float32Array(n * 3),
125
128
  seeds = new Float32Array(n);
126
129
  const mantles = new THREE.InstancedMesh(mantleGeometry(), mantleMaterial(FLAME, uniforms), n);