@expofp/renderer 3.49.2 → 3.51.0

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 (66) hide show
  1. package/dist/Renderer.d.ts +2 -2
  2. package/dist/core/SquareDataTexture.d.ts +5 -0
  3. package/dist/core/SquareDataTexture.js +6 -0
  4. package/dist/core/batch/BatchedMesh.d.ts +12 -0
  5. package/dist/core/batch/BatchedMesh.js +29 -0
  6. package/dist/core/instanced/InstancedMesh.d.ts +5 -0
  7. package/dist/core/instanced/InstancedMesh.js +12 -0
  8. package/dist/core/sprites/BatchedSprites.js +2 -2
  9. package/dist/core/sprites/RaycastingSprites.d.ts +9 -1
  10. package/dist/core/sprites/RaycastingSprites.js +23 -3
  11. package/dist/core/sprites/sprite-material.js +5 -6
  12. package/dist/core/text/MemberTexture.js +2 -4
  13. package/dist/events/LayoutDriver.js +17 -1
  14. package/dist/events/layout-targets.js +30 -5
  15. package/dist/events/placement/box.d.ts +14 -0
  16. package/dist/events/placement/box.js +19 -2
  17. package/dist/events/placement/index.d.ts +1 -0
  18. package/dist/events/placement/index.js +1 -0
  19. package/dist/events/placement/pass.js +9 -8
  20. package/dist/events/pointer.d.ts +27 -6
  21. package/dist/events/pointer.js +50 -9
  22. package/dist/index.d.ts +1 -1
  23. package/dist/index.js +2 -2
  24. package/dist/objects/containers/SlotContainer.d.ts +5 -0
  25. package/dist/objects/containers/SlotContainer.js +7 -0
  26. package/dist/objects/images/Images.js +1 -1
  27. package/dist/objects/lighting/Lighting.d.ts +56 -38
  28. package/dist/objects/lighting/Lighting.js +136 -344
  29. package/dist/objects/lighting/lighting-gui.js +32 -18
  30. package/dist/objects/lighting/studio-environment.d.ts +15 -43
  31. package/dist/objects/lighting/studio-environment.js +18 -126
  32. package/dist/objects/lighting/sun-shadow-map.d.ts +39 -15
  33. package/dist/objects/lighting/sun-shadow-map.js +163 -26
  34. package/dist/objects/materials/ColorMaterial.d.ts +11 -8
  35. package/dist/objects/materials/ColorMaterial.js +33 -11
  36. package/dist/objects/materials/ModelMaterial.js +3 -2
  37. package/dist/objects/materials/OutlineMaterial.d.ts +21 -0
  38. package/dist/objects/materials/OutlineMaterial.js +77 -0
  39. package/dist/objects/materials/TextureMaterial.d.ts +10 -0
  40. package/dist/objects/materials/TextureMaterial.js +13 -2
  41. package/dist/objects/materials/effects/ao/index.d.ts +2 -5
  42. package/dist/objects/materials/effects/ao/index.js +4 -7
  43. package/dist/objects/materials/effects/contact-shadow.d.ts +21 -10
  44. package/dist/objects/materials/effects/contact-shadow.js +60 -16
  45. package/dist/objects/materials/effects/effects-context.d.ts +2 -1
  46. package/dist/objects/materials/effects/effects-context.js +2 -1
  47. package/dist/objects/materials/effects/side-shade.d.ts +40 -0
  48. package/dist/objects/materials/effects/side-shade.js +52 -0
  49. package/dist/objects/materials/effects/sun-shadow.d.ts +5 -21
  50. package/dist/objects/materials/effects/sun-shadow.js +56 -89
  51. package/dist/objects/models/Models.d.ts +3 -2
  52. package/dist/objects/models/Models.js +46 -8
  53. package/dist/objects/models/gltf-cache.js +1 -1
  54. package/dist/objects/models/model-asset.d.ts +84 -20
  55. package/dist/objects/models/model-asset.js +171 -40
  56. package/dist/objects/models/model-container.d.ts +46 -10
  57. package/dist/objects/models/model-container.js +92 -19
  58. package/dist/objects/shapes/Shapes.js +11 -6
  59. package/dist/objects/shapes/shape-container.d.ts +3 -2
  60. package/dist/objects/shapes/shape-container.js +6 -4
  61. package/dist/objects/shapes/shape-geometry.d.ts +16 -4
  62. package/dist/objects/shapes/shape-geometry.js +17 -13
  63. package/dist/types/defs.d.ts +30 -1
  64. package/dist/utils/math.d.ts +14 -0
  65. package/dist/utils/math.js +20 -0
  66. package/package.json +2 -2
@@ -36,7 +36,7 @@ export function loadModel(url, renderer) {
36
36
  */
37
37
  async function parse(url, renderer) {
38
38
  const gltf = await loaderFor(renderer).loadAsync(url);
39
- return bakeGltf(gltf.scene, url);
39
+ return bakeGltf(gltf.scene, url, gltf.animations);
40
40
  }
41
41
  /**
42
42
  * The loader for one renderer. Meshopt is wired in because its decoder ships inside three's addons
@@ -1,42 +1,100 @@
1
- import { Box3, type BufferGeometry, type Group, type Material } from 'three';
2
- /** One drawable piece of a loaded model: everything in it that shares a source material. */
1
+ import { type AnimationClip, AnimationMixer, Box3, type BufferGeometry, type Group, type Material, Matrix4, type Object3D } from 'three';
2
+ /**
3
+ * One drawable piece of a loaded model, drawn once per {@link copies | copy} for every def placing
4
+ * the model. It is one of two things:
5
+ *
6
+ * - **Merged**: every mesh the GLB uses once with this material, flattened into one geometry that
7
+ * already sits where the model puts it. One copy, the identity.
8
+ * - **Reused**: one mesh the GLB places several times (several nodes sharing it, or a GPU-instanced
9
+ * node). Its geometry is kept once, in the mesh's own space, with a copy per placement.
10
+ */
3
11
  export interface ModelPart {
4
12
  /**
5
13
  * Identifies the part within its asset, and so keys the mesh drawing it. The material alone will
6
- * not do: parts are bucketed by material **and** merge signature, so one material can yield more
7
- * than one part and two parts can share a `material.uuid`.
14
+ * not do: merged parts are bucketed by material **and** merge signature, and a reused mesh is a
15
+ * part of its own, so two parts can share a `material.uuid`.
8
16
  */
9
17
  readonly id: string;
10
- /** Every mesh in the GLB using {@link material}, flattened and merged into one. */
18
+ /** The geometry each copy draws. */
11
19
  readonly geometry: BufferGeometry;
12
- /** The material the GLB authored for those meshes. Shared; clone before mutating. */
20
+ /** The material the GLB authored for that geometry. Shared; clone before mutating. */
13
21
  readonly material: Material;
22
+ /**
23
+ * Where each copy of {@link geometry} sits in the model's own space, in the rest pose. Never
24
+ * empty; a merged part has the identity alone.
25
+ *
26
+ * Kept apart rather than merged because each copy is then its own instance, with its own small
27
+ * bounds: a ray or a frustum that misses a tree skips that tree's triangles, where one geometry
28
+ * spanning the model is tested whole.
29
+ */
30
+ readonly copies: readonly Matrix4[];
31
+ /**
32
+ * How the part moves when the GLB animates it. Absent for a part that never moves. Moves every
33
+ * copy alike: the node's displacement applies outside each copy's matrix.
34
+ */
35
+ readonly motion?: PartMotion;
36
+ }
37
+ /**
38
+ * The node an animated part follows. Its geometry is baked in the rest pose, so what an instance
39
+ * adds is the node's displacement from that pose: `node.matrixWorld · restInverse`.
40
+ */
41
+ export interface PartMotion {
42
+ /** The part's nearest animated ancestor-or-self, inside {@link ModelAnimation.mixer}'s root. */
43
+ readonly node: Object3D;
44
+ /** The inverse of `node.matrixWorld` in the rest pose the geometry was baked in. */
45
+ readonly restInverse: Matrix4;
46
+ }
47
+ /** The clips a GLB carries, all playing on a loop. Shared by every layer drawing the asset. */
48
+ export interface ModelAnimation {
49
+ /** Drives the loaded scene; every clip has a playing action. */
50
+ readonly mixer: AnimationMixer;
14
51
  }
15
52
  /** A parsed GLB, ready to be instanced. */
16
53
  export interface ModelAsset {
17
54
  /** Where it was loaded from; also what picks out the defs drawing it. */
18
55
  readonly url: string;
19
- /** One entry per distinct source material, so a whole layer costs one draw call per entry. */
56
+ /**
57
+ * One entry per distinct source material, plus one per mesh the GLB reuses, so a whole layer
58
+ * costs one draw call per entry.
59
+ */
20
60
  readonly parts: readonly ModelPart[];
21
61
  /**
22
- * The union of every baked part's bounds, in the model's own y-up space. `ModelContainer` maps
23
- * them into the plan's once, which is the only place the two frames meet.
62
+ * The union of every part's copies' bounds, in the model's own y-up space. `ModelContainer` maps
63
+ * them into the plan's once, which is the only place the two frames meet. Rest pose for an
64
+ * animated model, so its fitted scale does not change while it moves.
24
65
  */
25
66
  readonly extents: Box3;
67
+ /** Present when the GLB carries clips that move some of its parts. */
68
+ readonly animation?: ModelAnimation;
26
69
  }
27
70
  /**
28
- * Flattens a loaded glTF scene and merges it down to one geometry per source material.
71
+ * Poses an animated asset at a point in time. Takes the absolute time rather than a step, because
72
+ * every animated part of every layer drawing the asset calls it each frame, and stepping would play
73
+ * the clips once per caller.
74
+ * @param animation - The asset's animation.
75
+ * @param seconds - The time to pose at.
76
+ */
77
+ export declare function poseAnimation(animation: ModelAnimation, seconds: number): void;
78
+ /**
79
+ * Splits a loaded glTF scene into parts: one per mesh the GLB places more than once, and the rest
80
+ * merged down to one geometry per source material.
29
81
  *
30
- * Per mesh node, its geometry is cloned and transformed by the node's world matrix, so every vertex
31
- * lands relative to the model's root and the node hierarchy is no longer needed — which is what lets
32
- * the merge happen at all. Then it is filed under its material, sub-keyed by {@link mergeSignature},
33
- * because `mergeGeometries` requires its inputs to agree about their attributes.
82
+ * Every mesh node is first filed under what it draws — its geometry, its material, and the animated
83
+ * node it follows, if any — with its world matrix as one placement. An `EXT_mesh_gpu_instancing`
84
+ * node (an `InstancedMesh`, from gltfpack `-mi`) files one placement per instance; its per-instance
85
+ * colors and custom attributes are dropped with a warning.
34
86
  *
35
- * Two shapes compressors emit are unpacked on the way in. An `EXT_mesh_gpu_instancing` node (an
36
- * `InstancedMesh`, from gltfpack `-mi`) is baked once per instance, since the def is our only
37
- * instanced unit; its per-instance colors and custom attributes are dropped with a warning. Quantized
38
- * attributes (`KHR_mesh_quantization`, from gltfpack) are widened to floats first — see
39
- * {@link toFloatGeometry}.
87
+ * **A geometry placed more than once stays one geometry**, with its placements as the part's
88
+ * {@link ModelPart.copies}, so each draws as its own instance. A venue's trees are the case this is
89
+ * for: a thousand copies of a few small meshes, which merged into a geometry whose bounds covered
90
+ * the venue, so every pointer ray over it tested every tree's triangles.
91
+ *
92
+ * **A geometry placed once is merged.** It is cloned and transformed by its placement, so every
93
+ * vertex lands relative to the model's root and the node hierarchy is no longer needed — which is
94
+ * what lets the merge happen at all. Then it is filed under its material, sub-keyed by
95
+ * {@link mergeSignature}, because `mergeGeometries` requires its inputs to agree about their
96
+ * attributes. Quantized attributes (`KHR_mesh_quantization`, from gltfpack) are widened to floats
97
+ * first — see {@link toFloatGeometry}.
40
98
  *
41
99
  * **Nothing here knows about the plan.** The geometry stays in the model's own space, glTF's y-up,
42
100
  * and the mapping onto the plan is a transform the *mesh* carries — see `ModelContainer`. That is
@@ -46,9 +104,15 @@ export interface ModelAsset {
46
104
  * Merging is what replaces legacy's `BatchedMesh`: we never address a sub-mesh individually — the
47
105
  * addressable unit is the def — so one geometry per material is strictly better, and it costs no
48
106
  * `WEBGL_multi_draw` path.
107
+ *
108
+ * Animation survives the flattening only where it moves whole nodes. A mesh under an animated node
109
+ * is filed by that node too, and the part records it as its {@link PartMotion}, so the instance can
110
+ * add the node's displacement each frame. Skinned meshes and morph targets are drawn in their rest
111
+ * pose, with a warning.
49
112
  * @param scene - The glTF scene to bake.
50
113
  * @param url - Where it came from; carried on the asset, and names the model in diagnostics.
114
+ * @param clips - The GLB's animations.
51
115
  * @returns The parsed asset.
52
116
  */
53
- export declare function bakeGltf(scene: Group, url: string): ModelAsset;
117
+ export declare function bakeGltf(scene: Group, url: string, clips?: AnimationClip[]): ModelAsset;
54
118
  //# sourceMappingURL=model-asset.d.ts.map
@@ -1,20 +1,38 @@
1
- import { Box3, BufferAttribute, InstancedMesh, Matrix4, Mesh, } from 'three';
1
+ import { AnimationMixer, Box3, BufferAttribute, InstancedBufferAttribute, InstancedMesh, Matrix4, Mesh, PropertyBinding, SkinnedMesh, Vector3, } from 'three';
2
2
  import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
3
3
  import { createLogger } from '../../utils/logging';
4
4
  const logger = createLogger('model');
5
5
  /**
6
- * Flattens a loaded glTF scene and merges it down to one geometry per source material.
6
+ * Poses an animated asset at a point in time. Takes the absolute time rather than a step, because
7
+ * every animated part of every layer drawing the asset calls it each frame, and stepping would play
8
+ * the clips once per caller.
9
+ * @param animation - The asset's animation.
10
+ * @param seconds - The time to pose at.
11
+ */
12
+ export function poseAnimation(animation, seconds) {
13
+ animation.mixer.setTime(seconds);
14
+ animation.mixer.getRoot().updateMatrixWorld(true);
15
+ }
16
+ /**
17
+ * Splits a loaded glTF scene into parts: one per mesh the GLB places more than once, and the rest
18
+ * merged down to one geometry per source material.
7
19
  *
8
- * Per mesh node, its geometry is cloned and transformed by the node's world matrix, so every vertex
9
- * lands relative to the model's root and the node hierarchy is no longer needed — which is what lets
10
- * the merge happen at all. Then it is filed under its material, sub-keyed by {@link mergeSignature},
11
- * because `mergeGeometries` requires its inputs to agree about their attributes.
20
+ * Every mesh node is first filed under what it draws — its geometry, its material, and the animated
21
+ * node it follows, if any — with its world matrix as one placement. An `EXT_mesh_gpu_instancing`
22
+ * node (an `InstancedMesh`, from gltfpack `-mi`) files one placement per instance; its per-instance
23
+ * colors and custom attributes are dropped with a warning.
12
24
  *
13
- * Two shapes compressors emit are unpacked on the way in. An `EXT_mesh_gpu_instancing` node (an
14
- * `InstancedMesh`, from gltfpack `-mi`) is baked once per instance, since the def is our only
15
- * instanced unit; its per-instance colors and custom attributes are dropped with a warning. Quantized
16
- * attributes (`KHR_mesh_quantization`, from gltfpack) are widened to floats first — see
17
- * {@link toFloatGeometry}.
25
+ * **A geometry placed more than once stays one geometry**, with its placements as the part's
26
+ * {@link ModelPart.copies}, so each draws as its own instance. A venue's trees are the case this is
27
+ * for: a thousand copies of a few small meshes, which merged into a geometry whose bounds covered
28
+ * the venue, so every pointer ray over it tested every tree's triangles.
29
+ *
30
+ * **A geometry placed once is merged.** It is cloned and transformed by its placement, so every
31
+ * vertex lands relative to the model's root and the node hierarchy is no longer needed — which is
32
+ * what lets the merge happen at all. Then it is filed under its material, sub-keyed by
33
+ * {@link mergeSignature}, because `mergeGeometries` requires its inputs to agree about their
34
+ * attributes. Quantized attributes (`KHR_mesh_quantization`, from gltfpack) are widened to floats
35
+ * first — see {@link toFloatGeometry}.
18
36
  *
19
37
  * **Nothing here knows about the plan.** The geometry stays in the model's own space, glTF's y-up,
20
38
  * and the mapping onto the plan is a transform the *mesh* carries — see `ModelContainer`. That is
@@ -24,13 +42,20 @@ const logger = createLogger('model');
24
42
  * Merging is what replaces legacy's `BatchedMesh`: we never address a sub-mesh individually — the
25
43
  * addressable unit is the def — so one geometry per material is strictly better, and it costs no
26
44
  * `WEBGL_multi_draw` path.
45
+ *
46
+ * Animation survives the flattening only where it moves whole nodes. A mesh under an animated node
47
+ * is filed by that node too, and the part records it as its {@link PartMotion}, so the instance can
48
+ * add the node's displacement each frame. Skinned meshes and morph targets are drawn in their rest
49
+ * pose, with a warning.
27
50
  * @param scene - The glTF scene to bake.
28
51
  * @param url - Where it came from; carried on the asset, and names the model in diagnostics.
52
+ * @param clips - The GLB's animations.
29
53
  * @returns The parsed asset.
30
54
  */
31
- export function bakeGltf(scene, url) {
32
- const buckets = new Map();
33
- const extents = new Box3();
55
+ export function bakeGltf(scene, url, clips = []) {
56
+ const animated = animatedNodes(scene, clips, url);
57
+ const motions = new Map();
58
+ const uses = new Map();
34
59
  scene.updateMatrixWorld(true);
35
60
  scene.traverse((node) => {
36
61
  // `instanceof` on a generic class instantiates its parameters as `any`, so the narrowed node is
@@ -44,39 +69,52 @@ export function bakeGltf(scene, url) {
44
69
  const material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;
45
70
  if (!material)
46
71
  return;
47
- const source = toFloatGeometry(mesh.geometry);
48
- // Per-instance attributes three parked on the shared geometry; each baked copy sheds them.
49
- const dropped = mesh instanceof InstancedMesh
50
- ? Object.keys(source.attributes).filter((name) => name.startsWith('_'))
51
- : [];
52
- const bake = (matrix) => {
53
- const baked = source.clone();
54
- for (const name of dropped)
55
- baked.deleteAttribute(name);
56
- baked.applyMatrix4(matrix);
57
- baked.computeBoundingBox();
58
- if (baked.boundingBox)
59
- extents.union(baked.boundingBox);
60
- const signature = mergeSignature(baked);
61
- const id = `${material.uuid}|${signature}`;
62
- const bucket = buckets.get(id) ?? { material, signature, geometries: [] };
63
- bucket.geometries.push(baked);
64
- buckets.set(id, bucket);
65
- };
72
+ if (mesh instanceof SkinnedMesh) {
73
+ logger.warn('model %s: skinned mesh "%s" is drawn in its rest pose', url, mesh.name);
74
+ }
75
+ const follows = nearestAnimated(mesh, animated);
76
+ let motion = follows ? motions.get(follows) : undefined;
77
+ if (follows && !motion) {
78
+ motion = { node: follows, restInverse: follows.matrixWorld.clone().invert() };
79
+ motions.set(follows, motion);
80
+ }
81
+ const key = `${mesh.geometry.uuid}|${material.uuid}${motion ? `|${motion.node.uuid}` : ''}`;
82
+ const use = uses.get(key) ?? { geometry: mesh.geometry, material, motion, placements: [] };
83
+ uses.set(key, use);
66
84
  if (!(mesh instanceof InstancedMesh)) {
67
- bake(mesh.matrixWorld);
85
+ use.placements.push(mesh.matrixWorld.clone());
68
86
  return;
69
87
  }
70
- const ignored = mesh.instanceColor ? [...dropped, '_COLOR_0'] : dropped;
88
+ const ignored = perInstanceAttributes(use.geometry);
89
+ if (mesh.instanceColor)
90
+ ignored.push('_COLOR_0');
71
91
  if (ignored.length > 0) {
72
92
  logger.warn('model %s: ignored per-instance attributes %s on mesh "%s"', url, ignored.join(', '), mesh.name);
73
93
  }
74
94
  for (let i = 0; i < mesh.count; i++) {
75
- bake(_matrix.multiplyMatrices(mesh.matrixWorld, mesh.getMatrixAt(i, _instanceMatrix)));
95
+ use.placements.push(new Matrix4().multiplyMatrices(mesh.matrixWorld, mesh.getMatrixAt(i, _instanceMatrix)));
76
96
  }
77
97
  });
98
+ const extents = new Box3();
99
+ const buckets = new Map();
100
+ const reused = [];
101
+ for (const [key, { geometry, material, motion, placements }] of uses) {
102
+ const source = withoutPerInstanceAttributes(geometry);
103
+ for (const placement of placements)
104
+ expandByPlaced(extents, source, placement);
105
+ if (placements.length > 1) {
106
+ reused.push(withMotion({ id: key, geometry: source, material, copies: placements }, motion));
107
+ continue;
108
+ }
109
+ const baked = toFloatGeometry(source).clone().applyMatrix4(placements[0]);
110
+ const signature = mergeSignature(baked);
111
+ const id = `${material.uuid}|${signature}${motion ? `|${motion.node.uuid}` : ''}`;
112
+ const bucket = buckets.get(id) ?? { material, signature, motion, geometries: [] };
113
+ bucket.geometries.push(baked);
114
+ buckets.set(id, bucket);
115
+ }
78
116
  const parts = [];
79
- for (const [id, { material, signature, geometries }] of buckets) {
117
+ for (const [id, { material, signature, motion, geometries }] of buckets) {
80
118
  const merged = geometries.length === 1 ? geometries[0] : mergeGeometries(geometries);
81
119
  // `mergeGeometries` still returns null when its inputs disagree about something the signature
82
120
  // does not cover — an attribute's item size or array type, a morph target. Reported rather than
@@ -86,9 +124,102 @@ export function bakeGltf(scene, url) {
86
124
  logger.warn('model %s: dropped a part, %d geometries would not merge — material "%s" (%s), %s', url, geometries.length, material.name, material.uuid, signature);
87
125
  continue;
88
126
  }
89
- parts.push({ id, geometry: merged, material });
127
+ parts.push(withMotion({ id, geometry: merged, material, copies: [new Matrix4()] }, motion));
128
+ }
129
+ parts.push(...reused);
130
+ if (motions.size === 0)
131
+ return { url, parts, extents };
132
+ const mixer = new AnimationMixer(scene);
133
+ for (const clip of clips)
134
+ mixer.clipAction(clip).play();
135
+ return { url, parts, extents, animation: { mixer } };
136
+ }
137
+ /**
138
+ * The nodes the clips move by position, rotation or scale. A morph-target track moves no node and
139
+ * is reported instead.
140
+ * @param scene - The scene the clips bind to.
141
+ * @param clips - The GLB's animations.
142
+ * @param url - Names the model in diagnostics.
143
+ * @returns The animated nodes.
144
+ */
145
+ function animatedNodes(scene, clips, url) {
146
+ const nodes = new Set();
147
+ for (const clip of clips) {
148
+ for (const track of clip.tracks) {
149
+ const { nodeName, propertyName } = PropertyBinding.parseTrackName(track.name);
150
+ if (propertyName === 'morphTargetInfluences') {
151
+ logger.warn('model %s: morph animation "%s" is not played', url, clip.name);
152
+ continue;
153
+ }
154
+ const node = PropertyBinding.findNode(scene, nodeName);
155
+ if (node)
156
+ nodes.add(node);
157
+ }
158
+ }
159
+ return nodes;
160
+ }
161
+ /**
162
+ * The nearest of a node and its ancestors that an animation moves. Everything below it is static, so
163
+ * its displacement is the whole of the mesh's.
164
+ * @param node - The mesh node.
165
+ * @param animated - The nodes the clips move.
166
+ * @returns The node to follow, or `null` when nothing above the mesh moves.
167
+ */
168
+ function nearestAnimated(node, animated) {
169
+ for (let current = node; current; current = current.parent) {
170
+ if (animated.has(current))
171
+ return current;
90
172
  }
91
- return { url, parts, extents };
173
+ return null;
174
+ }
175
+ /**
176
+ * A part, carrying a `motion` key only when it moves.
177
+ * @param part - The part without its motion.
178
+ * @param motion - The node it follows, if any.
179
+ * @returns The part.
180
+ */
181
+ function withMotion(part, motion) {
182
+ return motion ? { ...part, motion } : part;
183
+ }
184
+ /**
185
+ * Grows a box to hold a geometry's vertices where a placement puts them. Vertex by vertex rather
186
+ * than the geometry's bounding box moved, which is larger than what it holds once the placement
187
+ * rotates: the extents set the fitted scale of every def drawing the model.
188
+ * @param box - The box to grow.
189
+ * @param geometry - The geometry.
190
+ * @param placement - Where it sits.
191
+ */
192
+ function expandByPlaced(box, geometry, placement) {
193
+ const position = geometry.getAttribute('position');
194
+ // `fromBufferAttribute` denormalizes, so a quantized geometry measures as its widened copy would.
195
+ for (let i = 0; i < position.count; i++) {
196
+ box.expandByPoint(_vertex.fromBufferAttribute(position, i).applyMatrix4(placement));
197
+ }
198
+ }
199
+ /**
200
+ * The per-instance attributes three's glTF loader parks on a GPU-instanced node's geometry.
201
+ * @param geometry - The geometry.
202
+ * @returns Their names.
203
+ */
204
+ function perInstanceAttributes(geometry) {
205
+ return Object.entries(geometry.attributes)
206
+ .filter(([name, attribute]) => name.startsWith('_') && attribute instanceof InstancedBufferAttribute)
207
+ .map(([name]) => name);
208
+ }
209
+ /**
210
+ * The geometry without its {@link perInstanceAttributes}. A part's per-instance state lives in the
211
+ * mesh's textures, so an instanced attribute left on the geometry is one nothing should read.
212
+ * @param geometry - The geometry; left untouched.
213
+ * @returns The geometry itself, or a copy without them.
214
+ */
215
+ function withoutPerInstanceAttributes(geometry) {
216
+ const dropped = perInstanceAttributes(geometry);
217
+ if (dropped.length === 0)
218
+ return geometry;
219
+ const shed = geometry.clone();
220
+ for (const name of dropped)
221
+ shed.deleteAttribute(name);
222
+ return shed;
92
223
  }
93
224
  /**
94
225
  * A stable description of what `mergeGeometries` insists its inputs agree about: whether they are
@@ -140,5 +271,5 @@ function isPlainFloat(attribute) {
140
271
  attribute.array instanceof Float32Array &&
141
272
  !attribute.normalized);
142
273
  }
143
- const _matrix = new Matrix4();
144
274
  const _instanceMatrix = new Matrix4();
275
+ const _vertex = new Vector3();
@@ -1,8 +1,9 @@
1
1
  import { type Rect } from '@expofp/geometry';
2
2
  import { type Box3, Matrix4 } from 'three';
3
3
  import { type InstancedMeshImpl, type InstancedMeshImplParams } from '../../core/instanced/InstancedMesh';
4
- import { type ModelDef } from '../../types/defs';
4
+ import { type ModelDef, type RenderableDef } from '../../types/defs';
5
5
  import { SlotContainer } from '../containers';
6
+ import { type ModelPart, type PartMotion } from './model-asset';
6
7
  /**
7
8
  * The per-instance uniform a model mesh reads its opacity from. The container owns the name: it
8
9
  * declares the schema on bind and writes each slot's value, and hands the name to `ModelMaterial`,
@@ -30,13 +31,19 @@ export type ModelKind = (typeof MODEL_KINDS)[number];
30
31
  */
31
32
  export declare function modelKindOf(def: ModelDef): ModelKind;
32
33
  /**
33
- * One model part's slot bookkeeping: every def in the layer drawing that part gets an instance, so
34
- * twenty copies of a chair are one draw call rather than twenty.
34
+ * One model part's slot bookkeeping: every def in the layer drawing that part gets a slot, so twenty
35
+ * copies of a chair are one draw call rather than twenty.
35
36
  *
36
37
  * Much simpler than a shape container. The geometry is the part's — shared, never per instance — so
37
38
  * there is no geometry cache and no capacity pre-scan, and `InstancedMeshImpl` grows its own buffers,
38
- * so nothing here has to size anything. What is left is a slot per def and the transform each one
39
- * draws with.
39
+ * so nothing here has to size anything. What is left is a slot per def and the transforms it draws
40
+ * with.
41
+ *
42
+ * **A slot is a group of mesh instances**, one per copy of the part (see `ModelPart.copies`): a
43
+ * def placing a model with five hundred trees holds five hundred instances of the tree part. So, as
44
+ * in the text container, a slot is this container's own number and not the mesh's, and every
45
+ * per-instance write goes to each instance in the group. A merged part has one copy, so its group
46
+ * holds one instance.
40
47
  */
41
48
  export declare class ModelContainer extends SlotContainer<null, InstancedMeshImpl, ModelDef> {
42
49
  /** The constructor args R3F builds the mesh from; a frozen snapshot, never mutated. */
@@ -48,15 +55,26 @@ export declare class ModelContainer extends SlotContainer<null, InstancedMeshImp
48
55
  * requires and {@link place}'s plan-space answers land where they say. See {@link PLAN_FROM_GLTF}.
49
56
  */
50
57
  readonly meshMatrix: Matrix4;
58
+ /** The node the part follows when the GLB animates it; absent for a static part. */
59
+ readonly motion: PartMotion | undefined;
60
+ /** Where each copy of the part sits in the model; a slot holds one instance per entry. */
61
+ private readonly copies;
51
62
  /** The model's bounds in plan units; every instance is fitted against them. */
52
63
  private readonly extents;
64
+ /** Each slot's mesh instances, index-parallel to {@link copies}, with holes for released slots. */
65
+ private readonly groups;
66
+ private readonly freeSlots;
67
+ /** The slot holding each mesh instance, so a hit, which names an instance, resolves to a def. */
68
+ private readonly slotByInstance;
69
+ private slotCount;
53
70
  /**
54
71
  * Builds the bookkeeping for one model part.
55
72
  * @param extents - The model's own bounds, y-up, as `bakeGltf` left them.
56
- * @param count - How many defs the layer holds for this part, used as the mesh's initial capacity.
73
+ * @param count - How many defs the layer holds for this part; with the copies, sizes the mesh.
57
74
  * @param kind - Which of the layer's batches this is; its material is built for that one alone.
75
+ * @param part - Where the part's copies sit, and the animated node it follows, if any.
58
76
  */
59
- constructor(extents: Box3, count: number, kind?: ModelKind);
77
+ constructor(extents: Box3, count: number, kind?: ModelKind, part?: Pick<ModelPart, 'copies' | 'motion'>);
60
78
  /**
61
79
  * Paint order is not implemented for models, so this does nothing.
62
80
  *
@@ -74,16 +92,25 @@ export declare class ModelContainer extends SlotContainer<null, InstancedMeshImp
74
92
  */
75
93
  setPaintOrder(): void;
76
94
  /**
77
- * Writes a def's placement into its slot: the model's extents fitted into `bounds`.
95
+ * Writes a def's placement into its slot: each copy where the model puts it, the model's extents
96
+ * fitted into `bounds`, and for an animated part, moved by its node's current displacement from
97
+ * the rest pose.
78
98
  *
79
99
  * The mesh carries {@link PLAN_FROM_GLTF}, so its instances are placed in the model's own space,
80
100
  * while {@link fitToBounds} answers in the plan's. Conjugating moves the placement across — undo
81
101
  * the mesh's map, place, redo it — and is unavoidable: the instance matrix is innermost, so
82
102
  * anything the mesh applies outside it has to be taken back inside.
83
- * @param slot - The instance's slot.
103
+ * @param slot - The def's slot.
84
104
  * @param def - The def supplying the bounds.
85
105
  */
86
106
  place(slot: number, def: ModelDef): void;
107
+ /** Re-places every claimed slot, for an animated part after its node moved. */
108
+ follow(): void;
109
+ /**
110
+ * How far the followed node has moved from the pose the geometry was baked in, in glTF space.
111
+ * @returns The shared scratch matrix: the identity for a static part.
112
+ */
113
+ private displacement;
87
114
  /**
88
115
  * Writes a def's opacity into its slot — **clamped to opaque unless this batch blends**.
89
116
  *
@@ -96,10 +123,19 @@ export declare class ModelContainer extends SlotContainer<null, InstancedMeshImp
96
123
  * the def is still in this batch with its new opacity already written. Clamping is what makes the
97
124
  * gap invisible — the model simply stays solid until the batch that can blend it takes over —
98
125
  * without anything having to be fast enough.
99
- * @param slot - The instance's slot.
126
+ * @param slot - The def's slot.
100
127
  * @param def - The def supplying the opacity.
101
128
  */
102
129
  setOpacity(slot: number, def: ModelDef): void;
130
+ setVisibleAt(slot: number, visible: boolean): void;
131
+ /**
132
+ * The mesh reports the instance a ray hit, which is one copy of some def's model, so it resolves
133
+ * to a def through the slot holding it.
134
+ * @param instance - The instance the mesh reported.
135
+ * @returns The def, or `undefined` when no claimed slot holds that instance.
136
+ */
137
+ defAt(instance: number | undefined): RenderableDef | undefined;
138
+ protected writeDim(slot: number, amount: number): void;
103
139
  protected addInstance(): number;
104
140
  protected removeInstance(slot: number): void;
105
141
  }