@bendyline/molen-client 0.0.9 → 0.0.10

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,172 @@
1
+ import { modelSignalDerivedSchema } from "@bendyline/molen-schema";
2
+ //#region src/model-signal-expressions.ts
3
+ function evaluate(expression, values) {
4
+ const args = expression.args.map((arg) => typeof arg === "number" ? arg : Object.hasOwn(values, arg) ? values[arg] : void 0);
5
+ const [a, b, c] = args;
6
+ if (expression.op === "if") return a === void 0 ? void 0 : a !== 0 ? b : c;
7
+ if (expression.op === "coalesce") return args.find((value) => value !== void 0);
8
+ if (args.some((value) => value === void 0)) return void 0;
9
+ const numbers = args;
10
+ const x = a, y = b, z = c;
11
+ switch (expression.op) {
12
+ case "add": return numbers.reduce((sum, value) => sum + value, 0);
13
+ case "subtract": return x - y;
14
+ case "multiply": return numbers.reduce((product, value) => product * value, 1);
15
+ case "divide": return y === 0 ? void 0 : x / y;
16
+ case "min": return Math.min(...numbers);
17
+ case "max": return Math.max(...numbers);
18
+ case "clamp": return y > z ? void 0 : Math.max(y, Math.min(z, x));
19
+ case "abs": return Math.abs(x);
20
+ case "sqrt": return x < 0 ? void 0 : Math.sqrt(x);
21
+ case "floor": return Math.floor(x);
22
+ case "modulo": return y <= 0 ? void 0 : (x % y + y) % y;
23
+ case "sin": return Math.sin(x);
24
+ case "cos": return Math.cos(x);
25
+ case "atan2": return Math.atan2(x, y);
26
+ case "less": return Number(x < y);
27
+ case "greater": return Number(x > y);
28
+ case "equal": return Number(x === y);
29
+ case "and": return Number(numbers.every((value) => value !== 0));
30
+ case "or": return Number(numbers.some((value) => value !== 0));
31
+ case "not": return Number(x === 0);
32
+ }
33
+ }
34
+ /** Compile a bounded dependency graph once. Evaluation is read-only and never executes code. */
35
+ function compileModelSignalExpressions(definitions) {
36
+ const derived = modelSignalDerivedSchema.parse(definitions ?? {});
37
+ const order = [], visited = /* @__PURE__ */ new Set();
38
+ const visit = (name) => {
39
+ if (visited.has(name)) return;
40
+ visited.add(name);
41
+ const expression = derived[name];
42
+ if (!expression) return;
43
+ for (const arg of expression.args) if (typeof arg === "string" && Object.hasOwn(derived, arg)) visit(arg);
44
+ order.push([name, expression]);
45
+ };
46
+ for (const name of Object.keys(derived)) visit(name);
47
+ return (sources) => {
48
+ const values = Object.create(null);
49
+ for (const [name, value] of Object.entries(sources)) if (typeof value === "number" && Number.isFinite(value)) values[name] = value;
50
+ for (const [name, expression] of order) {
51
+ const value = evaluate(expression, values);
52
+ values[name] = value !== void 0 && Number.isFinite(value) ? value : void 0;
53
+ }
54
+ return values;
55
+ };
56
+ }
57
+ //#endregion
58
+ //#region src/model-signals.ts
59
+ /** Read data only: no expressions, evaluation, prototype traversal, or simulation writes. */
60
+ function readModelSignals(sources, readComponent) {
61
+ const signals = Object.create(null);
62
+ for (const [name, source] of Object.entries(sources ?? {})) {
63
+ signals[name] = void 0;
64
+ signals[name] = void 0;
65
+ let value = readComponent(source.component);
66
+ for (const part of source.path) {
67
+ if (value === null || typeof value !== "object" || !Object.hasOwn(value, part)) {
68
+ value = void 0;
69
+ break;
70
+ }
71
+ value = value[part];
72
+ }
73
+ if (typeof value === "boolean") signals[name] = Number(value);
74
+ else if (typeof value === "number" && Number.isFinite(value)) signals[name] = value;
75
+ }
76
+ return signals;
77
+ }
78
+ /**
79
+ * A binding's displacement for a signal, before its limits: linear in the signal, or along its
80
+ * keyframed curve, which holds its end values outside the keys. Exported for tests.
81
+ */
82
+ function modelSignalDisplacement(binding, signal) {
83
+ const keys = binding.keys;
84
+ if (keys === void 0) return signal * (binding.scale ?? 1) + (binding.offset ?? 0);
85
+ const first = keys[0];
86
+ const last = keys[keys.length - 1];
87
+ if (first === void 0 || last === void 0) return 0;
88
+ if (signal <= first[0]) return first[1];
89
+ if (signal >= last[0]) return last[1];
90
+ let index = 1;
91
+ while (index < keys.length - 1 && signal > (keys[index]?.[0] ?? Infinity)) index++;
92
+ const [x0, y0] = keys[index - 1] ?? first;
93
+ const [x1, y1] = keys[index] ?? last;
94
+ let f = (signal - x0) / (x1 - x0);
95
+ if (binding.ease === "smooth") f = f * f * (3 - 2 * f);
96
+ return y0 + (y1 - y0) * f;
97
+ }
98
+ /** Model-agnostic; moves existing geometry without creating a cockpit or changing physics. */
99
+ function createModelSignalVisual(model, spec) {
100
+ const derive = compileModelSignalExpressions(spec.derived);
101
+ let missingSignals = [];
102
+ const nodes = /* @__PURE__ */ new Map();
103
+ model.traverse((node) => {
104
+ const matches = nodes.get(node.name) ?? [];
105
+ matches.push(node);
106
+ nodes.set(node.name, matches);
107
+ });
108
+ const missingNodes = [...new Set(spec.bindings.map((b) => b.node))].filter((name) => !nodes.has(name));
109
+ const bindings = spec.bindings.flatMap((binding) => (nodes.get(binding.node) ?? []).map((node) => {
110
+ node.matrixAutoUpdate = true;
111
+ return {
112
+ binding,
113
+ node,
114
+ rest: binding.property === "visible" ? Number(node.visible) : node[binding.property][binding.axis ?? "z"],
115
+ current: void 0,
116
+ time: void 0
117
+ };
118
+ }));
119
+ return {
120
+ missingNodes,
121
+ get missingSignals() {
122
+ return missingSignals;
123
+ },
124
+ update(sources, timeSeconds) {
125
+ const signals = derive(sources);
126
+ const missing = /* @__PURE__ */ new Set();
127
+ const time = timeSeconds !== void 0 && Number.isFinite(timeSeconds) ? timeSeconds : void 0;
128
+ for (const state of bindings) {
129
+ const { binding, node, rest } = state;
130
+ const write = (value) => {
131
+ if (binding.property === "visible") node.visible = value > 0;
132
+ else node[binding.property][binding.axis ?? "z"] = value;
133
+ };
134
+ const signal = signals[binding.source];
135
+ const raw = signal === void 0 ? NaN : modelSignalDisplacement(binding, signal);
136
+ if (!Number.isFinite(raw)) {
137
+ missing.add(binding.source);
138
+ state.time = void 0;
139
+ if (binding.missing === "rest" || binding.missing === "hide") {
140
+ write(binding.missing === "hide" ? 0 : rest);
141
+ state.current = void 0;
142
+ } else write(state.current === void 0 ? rest : binding.property === "visible" ? state.current : rest + state.current);
143
+ continue;
144
+ }
145
+ let value = Math.max(binding.min ?? -Infinity, Math.min(binding.max ?? Infinity, raw));
146
+ const period = binding.period;
147
+ const wrap = (v) => period === void 0 ? v : (v % period + period) % period;
148
+ value = wrap(value);
149
+ if (binding.responseSeconds && time !== void 0 && state.time !== void 0 && time >= state.time && state.current !== void 0) {
150
+ let delta = value - state.current;
151
+ if (period !== void 0) delta = ((delta + period / 2) % period + period) % period - period / 2;
152
+ value = wrap(state.current + delta * -Math.expm1(-(time - state.time) / binding.responseSeconds));
153
+ }
154
+ state.current = value;
155
+ state.time = time;
156
+ write(binding.property === "visible" ? value : rest + value);
157
+ }
158
+ missingSignals = [...missing];
159
+ },
160
+ reset() {
161
+ for (const state of bindings) {
162
+ const { binding, node, rest } = state;
163
+ if (binding.property === "visible") node.visible = rest > 0;
164
+ else node[binding.property][binding.axis ?? "z"] = rest;
165
+ state.current = state.time = void 0;
166
+ }
167
+ missingSignals = [];
168
+ }
169
+ };
170
+ }
171
+ //#endregion
172
+ export { compileModelSignalExpressions as i, modelSignalDisplacement as n, readModelSignals as r, createModelSignalVisual as t };
@@ -30,6 +30,10 @@ declare function viewNeedsImmediateUpdate(previousPosition: NavigationVector, pr
30
30
  * Rendered roads, walls and portal covers can overlap. An octree copies each triangle into
31
31
  * every intersecting cell and repeatedly splits those copies, causing long rebuild stalls.
32
32
  * A balanced bounding-volume tree stores each triangle once, even for coincident surfaces.
33
+ *
34
+ * Triangle bounds and centers live in flat arrays and each split selects its median instead of
35
+ * sorting: an aircraft's neighborhood over dense ground cover held 170k triangles, and sorting
36
+ * them at every level of the tree took 700 ms of one frame.
33
37
  */
34
38
  declare class CollisionTree extends Octree {
35
39
  override build(): this;
@@ -168,6 +172,7 @@ declare const NAVIGATION_ACTIONS: {
168
172
  readonly engine: "nav-engine";
169
173
  readonly gear: "nav-gear";
170
174
  readonly flaps: "nav-flaps";
175
+ readonly vector: "nav-vector";
171
176
  readonly recover: "nav-recover";
172
177
  };
173
178
  /** The navigation modes with a default input profile. */
@@ -192,6 +197,8 @@ interface PilotInput {
192
197
  engine: number;
193
198
  gear: number;
194
199
  flaps: number;
200
+ /** Powered-lift lever advances through 0, 25, 50, 75, 100 percent on each press. */
201
+ vector?: number;
195
202
  recover: number;
196
203
  }
197
204
  /** Everything a navigation controller reads in one frame. */
@@ -496,6 +503,13 @@ interface WalkCollisionOptions {
496
503
  rescanIntervalMs?: number;
497
504
  /** Clock for the rescan interval, ms (default `performance.now`). */
498
505
  now?: () => number;
506
+ /**
507
+ * Collide with each instance of an instanced mesh as its bounding box, twelve triangles, instead
508
+ * of its own triangles (default false). An aircraft's neighborhood over a forest held 100k
509
+ * triangles of shrubs and crowns, about 110 ms to rebuild every 24 m; its probes and camera
510
+ * rays need the trees' extent, not their leaves.
511
+ */
512
+ instanceBounds?: boolean;
499
513
  }
500
514
  /**
501
515
  * A small collision neighborhood in metric coordinates, independent of floating-origin shifts.
@@ -515,6 +529,7 @@ declare class WalkCollision {
515
529
  private readonly verticalRadius;
516
530
  private readonly rescanIntervalMs;
517
531
  private readonly now;
532
+ private readonly instanceBounds;
518
533
  private meshes;
519
534
  private initialized;
520
535
  /** Vertical center of the current neighborhood, or undefined when it spans the whole column. */
@@ -63,49 +63,119 @@ const LEAF_SIZE = 16;
63
63
  * Rendered roads, walls and portal covers can overlap. An octree copies each triangle into
64
64
  * every intersecting cell and repeatedly splits those copies, causing long rebuild stalls.
65
65
  * A balanced bounding-volume tree stores each triangle once, even for coincident surfaces.
66
+ *
67
+ * Triangle bounds and centers live in flat arrays and each split selects its median instead of
68
+ * sorting: an aircraft's neighborhood over dense ground cover held 170k triangles, and sorting
69
+ * them at every level of the tree took 700 ms of one frame.
66
70
  */
67
71
  var CollisionTree = class extends Octree {
68
72
  build() {
69
73
  this.calcBox();
70
74
  this.subTrees = [];
71
- if (this.triangles.length > 0) {
72
- const entries = this.triangles.map((triangle) => {
73
- const bounds = new THREE.Box3().setFromPoints([
74
- triangle.a,
75
- triangle.b,
76
- triangle.c
77
- ]);
78
- return {
79
- triangle,
80
- bounds,
81
- center: bounds.getCenter(new THREE.Vector3())
82
- };
75
+ const triangles = this.triangles;
76
+ if (triangles.length > 0) {
77
+ const bounds = new Float64Array(triangles.length * 6);
78
+ const centers = new Float64Array(triangles.length * 3);
79
+ triangles.forEach(({ a, b, c }, index) => {
80
+ const box = index * 6;
81
+ bounds[box] = Math.min(a.x, b.x, c.x);
82
+ bounds[box + 1] = Math.min(a.y, b.y, c.y);
83
+ bounds[box + 2] = Math.min(a.z, b.z, c.z);
84
+ bounds[box + 3] = Math.max(a.x, b.x, c.x);
85
+ bounds[box + 4] = Math.max(a.y, b.y, c.y);
86
+ bounds[box + 5] = Math.max(a.z, b.z, c.z);
87
+ for (let axis = 0; axis < 3; axis++) centers[index * 3 + axis] = (bounds[box + axis] + bounds[box + 3 + axis]) / 2;
83
88
  });
84
- this.subTrees.push(partition(entries));
89
+ const order = new Uint32Array(triangles.length);
90
+ for (let index = 0; index < order.length; index++) order[index] = index;
91
+ this.subTrees.push(partition({
92
+ triangles,
93
+ bounds,
94
+ centers,
95
+ order
96
+ }, 0, triangles.length));
85
97
  }
86
98
  this.triangles = [];
87
99
  return this;
88
100
  }
89
101
  };
90
- function partition(entries) {
91
- const bounds = new THREE.Box3();
92
- const centers = new THREE.Box3();
93
- for (const entry of entries) {
94
- bounds.union(entry.bounds);
95
- centers.expandByPoint(entry.center);
102
+ function partition(entries, start, end) {
103
+ const { bounds, centers, order } = entries;
104
+ const box = new THREE.Box3();
105
+ const low = [
106
+ Infinity,
107
+ Infinity,
108
+ Infinity
109
+ ];
110
+ const high = [
111
+ -Infinity,
112
+ -Infinity,
113
+ -Infinity
114
+ ];
115
+ for (let k = start; k < end; k++) {
116
+ const index = order[k];
117
+ for (let axis = 0; axis < 3; axis++) {
118
+ const center = centers[index * 3 + axis];
119
+ if (center < low[axis]) low[axis] = center;
120
+ if (center > high[axis]) high[axis] = center;
121
+ }
122
+ box.min.x = Math.min(box.min.x, bounds[index * 6]);
123
+ box.min.y = Math.min(box.min.y, bounds[index * 6 + 1]);
124
+ box.min.z = Math.min(box.min.z, bounds[index * 6 + 2]);
125
+ box.max.x = Math.max(box.max.x, bounds[index * 6 + 3]);
126
+ box.max.y = Math.max(box.max.y, bounds[index * 6 + 4]);
127
+ box.max.z = Math.max(box.max.z, bounds[index * 6 + 5]);
96
128
  }
97
- const node = new Octree(bounds);
98
- if (entries.length <= LEAF_SIZE) {
99
- node.triangles = entries.map((entry) => entry.triangle);
129
+ const node = new Octree(box);
130
+ if (end - start <= LEAF_SIZE) {
131
+ node.triangles = Array.from(order.subarray(start, end)).sort((p, q) => p - q).map((index) => entries.triangles[index]);
100
132
  return node;
101
133
  }
102
- const size = centers.getSize(new THREE.Vector3());
103
- const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";
104
- entries.sort((a, b) => a.center[axis] - b.center[axis]);
105
- const middle = Math.floor(entries.length / 2);
106
- node.subTrees.push(partition(entries.slice(0, middle)), partition(entries.slice(middle)));
134
+ const [sx, sy, sz] = high.map((value, axis) => value - low[axis]);
135
+ const axis = sx >= sy && sx >= sz ? 0 : sy >= sz ? 1 : 2;
136
+ const middle = start + Math.floor((end - start) / 2);
137
+ selectMedian(entries, axis, start, end - 1, middle);
138
+ node.subTrees.push(partition(entries, start, middle), partition(entries, middle, end));
107
139
  return node;
108
140
  }
141
+ /**
142
+ * Reorder `order[left..right]` so position `k` holds the entry a full sort by center along `axis`
143
+ * would put there, with smaller entries before it and larger after. Equal centers order by
144
+ * triangle index, so the two halves never depend on how earlier splits arranged the range.
145
+ */
146
+ function selectMedian({ centers, order }, axis, left, right, k) {
147
+ const before = (p, q) => {
148
+ const cp = centers[p * 3 + axis];
149
+ const cq = centers[q * 3 + axis];
150
+ return cp < cq || cp === cq && p < q;
151
+ };
152
+ const swap = (i, j) => {
153
+ const held = order[i];
154
+ order[i] = order[j];
155
+ order[j] = held;
156
+ };
157
+ while (right > left) {
158
+ const mid = left + (right - left >> 1);
159
+ if (before(order[mid], order[left])) swap(mid, left);
160
+ if (before(order[right], order[left])) swap(right, left);
161
+ if (before(order[right], order[mid])) swap(right, mid);
162
+ const pivot = order[mid];
163
+ let i = left;
164
+ let j = right;
165
+ while (i <= j) {
166
+ while (before(order[i], pivot)) i++;
167
+ while (before(pivot, order[j])) j--;
168
+ if (i <= j) {
169
+ swap(i, j);
170
+ i++;
171
+ j--;
172
+ }
173
+ }
174
+ if (k <= j) right = j;
175
+ else if (k >= i) left = i;
176
+ else return;
177
+ }
178
+ }
109
179
  //#endregion
110
180
  //#region src/navigation/fly.ts
111
181
  var FlyController = class {
@@ -415,6 +485,7 @@ const NAVIGATION_ACTIONS = {
415
485
  engine: "nav-engine",
416
486
  gear: "nav-gear",
417
487
  flaps: "nav-flaps",
488
+ vector: "nav-vector",
418
489
  recover: "nav-recover"
419
490
  };
420
491
  const A = NAVIGATION_ACTIONS;
@@ -567,6 +638,7 @@ function navigationInputProfiles() {
567
638
  KeyI: A.engine,
568
639
  KeyG: A.gear,
569
640
  KeyF: A.flaps,
641
+ KeyJ: A.vector,
570
642
  KeyR: A.recover
571
643
  },
572
644
  axes: STICKS,
@@ -640,6 +712,7 @@ var NavigationInputSource = class {
640
712
  engine: 0,
641
713
  gear: 0,
642
714
  flaps: 0,
715
+ vector: 0,
643
716
  recover: 0
644
717
  };
645
718
  lookSpeed;
@@ -661,6 +734,7 @@ var NavigationInputSource = class {
661
734
  "engine",
662
735
  "gear",
663
736
  "flaps",
737
+ "vector",
664
738
  "recover"
665
739
  ].map((name) => this.map.onPress(A[name], () => {
666
740
  this.pilotPresses[name]++;
@@ -678,6 +752,7 @@ var NavigationInputSource = class {
678
752
  this.pilotPresses.engine = 0;
679
753
  this.pilotPresses.gear = 0;
680
754
  this.pilotPresses.flaps = 0;
755
+ this.pilotPresses.vector = 0;
681
756
  this.pilotPresses.recover = 0;
682
757
  })
683
758
  ];
@@ -731,6 +806,7 @@ var NavigationInputSource = class {
731
806
  this.pilotPresses.engine = 0;
732
807
  this.pilotPresses.gear = 0;
733
808
  this.pilotPresses.flaps = 0;
809
+ this.pilotPresses.vector = 0;
734
810
  this.pilotPresses.recover = 0;
735
811
  return input;
736
812
  }
@@ -1271,6 +1347,7 @@ var WalkCollision = class {
1271
1347
  verticalRadius;
1272
1348
  rescanIntervalMs;
1273
1349
  now;
1350
+ instanceBounds;
1274
1351
  meshes = [];
1275
1352
  initialized = false;
1276
1353
  /** Vertical center of the current neighborhood, or undefined when it spans the whole column. */
@@ -1286,6 +1363,7 @@ var WalkCollision = class {
1286
1363
  this.verticalRadius = resolved.verticalRadius === void 0 ? void 0 : requireFinite(resolved.verticalRadius, "verticalRadius", false);
1287
1364
  this.rescanIntervalMs = requireFinite(resolved.rescanIntervalMs ?? 0, "rescanIntervalMs", true);
1288
1365
  this.now = resolved.now ?? (() => performance.now());
1366
+ this.instanceBounds = resolved.instanceBounds ?? false;
1289
1367
  }
1290
1368
  /**
1291
1369
  * Track the subject at (x, z). With a `verticalRadius`, `y` bounds the neighborhood vertically.
@@ -1387,7 +1465,8 @@ var WalkCollision = class {
1387
1465
  const start = geometry.drawRange.start;
1388
1466
  const end = Math.min(index?.count ?? position.count, start + geometry.drawRange.count);
1389
1467
  const doubleSided = mesh.userData.walkDoubleSided === true;
1390
- const spatial = triangleIndexFor(geometry);
1468
+ const boxes = this.instanceBounds && mesh instanceof THREE.InstancedMesh;
1469
+ const spatial = boxes ? void 0 : triangleIndexFor(geometry);
1391
1470
  const visit = (vertex) => {
1392
1471
  if (vertex < start || vertex + 2 >= end) return;
1393
1472
  a.fromBufferAttribute(position, index?.getX(vertex) ?? vertex).applyMatrix4(transform);
@@ -1405,6 +1484,10 @@ var WalkCollision = class {
1405
1484
  } else transform.copy(local);
1406
1485
  bounds.copy(geometry.boundingBox).applyMatrix4(transform);
1407
1486
  if (!inside()) continue;
1487
+ if (boxes) {
1488
+ addBox(this.octree, geometry.boundingBox, transform);
1489
+ continue;
1490
+ }
1408
1491
  if (spatial === void 0) {
1409
1492
  for (let vertex = start; vertex + 2 < end; vertex += 3) visit(vertex);
1410
1493
  continue;
@@ -1418,6 +1501,80 @@ var WalkCollision = class {
1418
1501
  this.octree.build();
1419
1502
  }
1420
1503
  };
1504
+ const BOX_FACES = [
1505
+ [
1506
+ 0,
1507
+ 2,
1508
+ 6,
1509
+ 4
1510
+ ],
1511
+ [
1512
+ 1,
1513
+ 5,
1514
+ 7,
1515
+ 3
1516
+ ],
1517
+ [
1518
+ 0,
1519
+ 4,
1520
+ 5,
1521
+ 1
1522
+ ],
1523
+ [
1524
+ 2,
1525
+ 3,
1526
+ 7,
1527
+ 6
1528
+ ],
1529
+ [
1530
+ 0,
1531
+ 1,
1532
+ 3,
1533
+ 2
1534
+ ],
1535
+ [
1536
+ 4,
1537
+ 6,
1538
+ 7,
1539
+ 5
1540
+ ]
1541
+ ];
1542
+ const corners = Array.from({ length: 8 }, () => new THREE.Vector3());
1543
+ const boxCenter = new THREE.Vector3();
1544
+ const faceCenter = new THREE.Vector3();
1545
+ const edge = new THREE.Vector3();
1546
+ const across = new THREE.Vector3();
1547
+ /**
1548
+ * Add `box`, placed by `transform`, as twelve outward-facing triangles: rays test front faces only.
1549
+ * A box collapsed to a point (a hidden instance) adds nothing.
1550
+ */
1551
+ function addBox(tree, box, transform) {
1552
+ corners.forEach((corner, index) => {
1553
+ corner.set(index & 1 ? box.max.x : box.min.x, index & 2 ? box.max.y : box.min.y, index & 4 ? box.max.z : box.min.z).applyMatrix4(transform);
1554
+ });
1555
+ const [first] = corners;
1556
+ if (corners.every((corner) => corner.equals(first))) return;
1557
+ boxCenter.set(0, 0, 0);
1558
+ for (const corner of corners) boxCenter.add(corner);
1559
+ boxCenter.multiplyScalar(1 / 8);
1560
+ for (const face of BOX_FACES) {
1561
+ const [a, b, c, d] = face.map((index) => corners[index]);
1562
+ faceCenter.copy(a).add(b).add(c).add(d).multiplyScalar(.25).sub(boxCenter);
1563
+ const [p, q, r, t] = edge.subVectors(b, a).cross(across.subVectors(c, a)).dot(faceCenter) >= 0 ? [
1564
+ a,
1565
+ b,
1566
+ c,
1567
+ d
1568
+ ] : [
1569
+ a,
1570
+ d,
1571
+ c,
1572
+ b
1573
+ ];
1574
+ tree.addTriangle(new THREE.Triangle(p.clone(), q.clone(), r.clone()));
1575
+ tree.addTriangle(new THREE.Triangle(p.clone(), r.clone(), t.clone()));
1576
+ }
1577
+ }
1421
1578
  //#endregion
1422
1579
  //#region src/navigation/walk-controller.ts
1423
1580
  const WALK_EYE_HEIGHT = 1.7;
@@ -50,8 +50,14 @@ declare class FrameAdmissionQueue implements SceneAdmission {
50
50
  * the task and everything it captured. Only a queued job may stay reachable from its promise.
51
51
  */
52
52
  private forget;
53
- /** Move a still-queued background job to the normal lane, behind the jobs already there. */
54
- promote(promise: Promise<unknown>): void;
53
+ /**
54
+ * Move a still-queued background job to the normal lane, behind the jobs already there, or with
55
+ * `front` ahead of them: for work a frame is waiting on, such as a material an object holds off
56
+ * switching to until it is prepared.
57
+ */
58
+ promote(promise: Promise<unknown>, options?: {
59
+ front?: boolean;
60
+ }): void;
55
61
  get pending(): number;
56
62
  private request;
57
63
  /** One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests. */
@@ -285,6 +291,19 @@ interface ShadowFocus {
285
291
  radius: number;
286
292
  }
287
293
  //#endregion
294
+ //#region src/three/webgpu-ambient-occlusion.d.ts
295
+ interface AmbientOcclusionOptions {
296
+ /** World-space sampling radius, meters: about a wall-to-ground crease. */
297
+ radius?: number;
298
+ /** Share of the occlusion applied, 0–1. Sunlit faces keep most of their direct light. */
299
+ strength?: number;
300
+ /**
301
+ * View distance, meters, past which no occlusion is computed; it fades out over the last
302
+ * third. Farther creases are under a pixel, and skipping them is most of an aerial view.
303
+ */
304
+ reach?: number;
305
+ }
306
+ //#endregion
288
307
  //#region src/three/webgpu-scene-optimizer.d.ts
289
308
  /**
290
309
  * Uses Three render bundles and a pinned, version-aware instance upload adapter.
@@ -306,6 +325,8 @@ declare class WebGpuSceneOptimizer {
306
325
  private readonly matrixSamples;
307
326
  private readonly restoreRefresh;
308
327
  private materialSamples;
328
+ /** The render each material last refreshed a replayed object in; see the constructor. */
329
+ private readonly refreshed;
309
330
  private readonly videoMaterials;
310
331
  private readonly materialStates;
311
332
  constructor(renderer: WebGPURenderer);
@@ -427,6 +448,12 @@ declare class Renderer {
427
448
  private warmupMaterial;
428
449
  private readonly warmedPrograms;
429
450
  private readonly warmedMeshes;
451
+ /**
452
+ * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
453
+ * `prepareVariants`.
454
+ */
455
+ private readonly warmedVariants;
456
+ private readonly variantInterests;
430
457
  private readonly warmups;
431
458
  /** Deferred meshes whose preparation has not settled, with the interest that can promote it. */
432
459
  private readonly deferredMeshes;
@@ -461,6 +488,10 @@ declare class Renderer {
461
488
  private readonly optimizer;
462
489
  private activeSky;
463
490
  private readonly reflections;
491
+ private occlusionOptions;
492
+ private occlusion;
493
+ private occlusionLoad;
494
+ private occlusionSuspended;
464
495
  /** Sun lights whose WebGPU shadow map exists and must not be torn down; see setShadowQuality. */
465
496
  private readonly webgpuShadowLights;
466
497
  private readonly reflectionClearColor;
@@ -548,6 +579,18 @@ declare class Renderer {
548
579
  prepareObject(root: THREE.Object3D, signal?: AbortSignal, parent?: THREE.Object3D): Promise<void>;
549
580
  private prepareMesh;
550
581
  private flushWebGlBatches;
582
+ /**
583
+ * A mesh that swaps its own material, as an instanced detail switch swaps in an opaque twin for
584
+ * its coarser levels, lists every material in `userData.materialVariants`. Each needs its own
585
+ * shader build, which the first frame to draw it would otherwise make mid-frame: in flight a whole
586
+ * view of trees changed level at once and built their twins in one frame, for most of a second.
587
+ * `userData.materialReady(material)` tells the mesh's owner whether one is ready. Until it is, the
588
+ * owner keeps what it shows; asking queues its build ahead of other work. Most batches never
589
+ * change level, so a variant is built only once its mesh asks for it.
590
+ */
591
+ private prepareVariants;
592
+ /** Whether `mesh` can draw `material` without building it mid-frame; builds it first if not. */
593
+ private variantReady;
551
594
  /** Queue one cancellable warm-up job in the lane's admission priority. */
552
595
  private warmup;
553
596
  /**
@@ -564,6 +607,7 @@ declare class Renderer {
564
607
  /** Nobody waits any longer: drop the job from every cache first, then from the queue. */
565
608
  private cancelWarmup;
566
609
  private rememberPreparation;
610
+ /** Build `mesh` for the frame's draw target, drawn with `material` when given. */
567
611
  private compileMesh;
568
612
  private prepareWebGlGeometries;
569
613
  render(): void;
@@ -579,6 +623,22 @@ declare class Renderer {
579
623
  */
580
624
  private hideReflectedAmbient;
581
625
  private renderScene;
626
+ private optimized;
627
+ /**
628
+ * Screen-space ambient occlusion on the WebGPU backend (a no-op on WebGL): creases, corners and
629
+ * the ground around buildings and trees darken a little, as indirect light cannot reach them.
630
+ * The frame then renders through a node pipeline; frames draw directly while it compiles.
631
+ */
632
+ setAmbientOcclusion(enabled: boolean, options?: AmbientOcclusionOptions): void;
633
+ /**
634
+ * Skip the occlusion computation while keeping ambient occlusion set up: the frame still draws
635
+ * into its target, and the image is copied out unshaded. Each object's shaders are built for
636
+ * one draw target, so turning occlusion off and on again (`setAmbientOcclusion`) built every
637
+ * object in view again, mid-frame, when the target changed; suspending changes nothing there.
638
+ */
639
+ suspendAmbientOcclusion(suspended: boolean): void;
640
+ /** The occlusion pass for the current camera, building one in the background when needed. */
641
+ private currentOcclusion;
582
642
  /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
583
643
  createRenderGroup(): THREE.Group;
584
644
  /** Last completed visible frame, excluding offscreen resource preparation. */
@@ -0,0 +1,24 @@
1
+ import * as THREE from "three";
2
+ import { FontLibrary, FontLibrary as FontLibrary$1, TextLayoutOptions, TextLayoutOptions as TextLayoutOptions$1, TextMeshData, VectorFont, VectorFont as VectorFont$1, VectorGlyph, buildTextMesh, loadFontLibrary, vectorFontSchema } from "@bendyline/molen-materials/text";
3
+ import { FontData } from "three/addons/loaders/FontLoader.js";
4
+
5
+ //#region src/text.d.ts
6
+ interface CompileVectorFontOptions {
7
+ id: string;
8
+ /** Explicit subset, including ? and space. Default: every character in the typeface. */
9
+ characters?: string;
10
+ weight?: number;
11
+ style?: "normal" | "italic";
12
+ /** Segments per outline curve, 2–32; default 6 for medium-fi signage. */
13
+ curveSegments?: number;
14
+ /** Optional pair adjustments in em units from the source font's kerning tables. */
15
+ kerning?: Record<string, number>;
16
+ }
17
+ /** Compile typeface JSON (including TTFLoader output) once, then store the result in a pack.
18
+ * Node and browser compatible; no canvas or OS font dependency. Does not fetch a font.
19
+ */
20
+ declare function compileVectorFont(data: FontData, options: CompileVectorFontOptions): VectorFont$1;
21
+ /** Caller owns/disposes the geometry and chooses its material, color, transform and batching. */
22
+ declare function createTextGeometry(text: string, fonts: FontLibrary$1, options?: TextLayoutOptions$1): THREE.BufferGeometry;
23
+ //#endregion
24
+ export { CompileVectorFontOptions, type FontLibrary, type TextLayoutOptions, type TextMeshData, type VectorFont, type VectorGlyph, buildTextMesh, compileVectorFont, createTextGeometry, loadFontLibrary, vectorFontSchema };