@threenative/core 0.3.4 → 0.3.5

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.
Files changed (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,175 @@
1
+ import { CatmullRomCurve3, Vector3 } from "three";
2
+
3
+ export interface IPathFollow3DOptions {
4
+ readonly loop?: boolean;
5
+ readonly points: readonly Vector3[];
6
+ readonly speed?: number;
7
+ }
8
+
9
+ export interface IPathFollow3DSample {
10
+ point: Vector3;
11
+ progress: number;
12
+ tangent: Vector3;
13
+ }
14
+
15
+ export interface IPathFollow3DProjection {
16
+ distanceFromStart: number;
17
+ lateralDistance: number;
18
+ tangent: Vector3;
19
+ point: Vector3;
20
+ segment: number;
21
+ }
22
+
23
+ const CURVE_DIVISIONS = 128;
24
+
25
+ /** A portable, distance-based follower for an authored Three.js route. */
26
+ export class PathFollow3D {
27
+ readonly curve: CatmullRomCurve3;
28
+ readonly loop: boolean;
29
+ readonly totalLength: number;
30
+ readonly #samples: readonly Vector3[];
31
+ readonly #samplePoint = new Vector3();
32
+ readonly #sampleTangent = new Vector3();
33
+ readonly #tangentStart = new Vector3();
34
+ readonly #tangentEnd = new Vector3();
35
+ readonly #projectPoint = new Vector3();
36
+ readonly #projectTangent = new Vector3();
37
+ #progress = 0;
38
+ #speed: number;
39
+
40
+ constructor(options: IPathFollow3DOptions) {
41
+ if (options.points.length < 3) throw new Error("PathFollow3D requires at least three points.");
42
+ if (options.speed !== undefined && (!Number.isFinite(options.speed) || options.speed < 0))
43
+ throw new Error("PathFollow3D speed must be a finite non-negative number.");
44
+ const points = options.points.map((point) => {
45
+ if (![point.x, point.y, point.z].every(Number.isFinite))
46
+ throw new Error("PathFollow3D points must be finite.");
47
+ return point.clone();
48
+ });
49
+ this.loop = options.loop ?? false;
50
+ this.#speed = options.speed ?? 0;
51
+ this.curve = new CatmullRomCurve3(points, this.loop, "centripetal", 0.5);
52
+ this.totalLength = this.curve.getLengths(CURVE_DIVISIONS).at(-1) ?? 0;
53
+ if (!(this.totalLength > 0)) throw new Error("PathFollow3D requires a positive-length path.");
54
+ const spaced = this.curve.getSpacedPoints(CURVE_DIVISIONS);
55
+ this.#samples = this.loop ? spaced.slice(0, CURVE_DIVISIONS) : spaced;
56
+ }
57
+
58
+ get completed(): boolean {
59
+ return !this.loop && this.#progress >= this.totalLength;
60
+ }
61
+
62
+ get progress(): number {
63
+ return this.#progress;
64
+ }
65
+
66
+ get speed(): number {
67
+ return this.#speed;
68
+ }
69
+
70
+ set speed(value: number) {
71
+ if (!Number.isFinite(value) || value < 0)
72
+ throw new Error("PathFollow3D speed must be a finite non-negative number.");
73
+ this.#speed = value;
74
+ }
75
+
76
+ advance(dt: number, target?: IPathFollow3DSample): IPathFollow3DSample {
77
+ if (!Number.isFinite(dt) || dt < 0)
78
+ throw new Error("PathFollow3D.advance requires a finite non-negative delta.");
79
+ this.progressTo(this.#progress + this.#speed * dt);
80
+ return this.sample(this.#progress, target);
81
+ }
82
+
83
+ progressTo(distance: number): this {
84
+ if (!Number.isFinite(distance) || distance < 0)
85
+ throw new Error("PathFollow3D progress must be a finite non-negative number.");
86
+ this.#progress = this.loop ? distance % this.totalLength : Math.min(distance, this.totalLength);
87
+ return this;
88
+ }
89
+
90
+ sample(distance = this.#progress, target?: IPathFollow3DSample): IPathFollow3DSample {
91
+ if (!Number.isFinite(distance) || distance < 0)
92
+ throw new Error("PathFollow3D sample distance must be a finite non-negative number.");
93
+ const progress = this.loop ? distance % this.totalLength : Math.min(distance, this.totalLength);
94
+ const u = progress / this.totalLength;
95
+ if (target !== undefined) {
96
+ this.curve.getPointAt(u, target.point);
97
+ this.#writeTangentAt(u, target.tangent);
98
+ target.progress = progress;
99
+ return target;
100
+ }
101
+ this.curve.getPointAt(u, this.#samplePoint);
102
+ this.curve.getTangentAt(u, this.#sampleTangent).normalize();
103
+ return {
104
+ point: this.#samplePoint.clone(),
105
+ progress,
106
+ tangent: this.#sampleTangent.clone(),
107
+ };
108
+ }
109
+
110
+ pointAt(distance: number, target?: IPathFollow3DSample): IPathFollow3DSample {
111
+ return this.sample(distance, target);
112
+ }
113
+
114
+ project(position: Vector3, target?: IPathFollow3DProjection): IPathFollow3DProjection {
115
+ if (
116
+ !Number.isFinite(position.x) ||
117
+ !Number.isFinite(position.y) ||
118
+ !Number.isFinite(position.z)
119
+ )
120
+ throw new Error("PathFollow3D projection position must be finite.");
121
+ let nearest = Number.POSITIVE_INFINITY;
122
+ let nearestIndex = 0;
123
+ for (let index = 0; index < this.#samples.length; index += 1) {
124
+ const sample = this.#samples[index];
125
+ if (sample === undefined) throw new Error("PathFollow3D projection sample is missing.");
126
+ const distance = sample.distanceToSquared(position);
127
+ if (distance < nearest) {
128
+ nearest = distance;
129
+ nearestIndex = index;
130
+ }
131
+ }
132
+ const last = this.#samples.length - 1;
133
+ const segmentCount = this.loop ? this.#samples.length : last;
134
+ const segment = Math.min(nearestIndex, Math.max(0, segmentCount - 1));
135
+ const point = this.#samples[nearestIndex];
136
+ if (point === undefined) throw new Error("PathFollow3D projection sample is missing.");
137
+ const tangentStart = this.#samples[segment];
138
+ if (tangentStart === undefined) throw new Error("PathFollow3D projection tangent is missing.");
139
+ const nextIndex = this.loop
140
+ ? (segment + 1) % this.#samples.length
141
+ : Math.min(segment + 1, last);
142
+ const next = this.#samples[nextIndex];
143
+ if (next === undefined) throw new Error("PathFollow3D projection tangent is missing.");
144
+ const distanceFromSample = (nearestIndex / segmentCount) * this.totalLength;
145
+ const pointTarget = target?.point ?? this.#projectPoint;
146
+ const tangentTarget = target?.tangent ?? this.#projectTangent;
147
+ pointTarget.copy(point);
148
+ tangentTarget.subVectors(next, tangentStart).normalize();
149
+ if (target !== undefined) {
150
+ target.distanceFromStart = distanceFromSample;
151
+ target.lateralDistance = point.distanceTo(position);
152
+ target.segment = segment;
153
+ return target;
154
+ }
155
+ return {
156
+ distanceFromStart: distanceFromSample,
157
+ lateralDistance: point.distanceTo(position),
158
+ point: pointTarget.clone(),
159
+ segment,
160
+ tangent: tangentTarget.clone(),
161
+ };
162
+ }
163
+
164
+ #writeTangentAt(u: number, target: Vector3): Vector3 {
165
+ const t = this.curve.getUtoTmapping(u, 0);
166
+ const delta = 0.0001;
167
+ let t1 = t - delta;
168
+ let t2 = t + delta;
169
+ if (t1 < 0) t1 = 0;
170
+ if (t2 > 1) t2 = 1;
171
+ this.curve.getPoint(t1, this.#tangentStart);
172
+ this.curve.getPoint(t2, this.#tangentEnd);
173
+ return target.copy(this.#tangentEnd).sub(this.#tangentStart).normalize();
174
+ }
175
+ }
package/src/picking.ts ADDED
@@ -0,0 +1,250 @@
1
+ import {
2
+ type BufferGeometry,
3
+ type Camera,
4
+ type Intersection,
5
+ Mesh,
6
+ type Object3D,
7
+ Raycaster,
8
+ Vector2,
9
+ type Vector3,
10
+ } from "three";
11
+ import { MeshBVH } from "three-mesh-bvh";
12
+ import { baseGeometryOf, isLodJoinProxy } from "./model-lod.js";
13
+ import type { Viewport } from "./viewport.js";
14
+
15
+ export interface IRaycastOptions {
16
+ /** Screen point in canvas pixels. Mutually exclusive with `origin` and `direction`. */
17
+ readonly screen?: Vector2;
18
+ /** World-space ray origin. Requires `direction`. */
19
+ readonly origin?: Vector3;
20
+ /** World-space ray direction. The caller must provide a normalised vector. */
21
+ readonly direction?: Vector3;
22
+ /** Maximum distance. Defaults to unbounded. */
23
+ readonly far?: number;
24
+ /** What to test. Defaults to the whole scene. */
25
+ readonly targets?: Object3D | readonly Object3D[];
26
+ /** Subtrees never hit, whatever `targets` says. */
27
+ readonly exclude?: Object3D | readonly Object3D[];
28
+ }
29
+
30
+ export interface IScenePickerOptions {
31
+ readonly camera: Camera;
32
+ readonly pointer: () => Vector2;
33
+ readonly scene: Object3D;
34
+ readonly viewport: Viewport;
35
+ }
36
+
37
+ interface ICachedTree {
38
+ readonly tree: MeshBVH;
39
+ readonly version: number;
40
+ }
41
+
42
+ type AcceleratedRaycaster = Raycaster & { firstHitOnly?: boolean };
43
+
44
+ /**
45
+ * Ray queries against scene geometry, accelerated by a bounding volume hierarchy that is
46
+ * built on first use and rebuilt when the geometry's positions change.
47
+ *
48
+ * The acceleration is an implementation detail: nothing about it reaches the caller, no
49
+ * `three` prototype is patched, and a game that never calls `raycast` never builds a tree.
50
+ * Skinned, instanced, batched and morphed meshes fall back to the stock `three` path,
51
+ * because a hierarchy over their rest positions would report hits in the wrong place.
52
+ */
53
+ export class ScenePicker {
54
+ #camera: Camera;
55
+ #pointer: () => Vector2;
56
+ #scene: Object3D;
57
+ #viewport: Viewport;
58
+ #raycaster: AcceleratedRaycaster = new Raycaster();
59
+ #ndc = new Vector2();
60
+ #hits: Intersection[] = [];
61
+ #objectHits: Intersection[] = [];
62
+ #roots: Object3D[] = [];
63
+ #excluded = new Set<Object3D>();
64
+ #compareHits = (first: Intersection, second: Intersection): number =>
65
+ first.distance - second.distance;
66
+ #trees = new WeakMap<BufferGeometry, ICachedTree>();
67
+
68
+ constructor(options: IScenePickerOptions) {
69
+ this.#camera = options.camera;
70
+ this.#pointer = options.pointer;
71
+ this.#scene = options.scene;
72
+ this.#viewport = options.viewport;
73
+ this.#raycaster.firstHitOnly = false;
74
+ }
75
+
76
+ /**
77
+ * The closest hit, or `undefined` when the ray hits nothing.
78
+ *
79
+ * Collects at most one hit per target: the traversal runs with `firstHitOnly` so BVH-backed
80
+ * meshes stop at their own closest triangle (PRD-186 phase 1), and anything on the stock
81
+ * fallback path — instanced, skinned, morphed — is reduced to its own nearest before it joins
82
+ * the candidates. The winner is a running minimum, never a full sort: a game asking "what did
83
+ * this round hit" should not pay for every wall behind the answer.
84
+ */
85
+ raycast(options?: IRaycastOptions): Intersection | undefined {
86
+ this.#query(options, true);
87
+ let nearest: Intersection | undefined;
88
+ for (const hit of this.#hits) {
89
+ if (nearest === undefined || hit.distance < nearest.distance) nearest = hit;
90
+ }
91
+ return nearest;
92
+ }
93
+
94
+ /** Every hit, sorted from the nearest to the farthest. */
95
+ raycastAll(options?: IRaycastOptions, target?: Intersection[]): readonly Intersection[] {
96
+ if (target !== undefined) target.length = 0;
97
+ this.#query(options, false);
98
+ if (target === undefined) return this.#hits.slice();
99
+ for (const hit of this.#hits) target.push(hit);
100
+ return target;
101
+ }
102
+
103
+ #query(options: IRaycastOptions | undefined, single: boolean): void {
104
+ this.#setRay(options);
105
+ this.#raycaster.far = options?.far ?? Number.POSITIVE_INFINITY;
106
+ const targets = options?.targets ?? this.#scene;
107
+ this.#roots.length = 0;
108
+ if (Array.isArray(targets)) {
109
+ for (const target of targets as readonly Object3D[]) this.#roots.push(target);
110
+ } else {
111
+ this.#roots.push(targets as Object3D);
112
+ }
113
+ this.#excluded.clear();
114
+ const exclude = options?.exclude;
115
+ if (exclude !== undefined) {
116
+ if (Array.isArray(exclude)) {
117
+ for (const object of exclude as readonly Object3D[]) this.#excluded.add(object);
118
+ } else {
119
+ this.#excluded.add(exclude as Object3D);
120
+ }
121
+ }
122
+ this.#hits.length = 0;
123
+ this.#raycaster.firstHitOnly = single;
124
+ try {
125
+ for (const root of this.#roots) {
126
+ root.updateMatrixWorld();
127
+ this.#collect(root, this.#excluded, single);
128
+ }
129
+ if (!single) this.#hits.sort(this.#compareHits);
130
+ } finally {
131
+ this.#raycaster.firstHitOnly = false;
132
+ }
133
+ }
134
+
135
+ /** Drops every cached hierarchy. The next `raycast` rebuilds what it needs. */
136
+ dispose(): void {
137
+ this.#trees = new WeakMap<BufferGeometry, ICachedTree>();
138
+ this.#hits.length = 0;
139
+ this.#roots.length = 0;
140
+ this.#excluded.clear();
141
+ }
142
+
143
+ #setRay(options: IRaycastOptions | undefined): void {
144
+ const hasScreen = options?.screen !== undefined;
145
+ const hasOrigin = options?.origin !== undefined;
146
+ const hasDirection = options?.direction !== undefined;
147
+ if (hasScreen && (hasOrigin || hasDirection))
148
+ throw new Error("ICtx.raycast screen cannot be combined with origin or direction.");
149
+ if (hasDirection && !hasOrigin) throw new Error("ICtx.raycast direction requires origin.");
150
+ if (hasOrigin && !hasDirection) throw new Error("ICtx.raycast origin requires direction.");
151
+ if (hasOrigin) {
152
+ this.#raycaster.camera = this.#camera;
153
+ this.#raycaster.set(options?.origin as Vector3, options?.direction as Vector3);
154
+ return;
155
+ }
156
+
157
+ const screen = options?.screen ?? this.#pointer();
158
+ if (!Number.isFinite(screen.x) || !Number.isFinite(screen.y))
159
+ throw new Error("ICtx.raycast screen point must be finite.");
160
+ const { height, width } = this.#viewport.size;
161
+ if (width <= 0 || height <= 0) throw new Error("ICtx.raycast needs a sized viewport.");
162
+ this.#ndc.set((screen.x / width) * 2 - 1, -(screen.y / height) * 2 + 1);
163
+ this.#raycaster.setFromCamera(this.#ndc, this.#camera);
164
+ }
165
+
166
+ #collect(object: Object3D, excluded: ReadonlySet<Object3D>, single: boolean): void {
167
+ if (excluded.size !== 0 && this.#isExcluded(object, excluded)) return;
168
+ if (object.layers.test(this.#raycaster.layers)) {
169
+ if (single) {
170
+ // The stock fallback ignores `firstHitOnly`, so one object can still push several
171
+ // intersections; only that object's own nearest survives. The global answer can only
172
+ // ever be some object's nearest hit, so nothing behind it is ever needed.
173
+ this.#objectHits.length = 0;
174
+ this.#hitTest(object, this.#objectHits);
175
+ let best = this.#objectHits[0];
176
+ for (let index = 1; index < this.#objectHits.length; index += 1) {
177
+ const candidate = this.#objectHits[index];
178
+ if (candidate !== undefined && (best === undefined || candidate.distance < best.distance))
179
+ best = candidate;
180
+ }
181
+ if (best !== undefined) this.#hits.push(best);
182
+ } else {
183
+ this.#hitTest(object, this.#hits);
184
+ }
185
+ }
186
+ for (const child of object.children) this.#collect(child, excluded, single);
187
+ }
188
+
189
+ #hitTest(object: Object3D, into: Intersection[]): void {
190
+ // A joined rung inserts a proxy object carrying the collapsed geometry but none of the authored
191
+ // node identity. Authored primitives are hidden from the render, never from a ray test, so the
192
+ // proxy must be skipped or a pick at distance would answer with an object the game never added.
193
+ if (isLodJoinProxy(object)) return;
194
+ const tree = this.#treeFor(object);
195
+ if (tree === undefined) {
196
+ object.raycast(this.#raycaster, into);
197
+ return;
198
+ }
199
+ if (!(object instanceof Mesh)) {
200
+ tree.raycastObject3D(object, this.#raycaster, into);
201
+ return;
202
+ }
203
+ // A mesh the loader gave an automatic LOD chain swaps its `geometry` with the camera. Picking
204
+ // must not: the tree is built from LOD0, and the object is put back on LOD0 for the test so the
205
+ // hit is the authored surface whatever detail is currently drawn.
206
+ const base = baseGeometryOf(object);
207
+ const restore = base === object.geometry ? undefined : object.geometry;
208
+ if (restore !== undefined) object.geometry = base;
209
+ try {
210
+ tree.raycastObject3D(object, this.#raycaster, into);
211
+ } finally {
212
+ if (restore !== undefined) object.geometry = restore;
213
+ }
214
+ }
215
+
216
+ #isExcluded(object: Object3D, excluded: ReadonlySet<Object3D>): boolean {
217
+ let current: Object3D | null = object;
218
+ while (current !== null) {
219
+ if (excluded.has(current)) return true;
220
+ current = current.parent;
221
+ }
222
+ return false;
223
+ }
224
+
225
+ #treeFor(object: Object3D): MeshBVH | undefined {
226
+ if (!(object instanceof Mesh)) return undefined;
227
+ const deformed = object as Mesh & {
228
+ isBatchedMesh?: boolean;
229
+ isInstancedMesh?: boolean;
230
+ isSkinnedMesh?: boolean;
231
+ };
232
+ if (
233
+ deformed.isSkinnedMesh === true ||
234
+ deformed.isInstancedMesh === true ||
235
+ deformed.isBatchedMesh === true ||
236
+ (object.morphTargetInfluences?.length ?? 0) > 0
237
+ )
238
+ return undefined;
239
+ // The tree is built from the authored LOD0, never from whichever level the camera selected;
240
+ // the position attribute is shared across levels, so its version still tracks source changes.
241
+ const geometry = baseGeometryOf(object);
242
+ const position = object.geometry.attributes.position;
243
+ if (position === undefined || position.count === 0) return undefined;
244
+ const cached = this.#trees.get(geometry);
245
+ if (cached !== undefined && cached.version === position.version) return cached.tree;
246
+ const tree = new MeshBVH(geometry);
247
+ this.#trees.set(geometry, { tree, version: position.version });
248
+ return tree;
249
+ }
250
+ }