@jgengine/shell 0.12.0 → 0.13.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 (44) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/GameHost.d.ts +2 -0
  3. package/dist/GameHost.js +25 -2
  4. package/dist/GamePlayerShell.js +15 -1
  5. package/dist/Shell3dPresentation.js +2 -2
  6. package/dist/camera/GameOrbitCamera.js +7 -1
  7. package/dist/camera/cameraCollision.d.ts +28 -0
  8. package/dist/camera/cameraCollision.js +34 -0
  9. package/dist/camera/cameraRigs.js +4 -8
  10. package/dist/camera/index.d.ts +1 -0
  11. package/dist/camera/index.js +1 -0
  12. package/dist/camera/rigMath.d.ts +7 -0
  13. package/dist/camera/rigMath.js +16 -0
  14. package/dist/environment/EnvironmentScene.js +6 -1
  15. package/dist/environment/RoadJunctions.d.ts +12 -0
  16. package/dist/environment/RoadJunctions.js +69 -0
  17. package/dist/environment/RoadRibbons.d.ts +8 -2
  18. package/dist/environment/RoadRibbons.js +26 -8
  19. package/dist/presentationResolve.d.ts +5 -1
  20. package/dist/presentationResolve.js +3 -1
  21. package/dist/render/PartMotion.d.ts +18 -0
  22. package/dist/render/PartMotion.js +91 -0
  23. package/dist/render/SceneModels.d.ts +9 -2
  24. package/dist/render/SceneModels.js +31 -180
  25. package/dist/render/measureBounds.d.ts +34 -0
  26. package/dist/render/measureBounds.js +127 -0
  27. package/dist/render/resolveModel.js +16 -10
  28. package/dist/render/useModelAnimation.d.ts +10 -0
  29. package/dist/render/useModelAnimation.js +198 -0
  30. package/dist/structures/GeneratedBuilding.d.ts +4 -0
  31. package/dist/structures/GeneratedBuilding.js +17 -7
  32. package/dist/world/WorldHud.d.ts +3 -1
  33. package/dist/world/WorldHud.js +2 -2
  34. package/dist/world/WorldScene.js +3 -2
  35. package/package.json +4 -4
  36. package/skills/jgengine/SKILL.md +1 -0
  37. package/skills/jgengine/api.md +13 -5
  38. package/skills/jgengine-ui/SKILL.md +6 -4
  39. package/skills/jgengine-ui/api.md +116 -6
  40. package/skills/jgengine-ui/capabilities.md +64 -0
  41. package/skills/jgengine-ui/reference.md +40 -3
  42. package/skills/jgengine-world/api.md +52 -24
  43. package/skills/jgengine-world/capabilities.md +8 -4
  44. package/skills/jgengine-world/reference.md +1 -1
@@ -0,0 +1,91 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useFrame } from "@react-three/fiber";
3
+ import { useEffect, useMemo, useRef } from "react";
4
+ import * as THREE from "three";
5
+ import { createPartPose, partMotionPhase, sampleBodyPose, samplePartPose, } from "@jgengine/core/game/partAnimation";
6
+ import { useGameContext } from "@jgengine/react/provider";
7
+ const FLINCH_RELEASE_SEC = 0.35;
8
+ const DEATH_RAMP_PER_SEC = 2.5;
9
+ const SPEED_SMOOTHING = 12;
10
+ /**
11
+ * Procedural motion rig for a rig-less part-composed character (`ModelPart.role` — see
12
+ * `@jgengine/core/game/partAnimation`). Wraps the whole composition in a root group that bobs,
13
+ * breathes, flinches on `combat.hitReaction`, and topples on `entity.died`, while each
14
+ * role-tagged part swings around its authored transform — legs/arms counter-phase from the
15
+ * entity's live movement speed, head counter-sway, tail wag, wing flap. Untagged parts render
16
+ * as static kit pieces. Children are the base model content (primitive, attachments).
17
+ */
18
+ export function PartMotionRig({ parts, model, instanceId, renderPart, children, }) {
19
+ const ctx = useGameContext();
20
+ const rootRef = useRef(null);
21
+ const partRefs = useRef([]);
22
+ const motionRef = useRef({
23
+ lastPos: null,
24
+ speed: 0,
25
+ flinch: 0,
26
+ death: 0,
27
+ });
28
+ const phase = useMemo(() => partMotionPhase(instanceId ?? model.url), [instanceId, model.url]);
29
+ useEffect(() => {
30
+ if (instanceId === undefined)
31
+ return;
32
+ const offHit = ctx.game.events.on("combat.hitReaction", (event) => {
33
+ if (event.instanceId === instanceId)
34
+ motionRef.current.flinch = 1;
35
+ });
36
+ const offDied = ctx.game.events.on("entity.died", (event) => {
37
+ if (event.instanceId === instanceId)
38
+ motionRef.current.death = Math.max(motionRef.current.death, 1e-6);
39
+ });
40
+ return () => {
41
+ offHit();
42
+ offDied();
43
+ };
44
+ }, [ctx, instanceId]);
45
+ const input = useMemo(() => ({ timeSec: 0, speed: 0, phase, flinch: 0, death: 0 }), [phase]);
46
+ const pose = useMemo(() => createPartPose(), []);
47
+ useFrame((frameState, delta) => {
48
+ const motion = motionRef.current;
49
+ if (delta > 0 && instanceId !== undefined) {
50
+ const entity = ctx.scene.entity.get(instanceId);
51
+ if (entity !== null) {
52
+ const [x, , z] = entity.position;
53
+ if (motion.lastPos !== null) {
54
+ const instantSpeed = Math.hypot(x - motion.lastPos[0], z - motion.lastPos[2]) / delta;
55
+ motion.speed += (instantSpeed - motion.speed) * Math.min(1, delta * SPEED_SMOOTHING);
56
+ }
57
+ motion.lastPos = [x, entity.position[1], z];
58
+ }
59
+ motion.flinch = Math.max(0, motion.flinch - delta / FLINCH_RELEASE_SEC);
60
+ if (motion.death > 0)
61
+ motion.death = Math.min(1, motion.death + delta * DEATH_RAMP_PER_SEC);
62
+ }
63
+ input.timeSec = frameState.clock.elapsedTime;
64
+ input.speed = motion.speed;
65
+ input.flinch = motion.flinch;
66
+ input.death = motion.death;
67
+ const root = rootRef.current;
68
+ if (root !== null) {
69
+ sampleBodyPose(input, model.partMotion, pose);
70
+ root.position.set(pose.position[0], pose.position[1], pose.position[2]);
71
+ root.rotation.set(pose.rotation[0], pose.rotation[1], pose.rotation[2]);
72
+ root.scale.set(pose.scale[0], pose.scale[1], pose.scale[2]);
73
+ }
74
+ for (let index = 0; index < parts.length; index += 1) {
75
+ const part = parts[index];
76
+ const group = partRefs.current[index];
77
+ if (group === null || group === undefined || part.role === undefined)
78
+ continue;
79
+ samplePartPose(part.role, input, model.partMotion, pose);
80
+ const base = part.position ?? [0, 0, 0];
81
+ const baseRotation = part.rotation ?? [0, 0, 0];
82
+ group.position.set(base[0] + pose.position[0], base[1] + pose.position[1], base[2] + pose.position[2]);
83
+ group.rotation.set(baseRotation[0] + pose.rotation[0], baseRotation[1] + pose.rotation[1], baseRotation[2] + pose.rotation[2]);
84
+ const baseScale = part.scale ?? 1;
85
+ group.scale.set(baseScale * pose.scale[0], baseScale * pose.scale[1], baseScale * pose.scale[2]);
86
+ }
87
+ });
88
+ return (_jsxs("group", { ref: rootRef, children: [children, parts.map((part, index) => (_jsx("group", { ref: (group) => {
89
+ partRefs.current[index] = group;
90
+ }, position: part.position ?? [0, 0, 0], rotation: part.rotation ?? [0, 0, 0], scale: part.scale ?? 1, children: renderPart(part, index) }, index)))] }));
91
+ }
@@ -3,12 +3,19 @@ import type { EntitySpriteConfig, ModelConfig } from "@jgengine/core/game/playab
3
3
  export declare function EntitySprite({ sprite }: {
4
4
  sprite: EntitySpriteConfig;
5
5
  }): import("react").JSX.Element;
6
- export declare function IsolatedEntityModel({ model, instanceId, fallback, }: {
6
+ export declare function IsolatedEntityModel({ model, instanceId, measure, fallback, }: {
7
7
  model: ModelConfig;
8
8
  instanceId?: string;
9
+ measure?: MeasureTarget;
9
10
  fallback?: ReactNode;
10
11
  }): import("react").JSX.Element;
11
- export declare function EntityModel({ model, instanceId }: {
12
+ /** Where a measured model reports its rendered bounds: an entity kind or an object catalog id. */
13
+ export interface MeasureTarget {
14
+ target: "entity" | "object";
15
+ key: string;
16
+ }
17
+ export declare function EntityModel({ model, instanceId, measure, }: {
12
18
  model: ModelConfig;
13
19
  instanceId?: string;
20
+ measure?: MeasureTarget;
14
21
  }): import("react").JSX.Element;
@@ -3,9 +3,11 @@ import { useFrame, useLoader } from "@react-three/fiber";
3
3
  import { useTexture } from "@react-three/drei";
4
4
  import { Component, Suspense, useEffect, useMemo, useRef } from "react";
5
5
  import * as THREE from "three";
6
- import { resolveOneShotClip } from "@jgengine/core/game/modelAnimation";
7
6
  import { useGameContext } from "@jgengine/react/provider";
8
7
  import { sharedGltfLoader } from "./modelLoad.js";
8
+ import { measureLocalBounds, reportMeasuredBounds } from "./measureBounds.js";
9
+ import { useModelAnimation } from "./useModelAnimation.js";
10
+ import { PartMotionRig } from "./PartMotion.js";
9
11
  import { applyMaterialOverride } from "../materialOverride.js";
10
12
  import { applyPaintTextureToMaterials, cacheStandardMaterials, cloneModelScene, createPaintCanvas, disposeClonedMaterials, disposePaintCanvas, syncPaintCanvas, } from "./modelRender.js";
11
13
  export function EntitySprite({ sprite }) {
@@ -26,8 +28,8 @@ class ModelFallbackBoundary extends Component {
26
28
  return this.state.failed ? this.props.fallback : this.props.children;
27
29
  }
28
30
  }
29
- export function IsolatedEntityModel({ model, instanceId, fallback, }) {
30
- return (_jsx(ModelFallbackBoundary, { fallback: fallback ?? null, children: _jsx(Suspense, { fallback: null, children: _jsx(EntityModel, { model: model, instanceId: instanceId }) }) }));
31
+ export function IsolatedEntityModel({ model, instanceId, measure, fallback, }) {
32
+ return (_jsx(ModelFallbackBoundary, { fallback: fallback ?? null, children: _jsx(Suspense, { fallback: null, children: _jsx(EntityModel, { model: model, instanceId: instanceId, measure: measure }) }) }));
31
33
  }
32
34
  function BoneAttachment({ rig, model, slot, position, rotation, scale, }) {
33
35
  const gltf = useLoader(sharedGltfLoader, model.url);
@@ -83,7 +85,7 @@ function ModelMaterialMapsApplier({ scene, maps }) {
83
85
  }, [scene, textures]);
84
86
  return null;
85
87
  }
86
- export function EntityModel({ model, instanceId }) {
88
+ export function EntityModel({ model, instanceId, measure, }) {
87
89
  const gltf = useLoader(sharedGltfLoader, model.url);
88
90
  const ctx = useGameContext();
89
91
  const material = model.material;
@@ -119,150 +121,26 @@ export function EntityModel({ model, instanceId }) {
119
121
  useEffect(() => () => {
120
122
  disposeClonedMaterials(scene);
121
123
  }, [scene]);
122
- const animation = model.animation;
123
- const mixerRef = useRef(null);
124
- const animationPausedRef = useRef(false);
125
- const stateActionsRef = useRef(null);
126
- const states = animation?.states;
127
- const oneShots = animation?.oneShots;
128
- const oneShotPlayRef = useRef(null);
129
- const activeOneShotRef = useRef(null);
124
+ // A model without index-measured dims can't drive the fitted-collider path, so report the live
125
+ // measurement (the primitive mounts with only this uniform scale + position) instead of letting
126
+ // the kind fall back to a fixed-size box. Index dims keep priority — skip when they exist.
127
+ const measureTarget = measure?.target;
128
+ const measureKey = measure?.key;
129
+ const dimsMaxY = dims?.maxY;
130
+ const [positionX, positionY, positionZ] = position;
130
131
  useEffect(() => {
131
- if (animation === undefined || gltf.animations.length === 0) {
132
- mixerRef.current = null;
133
- stateActionsRef.current = null;
132
+ if (measureTarget === undefined || measureKey === undefined || dimsMaxY !== undefined)
134
133
  return;
135
- }
136
- const mixer = new THREE.AnimationMixer(scene);
137
- if (states !== undefined) {
138
- const clipFor = (name) => THREE.AnimationClip.findByName(gltf.animations, name) ?? gltf.animations[0];
139
- const actions = {
140
- idle: mixer.clipAction(clipFor(states.idle)),
141
- walk: mixer.clipAction(clipFor(states.walk)),
142
- ...(states.run === undefined ? {} : { run: mixer.clipAction(clipFor(states.run)) }),
143
- };
144
- for (const action of Object.values(actions)) {
145
- action.setLoop(THREE.LoopRepeat, Infinity);
146
- action.timeScale = animation.timeScale ?? 1;
147
- action.enabled = true;
148
- }
149
- actions.idle.play();
150
- mixer.update(0);
151
- mixerRef.current = mixer;
152
- stateActionsRef.current = { actions, active: "idle", lastPos: null, smoothedSpeed: 0 };
153
- animationPausedRef.current = false;
154
- let onOneShotFinished = null;
155
- if (oneShots !== undefined) {
156
- const clipNames = new Set();
157
- for (const spec of Object.values(oneShots)) {
158
- if (typeof spec === "string")
159
- clipNames.add(spec);
160
- else
161
- for (const name of spec)
162
- clipNames.add(name);
163
- }
164
- const oneShotActions = new Map();
165
- for (const name of clipNames) {
166
- const found = THREE.AnimationClip.findByName(gltf.animations, name);
167
- if (found === null)
168
- continue;
169
- const oneShotAction = mixer.clipAction(found);
170
- oneShotAction.setLoop(THREE.LoopOnce, 1);
171
- oneShotAction.enabled = true;
172
- oneShotActions.set(name, oneShotAction);
173
- }
174
- onOneShotFinished = ({ action }) => {
175
- const active = activeOneShotRef.current;
176
- if (active === null || action !== active.action || active.isDeath)
177
- return;
178
- const machine = stateActionsRef.current;
179
- const back = machine?.actions[machine.active];
180
- action.fadeOut(0.15);
181
- if (back !== undefined)
182
- back.reset().fadeIn(0.15).play();
183
- activeOneShotRef.current = null;
184
- };
185
- mixer.addEventListener("finished", onOneShotFinished);
186
- oneShotPlayRef.current = (event) => {
187
- const active = activeOneShotRef.current;
188
- if (active !== null && active.isDeath)
189
- return;
190
- const clipName = resolveOneShotClip(oneShots, event, Math.random());
191
- if (clipName === null)
192
- return;
193
- const oneShotAction = oneShotActions.get(clipName);
194
- if (oneShotAction === undefined)
195
- return;
196
- const machine = stateActionsRef.current;
197
- machine?.actions[machine.active]?.fadeOut(0.1);
198
- if (active !== null && active.action !== oneShotAction)
199
- active.action.stop();
200
- oneShotAction.clampWhenFinished = event === "death";
201
- oneShotAction.reset().fadeIn(0.1).play();
202
- activeOneShotRef.current = { action: oneShotAction, isDeath: event === "death" };
203
- };
204
- }
205
- return () => {
206
- if (onOneShotFinished !== null)
207
- mixer.removeEventListener("finished", onOneShotFinished);
208
- oneShotPlayRef.current = null;
209
- activeOneShotRef.current = null;
210
- mixer.stopAllAction();
211
- mixerRef.current = null;
212
- stateActionsRef.current = null;
213
- };
214
- }
215
- const clip = (animation.clip !== undefined ? THREE.AnimationClip.findByName(gltf.animations, animation.clip) : undefined) ??
216
- gltf.animations[0];
217
- const action = mixer.clipAction(clip);
218
- action.setLoop(animation.loop === false ? THREE.LoopOnce : THREE.LoopRepeat, Infinity);
219
- action.clampWhenFinished = animation.loop === false;
220
- action.timeScale = animation.timeScale ?? 1;
221
- action.enabled = true;
222
- action.paused = animation.paused === true;
223
- action.play();
224
- if (animation.time !== undefined)
225
- action.time = animation.time;
226
- mixer.update(0);
227
- mixerRef.current = mixer;
228
- animationPausedRef.current = animation.paused === true;
229
- return () => {
230
- mixer.stopAllAction();
231
- mixerRef.current = null;
232
- };
233
- }, [
234
- scene,
235
- gltf,
236
- animation?.clip,
237
- animation?.loop,
238
- animation?.timeScale,
239
- animation?.paused,
240
- animation?.time,
241
- states,
242
- oneShots,
243
- ]);
244
- useEffect(() => {
245
- if (instanceId === undefined || oneShots === undefined)
134
+ const raw = measureLocalBounds(scene);
135
+ if (raw === null)
246
136
  return;
247
- const fire = (event) => oneShotPlayRef.current?.(event);
248
- const offAnimation = ctx.game.events.on("entity.animation", (event) => {
249
- if (event.instanceId === instanceId)
250
- fire(event.event);
137
+ reportMeasuredBounds(ctx, measureTarget, measureKey, {
138
+ min: [raw.min[0] * scale + positionX, raw.min[1] * scale + positionY, raw.min[2] * scale + positionZ],
139
+ max: [raw.max[0] * scale + positionX, raw.max[1] * scale + positionY, raw.max[2] * scale + positionZ],
140
+ meshCount: raw.meshCount,
251
141
  });
252
- const offHit = ctx.game.events.on("combat.hitReaction", (event) => {
253
- if (event.instanceId === instanceId)
254
- fire("hit");
255
- });
256
- const offDied = ctx.game.events.on("entity.died", (event) => {
257
- if (event.instanceId === instanceId)
258
- fire("death");
259
- });
260
- return () => {
261
- offAnimation();
262
- offHit();
263
- offDied();
264
- };
265
- }, [ctx, instanceId, oneShots]);
142
+ }, [ctx, scene, scale, positionX, positionY, positionZ, measureTarget, measureKey, dimsMaxY]);
143
+ useModelAnimation(scene, gltf.animations, model.animation, instanceId);
266
144
  const paintCanvasRef = useRef(null);
267
145
  const paintDrawnCountRef = useRef(0);
268
146
  const paintVersionRef = useRef(-1);
@@ -276,41 +154,7 @@ export function EntityModel({ model, instanceId }) {
276
154
  paintVersionRef.current = -1;
277
155
  materialCacheRef.current = null;
278
156
  }, [scene]);
279
- useFrame((_state, delta) => {
280
- const stateMachine = stateActionsRef.current;
281
- if (stateMachine !== null && states !== undefined && instanceId !== undefined && delta > 0) {
282
- const entity = ctx.scene.entity.get(instanceId);
283
- if (entity !== null) {
284
- const [x, , z] = entity.position;
285
- if (stateMachine.lastPos !== null) {
286
- const instantSpeed = Math.hypot(x - stateMachine.lastPos[0], z - stateMachine.lastPos[2]) / delta;
287
- stateMachine.smoothedSpeed +=
288
- (instantSpeed - stateMachine.smoothedSpeed) * Math.min(1, delta * 12);
289
- }
290
- stateMachine.lastPos = [x, entity.position[1], z];
291
- const walkSpeed = states.walkSpeed ?? 0.5;
292
- const runSpeed = states.runSpeed ?? 6;
293
- const next = stateMachine.smoothedSpeed < walkSpeed
294
- ? "idle"
295
- : stateMachine.actions.run !== undefined && stateMachine.smoothedSpeed >= runSpeed
296
- ? "run"
297
- : "walk";
298
- if (next !== stateMachine.active) {
299
- if (activeOneShotRef.current === null) {
300
- const fade = states.fadeSec ?? 0.2;
301
- const from = stateMachine.actions[stateMachine.active];
302
- const to = stateMachine.actions[next];
303
- if (from !== undefined && to !== undefined) {
304
- to.reset().fadeIn(fade).play();
305
- from.fadeOut(fade);
306
- }
307
- }
308
- stateMachine.active = next;
309
- }
310
- }
311
- }
312
- if (mixerRef.current !== null && !animationPausedRef.current)
313
- mixerRef.current.update(delta);
157
+ useFrame(() => {
314
158
  if (instanceId === undefined)
315
159
  return;
316
160
  const paint = ctx.scene.entity.paint;
@@ -333,5 +177,12 @@ export function EntityModel({ model, instanceId }) {
333
177
  }
334
178
  paintDrawnCountRef.current = syncPaintCanvas(paintCanvasRef.current, cache.seedColor, strokes, paintDrawnCountRef.current);
335
179
  });
336
- return (_jsxs(_Fragment, { children: [_jsx("primitive", { object: scene, position: position, scale: [scale, scale, scale] }), material?.maps !== undefined ? _jsx(ModelMaterialMapsApplier, { scene: scene, maps: material.maps }) : null, (model.attachments ?? []).map((attachment, index) => typeof attachment.model === "string" ? null : (_jsx(BoneAttachment, { rig: scene, model: attachment.model, slot: attachment.slot, position: attachment.position, rotation: attachment.rotation, scale: attachment.scale }, `${attachment.slot}-${index}`))), (model.parts ?? []).map((part, index) => typeof part.model === "string" ? null : (_jsx(ModelPartGroup, { model: part.model, position: part.position, rotation: part.rotation, scale: part.scale }, index)))] }));
180
+ const base = (_jsxs(_Fragment, { children: [_jsx("primitive", { object: scene, position: position, scale: [scale, scale, scale] }), material?.maps !== undefined ? _jsx(ModelMaterialMapsApplier, { scene: scene, maps: material.maps }) : null, (model.attachments ?? []).map((attachment, index) => typeof attachment.model === "string" ? null : (_jsx(BoneAttachment, { rig: scene, model: attachment.model, slot: attachment.slot, position: attachment.position, rotation: attachment.rotation, scale: attachment.scale }, `${attachment.slot}-${index}`)))] }));
181
+ const parts = model.parts ?? [];
182
+ // Any role-tagged part switches the composition onto the procedural part-motion rig:
183
+ // root bob/flinch/topple plus per-role limb swing, driven from the entity's live state.
184
+ if (parts.some((part) => part.role !== undefined)) {
185
+ return (_jsx(PartMotionRig, { parts: parts, model: model, instanceId: instanceId, renderPart: (part) => (typeof part.model === "string" ? null : _jsx(EntityModel, { model: part.model })), children: base }));
186
+ }
187
+ return (_jsxs(_Fragment, { children: [base, parts.map((part, index) => typeof part.model === "string" ? null : (_jsx(ModelPartGroup, { model: part.model, position: part.position, rotation: part.rotation, scale: part.scale }, index)))] }));
337
188
  }
@@ -0,0 +1,34 @@
1
+ import { type ReactNode } from "react";
2
+ import * as THREE from "three";
3
+ import type { GameContext } from "@jgengine/core/runtime/gameContext";
4
+ /** Subtrees flagged with this userData key are excluded from bounds measurement — debug gizmos,
5
+ * selection quads, effect billboards that should not inflate the hitbox. Sprites and invisible
6
+ * subtrees are always excluded. */
7
+ export declare const MEASURE_EXCLUDE_KEY = "jgMeasureExclude";
8
+ /** Entity-local AABB of the meshes under a measured root, plus how many meshes contributed — the
9
+ * count lets callers detect async subtree fill-in without diffing bounds. */
10
+ export interface MeasuredLocalBounds {
11
+ min: [number, number, number];
12
+ max: [number, number, number];
13
+ meshCount: number;
14
+ }
15
+ /**
16
+ * Measure the meshes under `root` in `root`'s own frame (root's transform is the measuring frame,
17
+ * children compose their local matrices below it). Returns `null` when nothing measurable is
18
+ * mounted. Skinned meshes measure at bind pose — the standard engine approximation.
19
+ */
20
+ export declare function measureLocalBounds(root: THREE.Object3D): MeasuredLocalBounds | null;
21
+ /** Forward a measured result into the context (entity kind or object catalog id), deduping repeat
22
+ * reports of the same shape so remounts and multi-instance kinds don't churn collider resolution. */
23
+ export declare function reportMeasuredBounds(ctx: GameContext, target: "entity" | "object", key: string, bounds: MeasuredLocalBounds): void;
24
+ /**
25
+ * Wraps custom-rendered actor content (`renderEntity` / `renderObject`) and reports its measured
26
+ * entity-local bounds into collider resolution, so the hitbox wraps what is actually on screen
27
+ * instead of the fixed-size fallback box. A successful measure re-reports only when the subtree
28
+ * gained or lost meshes (async fill-in), not when idle animation nudges the same meshes.
29
+ */
30
+ export declare function MeasuredBoundsGroup({ target, measureKey, children, }: {
31
+ target: "entity" | "object";
32
+ measureKey: string;
33
+ children: ReactNode;
34
+ }): import("react").JSX.Element;
@@ -0,0 +1,127 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useFrame } from "@react-three/fiber";
3
+ import { useRef } from "react";
4
+ import * as THREE from "three";
5
+ import { useGameContext } from "@jgengine/react/provider";
6
+ /** Subtrees flagged with this userData key are excluded from bounds measurement — debug gizmos,
7
+ * selection quads, effect billboards that should not inflate the hitbox. Sprites and invisible
8
+ * subtrees are always excluded. */
9
+ export const MEASURE_EXCLUDE_KEY = "jgMeasureExclude";
10
+ const IDENTITY = new THREE.Matrix4();
11
+ const tmpBox = new THREE.Box3();
12
+ /**
13
+ * Measure the meshes under `root` in `root`'s own frame (root's transform is the measuring frame,
14
+ * children compose their local matrices below it). Returns `null` when nothing measurable is
15
+ * mounted. Skinned meshes measure at bind pose — the standard engine approximation.
16
+ */
17
+ export function measureLocalBounds(root) {
18
+ const box = new THREE.Box3();
19
+ box.makeEmpty();
20
+ const meshCount = collectBounds(root, null, box);
21
+ if (meshCount === 0 || box.isEmpty())
22
+ return null;
23
+ return {
24
+ min: [box.min.x, box.min.y, box.min.z],
25
+ max: [box.max.x, box.max.y, box.max.z],
26
+ meshCount,
27
+ };
28
+ }
29
+ function collectBounds(object, parentMatrix, into) {
30
+ if (parentMatrix !== null) {
31
+ if (!object.visible)
32
+ return 0;
33
+ if (object.isSprite === true)
34
+ return 0;
35
+ if (object.userData[MEASURE_EXCLUDE_KEY] === true)
36
+ return 0;
37
+ }
38
+ let matrix = null;
39
+ if (parentMatrix !== null) {
40
+ if (object.matrixAutoUpdate)
41
+ object.updateMatrix();
42
+ matrix = new THREE.Matrix4().multiplyMatrices(parentMatrix, object.matrix);
43
+ }
44
+ let count = 0;
45
+ const mesh = object;
46
+ if (mesh.isMesh === true && mesh.geometry !== undefined) {
47
+ const geometry = mesh.geometry;
48
+ if (geometry.boundingBox === null)
49
+ geometry.computeBoundingBox();
50
+ const bounds = geometry.boundingBox;
51
+ if (bounds !== null && !bounds.isEmpty()) {
52
+ tmpBox.copy(bounds);
53
+ if (matrix !== null)
54
+ tmpBox.applyMatrix4(matrix);
55
+ into.union(tmpBox);
56
+ count += 1;
57
+ }
58
+ }
59
+ const childMatrix = matrix ?? IDENTITY;
60
+ for (const child of object.children)
61
+ count += collectBounds(child, childMatrix, into);
62
+ return count;
63
+ }
64
+ const reportedByContext = new WeakMap();
65
+ const EPSILON = 0.01;
66
+ function boundsClose(a, b) {
67
+ for (let axis = 0; axis < 3; axis += 1) {
68
+ if (Math.abs(a.min[axis] - b.min[axis]) > EPSILON)
69
+ return false;
70
+ if (Math.abs(a.max[axis] - b.max[axis]) > EPSILON)
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+ /** Forward a measured result into the context (entity kind or object catalog id), deduping repeat
76
+ * reports of the same shape so remounts and multi-instance kinds don't churn collider resolution. */
77
+ export function reportMeasuredBounds(ctx, target, key, bounds) {
78
+ let map = reportedByContext.get(ctx);
79
+ if (map === undefined) {
80
+ map = new Map();
81
+ reportedByContext.set(ctx, map);
82
+ }
83
+ const registryKey = `${target}:${key}`;
84
+ const prev = map.get(registryKey);
85
+ if (prev !== undefined && prev.meshCount === bounds.meshCount && boundsClose(prev, bounds))
86
+ return;
87
+ const accepted = target === "entity"
88
+ ? ctx.scene.entity.reportBounds(key, bounds)
89
+ : ctx.scene.object.reportBounds(key, bounds);
90
+ if (accepted)
91
+ map.set(registryKey, bounds);
92
+ }
93
+ /** Frames-since-mount at which a marker re-measures — bounded retries catch content that fills in
94
+ * asynchronously after first mount without paying a traversal every frame forever. */
95
+ const MEASURE_FRAMES = [1, 15, 30, 60];
96
+ /**
97
+ * Wraps custom-rendered actor content (`renderEntity` / `renderObject`) and reports its measured
98
+ * entity-local bounds into collider resolution, so the hitbox wraps what is actually on screen
99
+ * instead of the fixed-size fallback box. A successful measure re-reports only when the subtree
100
+ * gained or lost meshes (async fill-in), not when idle animation nudges the same meshes.
101
+ */
102
+ export function MeasuredBoundsGroup({ target, measureKey, children, }) {
103
+ const ctx = useGameContext();
104
+ const groupRef = useRef(null);
105
+ const frameRef = useRef(0);
106
+ const attemptRef = useRef(0);
107
+ const lastMeshCountRef = useRef(null);
108
+ useFrame(() => {
109
+ if (attemptRef.current >= MEASURE_FRAMES.length)
110
+ return;
111
+ frameRef.current += 1;
112
+ if (frameRef.current < MEASURE_FRAMES[attemptRef.current])
113
+ return;
114
+ attemptRef.current += 1;
115
+ const group = groupRef.current;
116
+ if (group === null)
117
+ return;
118
+ const measured = measureLocalBounds(group);
119
+ if (measured === null)
120
+ return;
121
+ if (lastMeshCountRef.current === measured.meshCount)
122
+ return;
123
+ lastMeshCountRef.current = measured.meshCount;
124
+ reportMeasuredBounds(ctx, target, measureKey, measured);
125
+ });
126
+ return _jsx("group", { ref: groupRef, children: children });
127
+ }
@@ -1,3 +1,17 @@
1
+ /**
2
+ * The `ModelConfig` a resolved catalog ref renders as. Stamps `animation: "auto"` so any rigged
3
+ * catalog asset animates by default — the shell derives idle/walk/run states and one-shots from
4
+ * the loaded GLB's clip names; clipless models are unaffected. An explicit `style.animation`
5
+ * (merged after resolve) or `"none"` overrides.
6
+ */
7
+ function catalogModelConfig(ref) {
8
+ return {
9
+ url: ref.url,
10
+ ...(ref.dims === undefined ? {} : { dims: ref.dims }),
11
+ ...(ref.collisionMesh === undefined ? {} : { collisionMesh: ref.collisionMesh }),
12
+ animation: "auto",
13
+ };
14
+ }
1
15
  /**
2
16
  * Resolve a string asset id or a direct ModelConfig. Missing/misspelled catalog
3
17
  * ids throw — silent generic-primitive fallback only happens when the mapping
@@ -14,11 +28,7 @@ export function resolveModel(value, assets, context) {
14
28
  const where = context === undefined ? `model asset "${value}"` : `${context.seam}["${context.key}"] → "${value}"`;
15
29
  throw new Error(`[jgengine] missing ${where} — not in the asset catalog. Fix the id, register it, or omit the mapping to keep the deliberate primitive/sprite fallback.`);
16
30
  }
17
- return {
18
- url: ref.url,
19
- ...(ref.dims === undefined ? {} : { dims: ref.dims }),
20
- ...(ref.collisionMesh === undefined ? {} : { collisionMesh: ref.collisionMesh }),
21
- };
31
+ return catalogModelConfig(ref);
22
32
  }
23
33
  /** Soft lookup used when an object catalog id may double as a model asset id.
24
34
  * @internal
@@ -27,11 +37,7 @@ export function tryResolveCatalogModel(id, assets) {
27
37
  const ref = assets.resolve(id);
28
38
  if (ref === null)
29
39
  return undefined;
30
- return {
31
- url: ref.url,
32
- ...(ref.dims === undefined ? {} : { dims: ref.dims }),
33
- ...(ref.collisionMesh === undefined ? {} : { collisionMesh: ref.collisionMesh }),
34
- };
40
+ return catalogModelConfig(ref);
35
41
  }
36
42
  /**
37
43
  * Resolve an entity model plus bone-attachment / kit-of-parts models through the catalog
@@ -0,0 +1,10 @@
1
+ import * as THREE from "three";
2
+ import type { ModelAnimationConfig } from "@jgengine/core/game/playableGame";
3
+ /**
4
+ * The engine's model animation driver as a standalone hook — the same mixer `EntityModel` runs,
5
+ * for games that render a cloned scene themselves (custom materials, procedural composition).
6
+ * Handles `"auto"` derivation from the GLB's clip names, speed-driven idle/walk/run crossfades
7
+ * read from the entity's live position when `instanceId` is set, one-shots fired from
8
+ * `entity.animation` / `combat.hitReaction` / `entity.died`, held poses, and the death clamp.
9
+ */
10
+ export declare function useModelAnimation(scene: THREE.Object3D, clips: THREE.AnimationClip[], animationInput: ModelAnimationConfig | "auto" | "none" | undefined, instanceId?: string): void;