@jgengine/shell 0.10.0 → 0.11.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 (234) hide show
  1. package/CHANGELOG.md +13 -2
  2. package/LICENSE +203 -661
  3. package/README.md +1 -1
  4. package/dist/GamePhaseStamp.d.ts +1 -0
  5. package/dist/GamePhaseStamp.js +9 -0
  6. package/dist/GamePlayerShell.d.ts +0 -12
  7. package/dist/GamePlayerShell.js +88 -1043
  8. package/dist/GameUiPreview.js +0 -2
  9. package/dist/audio/audioEngine.js +30 -8
  10. package/dist/audio/audioWire.d.ts +22 -0
  11. package/dist/audio/audioWire.js +19 -0
  12. package/dist/behaviour.d.ts +2 -1
  13. package/dist/behaviour.js +2 -1
  14. package/dist/behaviourAttach.d.ts +1 -0
  15. package/dist/behaviourAttach.js +1 -0
  16. package/dist/behaviourDriver.d.ts +1 -0
  17. package/dist/behaviourDriver.js +1 -0
  18. package/dist/boundActionDispatch.d.ts +13 -0
  19. package/dist/boundActionDispatch.js +37 -0
  20. package/dist/camera/GameCameraRig.d.ts +5 -2
  21. package/dist/camera/GameCameraRig.js +2 -2
  22. package/dist/camera/GameFirstPersonCamera.d.ts +9 -2
  23. package/dist/camera/GameFirstPersonCamera.js +8 -3
  24. package/dist/camera/GameInspectionCamera.d.ts +1 -1
  25. package/dist/camera/GameInspectionCamera.js +2 -2
  26. package/dist/camera/GameOrbitCamera.js +24 -9
  27. package/dist/camera/cameraBlendMath.d.ts +3 -0
  28. package/dist/camera/cameraBlendMath.js +3 -0
  29. package/dist/camera/fovPreference.d.ts +6 -1
  30. package/dist/camera/fovPreference.js +6 -1
  31. package/dist/camera/index.d.ts +4 -7
  32. package/dist/camera/index.js +4 -7
  33. package/dist/camera/inspectionCameraMath.d.ts +7 -2
  34. package/dist/camera/inspectionCameraMath.js +7 -2
  35. package/dist/camera/orbitCameraMath.d.ts +36 -6
  36. package/dist/camera/orbitCameraMath.js +56 -6
  37. package/dist/camera/rigMath.d.ts +94 -24
  38. package/dist/camera/rigMath.js +100 -24
  39. package/dist/camera/rigResolve.d.ts +4 -2
  40. package/dist/camera/rigResolve.js +4 -2
  41. package/dist/camera/shakeChannel.d.ts +6 -2
  42. package/dist/camera/shakeChannel.js +6 -2
  43. package/dist/camera/shakeChannelMath.d.ts +1 -0
  44. package/dist/camera/shakeChannelMath.js +1 -0
  45. package/dist/cartridge/runtime.d.ts +15 -0
  46. package/dist/cartridge/runtime.js +556 -0
  47. package/dist/cartridge/spec.d.ts +188 -0
  48. package/dist/cartridge/spec.js +19 -0
  49. package/dist/cartridge/validate.d.ts +2 -0
  50. package/dist/cartridge/validate.js +78 -0
  51. package/dist/cartridge.d.ts +1 -1
  52. package/dist/cartridge.js +3 -3
  53. package/dist/commandSink.d.ts +8 -3
  54. package/dist/commandSink.js +8 -3
  55. package/dist/defineGame.js +25 -6
  56. package/dist/devtools/ColPanel.d.ts +1 -0
  57. package/dist/devtools/ColPanel.js +14 -0
  58. package/dist/devtools/DevtoolsOverlay.d.ts +7 -3
  59. package/dist/devtools/DevtoolsOverlay.js +19 -450
  60. package/dist/devtools/KeysPanel.d.ts +4 -0
  61. package/dist/devtools/KeysPanel.js +31 -0
  62. package/dist/devtools/LogsPanel.d.ts +1 -0
  63. package/dist/devtools/LogsPanel.js +12 -0
  64. package/dist/devtools/NetPanel.d.ts +4 -0
  65. package/dist/devtools/NetPanel.js +10 -0
  66. package/dist/devtools/PerfPanel.d.ts +4 -0
  67. package/dist/devtools/PerfPanel.js +53 -0
  68. package/dist/devtools/TunePanel.d.ts +3 -0
  69. package/dist/devtools/TunePanel.js +309 -0
  70. package/dist/devtools/agentBridge.d.ts +41 -0
  71. package/dist/devtools/agentBridge.js +262 -0
  72. package/dist/devtools/collisionDebug.d.ts +6 -0
  73. package/dist/devtools/collisionDebug.js +6 -0
  74. package/dist/devtools/collisionDebugMath.d.ts +8 -2
  75. package/dist/devtools/collisionDebugMath.js +24 -5
  76. package/dist/devtools/devtoolsOverrides.d.ts +6 -0
  77. package/dist/devtools/devtoolsOverrides.js +48 -0
  78. package/dist/devtools/panelAtoms.d.ts +9 -0
  79. package/dist/devtools/panelAtoms.js +10 -0
  80. package/dist/devtools/perfDiagnose.d.ts +2 -0
  81. package/dist/devtools/perfDiagnose.js +43 -0
  82. package/dist/diagnostics/RuntimeDiagnostics.d.ts +29 -0
  83. package/dist/diagnostics/RuntimeDiagnostics.js +69 -0
  84. package/dist/drivers/FrameDriver.d.ts +37 -0
  85. package/dist/drivers/FrameDriver.js +232 -0
  86. package/dist/drivers/HudOnlyDriver.d.ts +16 -0
  87. package/dist/drivers/HudOnlyDriver.js +60 -0
  88. package/dist/environment/Daylight.d.ts +23 -7
  89. package/dist/environment/Daylight.js +106 -13
  90. package/dist/environment/EnvironmentScene.js +32 -6
  91. package/dist/environment/VolumetricClouds.d.ts +17 -0
  92. package/dist/environment/VolumetricClouds.js +202 -0
  93. package/dist/environment/daylightCycle.d.ts +3 -1
  94. package/dist/environment/daylightCycle.js +3 -1
  95. package/dist/environment/groundPadMath.d.ts +3 -0
  96. package/dist/environment/groundPadMath.js +3 -0
  97. package/dist/environment/index.d.ts +1 -0
  98. package/dist/environment/index.js +1 -0
  99. package/dist/environment/skyLightingPolicy.d.ts +2 -0
  100. package/dist/environment/skyLightingPolicy.js +2 -0
  101. package/dist/hotbarActions.d.ts +26 -0
  102. package/dist/hotbarActions.js +27 -0
  103. package/dist/inputSink.d.ts +16 -4
  104. package/dist/inputSink.js +57 -7
  105. package/dist/materialOverride.d.ts +10 -0
  106. package/dist/materialOverride.js +15 -3
  107. package/dist/multiplayer.js +8 -2
  108. package/dist/postfx/PostProcessing.js +47 -9
  109. package/dist/postfx/gradeShader.js +9 -1
  110. package/dist/registry.d.ts +3 -2
  111. package/dist/render/EnvironmentLighting.d.ts +10 -0
  112. package/dist/render/EnvironmentLighting.js +34 -0
  113. package/dist/render/SceneLighting.d.ts +7 -0
  114. package/dist/render/SceneLighting.js +18 -0
  115. package/dist/render/SceneModels.d.ts +14 -0
  116. package/dist/render/SceneModels.js +337 -0
  117. package/dist/render/defaultSurface.d.ts +29 -0
  118. package/dist/render/defaultSurface.js +101 -0
  119. package/dist/render/modelLoad.d.ts +24 -0
  120. package/dist/render/modelLoad.js +73 -0
  121. package/dist/render/modelRender.d.ts +11 -0
  122. package/dist/render/modelRender.js +15 -0
  123. package/dist/render/resolveModel.d.ts +39 -3
  124. package/dist/render/resolveModel.js +79 -2
  125. package/dist/render/useEntityRenderCues.d.ts +13 -0
  126. package/dist/render/useEntityRenderCues.js +62 -0
  127. package/dist/scatter/InstancedScatter.d.ts +24 -0
  128. package/dist/scatter/InstancedScatter.js +130 -0
  129. package/dist/scatter/scatterModels.d.ts +25 -0
  130. package/dist/scatter/scatterModels.js +61 -0
  131. package/dist/scatter/scatterProxies.d.ts +6 -0
  132. package/dist/scatter/scatterProxies.js +94 -0
  133. package/dist/scatter.d.ts +1 -0
  134. package/dist/scatter.js +1 -0
  135. package/dist/scene/AuthoredScene.d.ts +82 -0
  136. package/dist/scene/AuthoredScene.js +173 -0
  137. package/dist/scene/GeneratedAssetRenderer.d.ts +14 -0
  138. package/dist/scene/GeneratedAssetRenderer.js +59 -0
  139. package/dist/scene/GrassFieldRenderer.d.ts +2 -0
  140. package/dist/scene/GrassFieldRenderer.js +25 -0
  141. package/dist/scene/SoilPatchRenderer.d.ts +2 -0
  142. package/dist/scene/SoilPatchRenderer.js +21 -0
  143. package/dist/scene/StudioStage.d.ts +37 -0
  144. package/dist/scene/StudioStage.js +42 -0
  145. package/dist/scene/WaterRenderer.d.ts +2 -0
  146. package/dist/scene/WaterRenderer.js +37 -0
  147. package/dist/scene/builtinSceneKindRenderers.d.ts +2 -0
  148. package/dist/scene/builtinSceneKindRenderers.js +22 -0
  149. package/dist/scene/sceneKindRenderers.d.ts +28 -0
  150. package/dist/scene/sceneKindRenderers.js +17 -0
  151. package/dist/scene.d.ts +1 -0
  152. package/dist/scene.js +1 -0
  153. package/dist/settings/appliedSettings.d.ts +5 -0
  154. package/dist/settings/appliedSettings.js +9 -0
  155. package/dist/settings/settingsController.d.ts +2 -0
  156. package/dist/settings/settingsController.js +22 -1
  157. package/dist/shellConstants.d.ts +4 -0
  158. package/dist/shellConstants.js +4 -0
  159. package/dist/shellMovement.d.ts +8 -0
  160. package/dist/shellMovement.js +11 -0
  161. package/dist/shellPointer.d.ts +20 -0
  162. package/dist/shellPointer.js +28 -0
  163. package/dist/structures/PlacementGhost.d.ts +4 -0
  164. package/dist/structures/PlacementGhost.js +4 -0
  165. package/dist/structures/TransformGizmo.d.ts +43 -0
  166. package/dist/structures/TransformGizmo.js +55 -0
  167. package/dist/structures/index.d.ts +1 -0
  168. package/dist/structures/index.js +1 -0
  169. package/dist/terrain/GrassField.js +1 -1
  170. package/dist/terrain/TerraformBrushCursor.js +3 -0
  171. package/dist/terrain/grassBudget.d.ts +11 -2
  172. package/dist/terrain/grassBudget.js +20 -4
  173. package/dist/terrain/grassGeometry.d.ts +3 -0
  174. package/dist/terrain/grassGeometry.js +3 -0
  175. package/dist/terrain/grassMaterial.d.ts +2 -0
  176. package/dist/terrain/grassMaterial.js +2 -0
  177. package/dist/terrain/random.d.ts +3 -0
  178. package/dist/terrain/random.js +3 -0
  179. package/dist/terrain/soilPatchMaterial.d.ts +10 -0
  180. package/dist/terrain/soilPatchMaterial.js +109 -0
  181. package/dist/terrain/terrainDetailMaterial.d.ts +19 -2
  182. package/dist/terrain/terrainDetailMaterial.js +72 -5
  183. package/dist/terrain/terrainMath.d.ts +8 -1
  184. package/dist/terrain/terrainMath.js +8 -1
  185. package/dist/touch/TouchControlsOverlay.d.ts +9 -5
  186. package/dist/touch/TouchControlsOverlay.js +201 -22
  187. package/dist/useShellMultiplayerSync.d.ts +9 -0
  188. package/dist/useShellMultiplayerSync.js +98 -0
  189. package/dist/visibility/CullingProvider.js +1 -1
  190. package/dist/water/OceanConfig.d.ts +2 -0
  191. package/dist/water/OceanConfig.js +2 -0
  192. package/dist/weather/fireSpreadPose.d.ts +1 -0
  193. package/dist/weather/fireSpreadPose.js +1 -0
  194. package/dist/weather/weatherGeometry.d.ts +1 -0
  195. package/dist/weather/weatherGeometry.js +1 -0
  196. package/dist/weather/weatherMath.d.ts +3 -0
  197. package/dist/weather/weatherMath.js +3 -0
  198. package/dist/weather/weatherUniforms.d.ts +3 -0
  199. package/dist/weather/weatherUniforms.js +3 -0
  200. package/dist/world/RetainedVfx.d.ts +10 -0
  201. package/dist/world/RetainedVfx.js +136 -0
  202. package/dist/world/WorldHud.d.ts +49 -2
  203. package/dist/world/WorldHud.js +87 -2
  204. package/dist/world/WorldScene.d.ts +21 -0
  205. package/dist/world/WorldScene.js +159 -0
  206. package/dist/world/WorldVfx.d.ts +9 -0
  207. package/dist/world/WorldVfx.js +184 -0
  208. package/dist/world/entityPose.d.ts +2 -0
  209. package/dist/world/entityPose.js +2 -0
  210. package/dist/world/floatTextStyle.d.ts +1 -0
  211. package/dist/world/floatTextStyle.js +1 -0
  212. package/dist/world/telegraphPulse.d.ts +1 -0
  213. package/dist/world/telegraphPulse.js +1 -0
  214. package/dist/world/worldBarSamples.d.ts +25 -0
  215. package/dist/world/worldBarSamples.js +38 -0
  216. package/dist/worldSky.d.ts +5 -0
  217. package/dist/worldSky.js +11 -0
  218. package/dist/worldSync.d.ts +2 -1
  219. package/dist/worldSync.js +2 -1
  220. package/package.json +6 -6
  221. package/skills/jgengine/SKILL.md +51 -0
  222. package/skills/jgengine/api.md +434 -0
  223. package/skills/jgengine/capabilities.md +29 -0
  224. package/skills/jgengine/reference-cartridge.md +72 -0
  225. package/skills/jgengine-ui/SKILL.md +36 -0
  226. package/skills/jgengine-ui/api.md +1852 -0
  227. package/skills/jgengine-ui/capabilities.md +142 -0
  228. package/skills/jgengine-ui/reference.md +500 -0
  229. package/skills/jgengine-ui/references/visual-scorecard.md +73 -0
  230. package/skills/jgengine-world/SKILL.md +38 -0
  231. package/skills/jgengine-world/api.md +2652 -0
  232. package/skills/jgengine-world/capabilities.md +370 -0
  233. package/skills/jgengine-world/reference.md +222 -0
  234. package/llms.txt +0 -2761
package/llms.txt DELETED
@@ -1,2761 +0,0 @@
1
- # @jgengine/shell
2
- > Game player shell for JGengine: React Three Fiber canvas, orbit camera, input tracking, HUD mounting, GameUiPreview, and a demo game. Consumers supply a GameRegistry.
3
-
4
- Version: 0.10.0
5
- License: AGPL-3.0-only
6
- Repository: https://github.com/Noisemaker111/jgengine
7
- Docs: https://jgengine.com
8
- Imports use deep paths: `@jgengine/shell/<path>`.
9
-
10
- ## Exported surface
11
-
12
- ### @jgengine/shell/GameHost
13
-
14
- - GameHost (function): function GameHost({ playable, gameId, wsUrl, multiplayer, resolveMultiplayer }: GameHostProps): React.JSX.Element
15
- - GameHostProps (interface): interface GameHostProps
16
-
17
- ### @jgengine/shell/GamePlayer
18
-
19
- - GamePlayer (function): function GamePlayer({ gameId, registry, fallbackGameId, loading = null, multiplayer = null }: GamePlayerProps): React.JSX.Element
20
- - GamePlayerProps (type): type GamePlayerProps = { gameId: string; registry: GameRegistry; fallbackGameId?: string; loading?: ReactNode; multiplayer?: ShellMultiplayer | null; }
21
-
22
- ### @jgengine/shell/GamePlayerShell
23
-
24
- - GamePlayerShell (function): function GamePlayerShell({ playable, multiplayer: rawMultiplayer = null, poster = false, onContextReady, }: { playable: PlayableGame; multiplayer?: ShellMultiplayer | null; poster?: boolean; /** Called once per boot after onInit/onNewPlayer with the live GameContext — a staging seam for screenshots,…
25
- - dispatchBoundAction (function): function dispatchBoundAction(ctx: GameContext, action: string, yaw: number, pitch: number, aim: Aim, reserved: ReadonlySet<string> = RESERVED_INPUT_ACTIONS, sink: CommandSink = localCommandSink(ctx)): void — Resolves and runs the command bound to `action` via the shell's action→command convention (shared by `FrameDriver` and `HudOnlyDriver`).
26
- - heldActionsFor (function): function heldActionsFor(tracker: Pick<ActionStateTracker<string>, "isDown">, actions: readonly string[]): string[] — Actions from `input` currently held down, for `ctx.input.publish` (#164.1); includes reserved movement/jump actions.
27
- - resolveWorldSky (function): function resolveWorldSky(world: WorldFeature | undefined): SkyEnvironmentDescriptor | undefined — The world's declared sky, when its world feature is an environment with one (#196.1).
28
- - shouldFireBoundAction (function): function shouldFireBoundAction(tracker: Pick<ActionStateTracker<string>, "isDown" | "wasPressed">, action: string, input: PlayableGame["game"]["input"], repeatFiredAt: ReadonlyMap<string, number>, now: number): boolean — Whether a bound action should fire this frame: on press, or on repeat interval while held (shared by `FrameDriver` and `HudOnlyDriver`).
29
-
30
- ### @jgengine/shell/GameUiPreview
31
-
32
- - GameUiPreview (function): function GameUiPreview({ playable, scenario = defaultUiScenario, }: { playable: PlayableGame; scenario?: UiPreviewScenario; }): React.JSX.Element
33
- - UiPreviewScenario (type): type UiPreviewScenario = (ctx: GameContext, playable: PlayableGame) => void
34
- - defaultUiScenario (const): const defaultUiScenario: UiPreviewScenario
35
-
36
- ### @jgengine/shell/audio/AudioComponents
37
-
38
- - AudioListener (function): function AudioListener({ engine }: { engine: AudioEngine }): null
39
- - EntityAudioEmitters (function): function EntityAudioEmitters({ engine, entitySounds, }: { engine: AudioEngine; entitySounds: Record<string, string> | undefined; }): null
40
- - ObjectAudioEmitters (function): function ObjectAudioEmitters({ engine, objectSounds, }: { engine: AudioEngine; objectSounds: Record<string, string> | undefined; }): null
41
-
42
- ### @jgengine/shell/audio/audioEngine
43
-
44
- - AudioEmitterHandle (interface): interface AudioEmitterHandle
45
- - AudioEngine (interface): interface AudioEngine
46
- - AudioSceneConfig (interface): interface AudioSceneConfig
47
- - Vec3 (interface): interface Vec3
48
- - createAudioEngine (function): function createAudioEngine(config: AudioSceneConfig = {}): AudioEngine
49
-
50
- ### @jgengine/shell/audio/musicDirector
51
-
52
- - CrossfadeOptions (interface): interface CrossfadeOptions — Options for a music crossfade.
53
- - MusicDirector (class): class MusicDirector — Runs a set of looping {@link MusicTheme}s as crossfadeable layers on one shared Web Audio graph: master → compressor → destination, with a fixed convolution reverb send. `crossfadeTo` swaps the audible theme; a 110ms lookahead scheduler keeps each active layer's notes queued ahead of the clock so loops are seamless.
54
-
55
- ### @jgengine/shell/audio/musicVoices
56
-
57
- - playMusicNote (function): function playMusicNote(ctx: Ctx, event: NoteEvent, when: number, spb: number, out: GainNode, transpose = 0): void — Play one theme note through its instrument voice into `out` (a per-layer gain node the director wires to master + reverb). `spb` is seconds-per-beat and `transpose` shifts the note in semitones for per-zone key changes. This is the engine's reusable instrument library; unknown instruments fall back to a sine.
58
-
59
- ### @jgengine/shell/audio/synthEngine
60
-
61
- - createNoiseBuffer (function): function createNoiseBuffer(ctx: BaseAudioContext): AudioBuffer — Build the shared 1-second mono white-noise buffer every noise voice samples from.
62
- - realizeSynthPatch (function): function realizeSynthPatch(ctx: BaseAudioContext, out: AudioNode, noiseBuf: AudioBuffer, patch: SynthPatch): void — Realise a procedural cue on Web Audio: every voice is scheduled at `ctx.currentTime + delay` into `out`, summed into one one-shot. `noiseBuf` is the shared buffer from {@link createNoiseBuffer}.
63
-
64
- ### @jgengine/shell/behaviour
65
-
66
- - Object3DBehaviour (class): class Object3DBehaviour extends Behaviour
67
- - attachObject3D (function): function attachObject3D<T extends Object3DBehaviour>(world: BehaviourWorld, object: Object3D, behaviour: T, nodeId: string = object.uuid): T
68
- - createBehaviourWorldDriver (function): function createBehaviourWorldDriver(world: BehaviourWorld): { start(): void; stop(): void; isRunning(): boolean; step(dt: number): void; }
69
- - useBehaviourWorld (function): function useBehaviourWorld(world: BehaviourWorld, scaleDt?: (rawDt: number) => number): void — Bootstraps `world` on mount and dispatches `world.update` every frame at simulation priority. Stops driving updates on unmount so remount does not double-step. `scaleDt` maps the raw frame delta to the dt behaviours receive — pass the game clock's scaling to keep behaviours on game time, or omit for real-time seconds. Games driving `world.update` themselves from `loop.onTick` should not also render this.
70
-
71
- ### @jgengine/shell/behaviourAttach
72
-
73
- - Object3DBehaviour (class): class Object3DBehaviour extends Behaviour
74
- - attachObject3D (function): function attachObject3D<T extends Object3DBehaviour>(world: BehaviourWorld, object: Object3D, behaviour: T, nodeId: string = object.uuid): T
75
-
76
- ### @jgengine/shell/behaviourDriver
77
-
78
- - createBehaviourWorldDriver (function): function createBehaviourWorldDriver(world: BehaviourWorld): { start(): void; stop(): void; isRunning(): boolean; step(dt: number): void; }
79
-
80
- ### @jgengine/shell/camera/GameCameraRig
81
-
82
- - GameCameraRig (function): function GameCameraRig({ yawRef, pitchRef, config, onDragChange, pointerControls, panKeysEnabled, director, }: GameCameraRigProps): React.JSX.Element
83
- - GameCameraRigProps (interface): interface GameCameraRigProps
84
- - resolveRigKind (function): function resolveRigKind(config: GameCameraConfig | undefined): CameraRigKind — Resolves which rig mounts from a `GameCameraConfig`. Precedence, most to least specific: an explicit `rig` field always wins; then `perspective: "first"` (the historical shorthand for `rig: "orbit" | "first"`); then the mere presence of a rig's own config block selects that rig, checked in the fixed order below (#207.8) so a config carrying more than one block resolves deterministically instead of depending on object key order. Set `rig` explicitly to break a tie.
85
-
86
- ### @jgengine/shell/camera/GameFirstPersonCamera
87
-
88
- - GameFirstPersonCamera (function): function GameFirstPersonCamera({ yawRef, pitchRef, config, followEntityId, }: GameFirstPersonCameraProps): React.JSX.Element | null
89
- - GameFirstPersonCameraProps (interface): interface GameFirstPersonCameraProps
90
- - readFirstPersonMuzzle (function): function readFirstPersonMuzzle(target: THREE.Vector3): boolean — World position of the first-person weapon muzzle, or false when no viewmodel is mounted.
91
-
92
- ### @jgengine/shell/camera/GameInspectionCamera
93
-
94
- - GameInspectionCamera (function): function GameInspectionCamera({ config: configPatch }: GameInspectionCameraProps): React.JSX.Element — Model-viewer style rig (#207.7): left-drag orbit, middle/right-drag pan, scroll zoom toward a configurable anchor. Orbits a fixed `target`; never reads player/entity state.
95
- - GameInspectionCameraProps (interface): interface GameInspectionCameraProps
96
-
97
- ### @jgengine/shell/camera/GameOrbitCamera
98
-
99
- - CameraFollowListener (type): type CameraFollowListener = (state: CameraFollowState) => void
100
- - GameOrbitCamera (function): function GameOrbitCamera({ yawRef, pitchRef, config: configPatch, followEntityId, resolveFollowTarget, onDragChange, onCameraFollow, pointerControls = false, }: GameOrbitCameraProps): React.JSX.Element
101
- - GameOrbitCameraProps (interface): interface GameOrbitCameraProps
102
- - seedOrbitCameraTarget (function): function seedOrbitCameraTarget(camera: Camera, target: Vector3, distance: number, height: number): void — Seed orbit target before controls mount (demo spawn at origin).
103
-
104
- ### @jgengine/shell/camera/PlayerFov
105
-
106
- - PlayerFovProvider (function): function PlayerFovProvider({ config, orthographic, children, }: { config?: GameCameraConfig; orthographic: boolean; children: ReactNode; }): React.JSX.Element
107
- - PlayerFovSlider (function): function PlayerFovSlider(): React.JSX.Element | null
108
- - PlayerFovState (interface): interface PlayerFovState
109
- - usePlayerFov (function): function usePlayerFov(): PlayerFovState
110
-
111
- ### @jgengine/shell/camera/cameraBlendMath
112
-
113
- - CameraBlendScratch (interface): interface CameraBlendScratch
114
- - applyCameraBlendStep (function): function applyCameraBlendStep(scratch: CameraBlendScratch, camera: Camera, targetFov: number, dt: number): boolean
115
- - captureCameraBlendFrom (function): function captureCameraBlendFrom(scratch: CameraBlendScratch, position: Vector3, quaternion: Quaternion, fov: number, duration: number): void
116
- - createCameraBlendScratch (function): function createCameraBlendScratch(Vector3Ctor: new () => Vector3, QuaternionCtor: new () => Quaternion): CameraBlendScratch
117
-
118
- ### @jgengine/shell/camera/cameraRigs
119
-
120
- - CAMERA_POST_FRAME_PRIORITY (const): const CAMERA_POST_FRAME_PRIORITY: number
121
- - CAMERA_RIG_FRAME_PRIORITY (const): const CAMERA_RIG_FRAME_PRIORITY: -1
122
- - CameraBlendScratch (interface): interface CameraBlendScratch
123
- - ChaseRig (function): function ChaseRig(props: RigProps): null
124
- - CinematicRig (function): function CinematicRig(props: RigProps): null
125
- - LockOnRig (function): function LockOnRig(props: RigProps): null
126
- - ObserverRig (function): function ObserverRig(props: RigProps): null — Detached spectator/photo cam (#120): binds to any entity or fixed point and auto-orbits it, reading no player input at all — the van CCTV / photo-mode / kill-cam rig. Distinct from every other rig, which drives from mouse/keys.
127
- - RigProps (interface): interface RigProps
128
- - RtsRig (function): function RtsRig(props: RigProps & { panKeysEnabled?: boolean }): null
129
- - ShoulderRig (function): function ShoulderRig(props: RigProps): null
130
- - SideScrollRig (function): function SideScrollRig(props: RigProps): null — Fixed side-on 2.5D follow rig: watches the followed entity from the perpendicular axis, never reading WASD/mouse-look.
131
- - TopDownRig (function): function TopDownRig(props: RigProps): null
132
- - applyCameraBlendStep (function): function applyCameraBlendStep(scratch: CameraBlendScratch, camera: Camera, targetFov: number, dt: number): boolean
133
- - captureCameraBlendFrom (function): function captureCameraBlendFrom(scratch: CameraBlendScratch, position: Vector3, quaternion: Quaternion, fov: number, duration: number): void
134
- - createCameraBlendScratch (function): function createCameraBlendScratch(Vector3Ctor: new () => Vector3, QuaternionCtor: new () => Quaternion): CameraBlendScratch
135
-
136
- ### @jgengine/shell/camera/fovPreference
137
-
138
- - PLAYER_FOV_DEFAULT (const): const PLAYER_FOV_DEFAULT: any
139
- - PLAYER_FOV_MAX (const): const PLAYER_FOV_MAX: 120
140
- - PLAYER_FOV_MIN (const): const PLAYER_FOV_MIN: 40
141
- - PLAYER_FOV_STORAGE_KEY (const): const PLAYER_FOV_STORAGE_KEY: "jgengine:player-fov"
142
- - PlayerFovBounds (interface): interface PlayerFovBounds
143
- - clampPlayerFov (function): function clampPlayerFov(value: unknown, min: number = PLAYER_FOV_MIN, max: number = PLAYER_FOV_MAX): number
144
- - composePlayerFov (function): function composePlayerFov(preference: number, poseFov: number, mode: "relative" | "absolute" = "relative", bounds: PlayerFovBounds = resolvePlayerFovBounds()): number — Composition model for perspective rigs: - preference is the player base FOV - poseFov is the rig's authored FOV (includes chase-speed modulation, ADS zoom, transitions) - relative mode shifts the authored FOV by (preference − default) so mods still stack - absolute mode (cinematic keyframes) keeps the authored FOV as-is
145
- - loadPlayerFov (function): function loadPlayerFov(bounds: PlayerFovBounds = resolvePlayerFovBounds(), storage: Pick<Storage, "getItem"> | null | undefined = defaultStorage()): number
146
- - resolvePlayerFovBounds (function): function resolvePlayerFovBounds(options?: { min?: number; max?: number; default?: number; }): PlayerFovBounds
147
- - savePlayerFov (function): function savePlayerFov(value: number, bounds: PlayerFovBounds = resolvePlayerFovBounds(), storage: Pick<Storage, "setItem"> | null | undefined = defaultStorage()): number
148
-
149
- ### @jgengine/shell/camera/index
150
-
151
- - CAMERA_POST_FRAME_PRIORITY (const): const CAMERA_POST_FRAME_PRIORITY: number
152
- - CAMERA_RIG_FRAME_PRIORITY (const): const CAMERA_RIG_FRAME_PRIORITY: -1
153
- - CameraBlendScratch (interface): interface CameraBlendScratch
154
- - CameraFollowListener (type): type CameraFollowListener = (state: CameraFollowState) => void
155
- - CameraFollowState (interface): interface CameraFollowState
156
- - CameraPose (interface): interface CameraPose
157
- - CameraShakeChannel (interface): interface CameraShakeChannel
158
- - CameraShakeContext (const): const CameraShakeContext: React.Context<CameraShakeChannel>
159
- - ChaseRig (function): function ChaseRig(props: RigProps): null
160
- - CinematicRig (function): function CinematicRig(props: RigProps): null
161
- - DEFAULT_ORBIT_CAMERA (const): const DEFAULT_ORBIT_CAMERA: ResolvedOrbitCameraConfig
162
- - DirectorCameraValues (interface): interface DirectorCameraValues
163
- - GAME_SIM_FRAME_PRIORITY (const): const GAME_SIM_FRAME_PRIORITY: 0 — Run simulation/movement before orbit follow so poses are current.
164
- - GameCameraRig (function): function GameCameraRig({ yawRef, pitchRef, config, onDragChange, pointerControls, panKeysEnabled, director, }: GameCameraRigProps): React.JSX.Element
165
- - GameCameraRigProps (interface): interface GameCameraRigProps
166
- - GameFirstPersonCamera (function): function GameFirstPersonCamera({ yawRef, pitchRef, config, followEntityId, }: GameFirstPersonCameraProps): React.JSX.Element | null
167
- - GameFirstPersonCameraProps (interface): interface GameFirstPersonCameraProps
168
- - GameInspectionCamera (function): function GameInspectionCamera({ config: configPatch }: GameInspectionCameraProps): React.JSX.Element — Model-viewer style rig (#207.7): left-drag orbit, middle/right-drag pan, scroll zoom toward a configurable anchor. Orbits a fixed `target`; never reads player/entity state.
169
- - GameInspectionCameraProps (interface): interface GameInspectionCameraProps
170
- - GameOrbitCamera (function): function GameOrbitCamera({ yawRef, pitchRef, config: configPatch, followEntityId, resolveFollowTarget, onDragChange, onCameraFollow, pointerControls = false, }: GameOrbitCameraProps): React.JSX.Element
171
- - GameOrbitCameraProps (interface): interface GameOrbitCameraProps
172
- - LockOnRig (function): function LockOnRig(props: RigProps): null
173
- - ORBIT_CAMERA_FRAME_PRIORITY (const): const ORBIT_CAMERA_FRAME_PRIORITY: -1 — Orbit follow reads the latest entity pose after GAME_SIM_FRAME_PRIORITY.
174
- - ObserverRig (function): function ObserverRig(props: RigProps): null — Detached spectator/photo cam (#120): binds to any entity or fixed point and auto-orbits it, reading no player input at all — the van CCTV / photo-mode / kill-cam rig. Distinct from every other rig, which drives from mouse/keys.
175
- - OrbitCameraConfig (interface): interface OrbitCameraConfig
176
- - OrbitFollowRuntimeState (interface): interface OrbitFollowRuntimeState
177
- - PLAYER_FOV_DEFAULT (const): const PLAYER_FOV_DEFAULT: any
178
- - PLAYER_FOV_MAX (const): const PLAYER_FOV_MAX: 120
179
- - PLAYER_FOV_MIN (const): const PLAYER_FOV_MIN: 40
180
- - PLAYER_FOV_STORAGE_KEY (const): const PLAYER_FOV_STORAGE_KEY: "jgengine:player-fov"
181
- - PlayerFovBounds (interface): interface PlayerFovBounds
182
- - PlayerFovProvider (function): function PlayerFovProvider({ config, orthographic, children, }: { config?: GameCameraConfig; orthographic: boolean; children: ReactNode; }): React.JSX.Element
183
- - PlayerFovSlider (function): function PlayerFovSlider(): React.JSX.Element | null
184
- - PlayerFovState (interface): interface PlayerFovState
185
- - ResolvedChase (interface): interface ResolvedChase
186
- - ResolvedDirectedCamera (interface): interface ResolvedDirectedCamera
187
- - ResolvedInspectionCameraConfig (interface): interface ResolvedInspectionCameraConfig
188
- - ResolvedObserver (interface): interface ResolvedObserver
189
- - ResolvedOrbitCameraConfig (interface): interface ResolvedOrbitCameraConfig — Fully resolved shell config after merging with DEFAULT_ORBIT_CAMERA.
190
- - ResolvedShoulder (interface): interface ResolvedShoulder
191
- - ResolvedSideScroll (interface): interface ResolvedSideScroll
192
- - ResolvedTopDown (interface): interface ResolvedTopDown
193
- - RigProps (interface): interface RigProps
194
- - RtsRig (function): function RtsRig(props: RigProps & { panKeysEnabled?: boolean }): null
195
- - ShakeOffset (interface): interface ShakeOffset
196
- - ShoulderRig (function): function ShoulderRig(props: RigProps): null
197
- - SideScrollRig (function): function SideScrollRig(props: RigProps): null — Fixed side-on 2.5D follow rig: watches the followed entity from the perpendicular axis, never reading WASD/mouse-look.
198
- - StaticCameraValues (interface): interface StaticCameraValues
199
- - TopDownRig (function): function TopDownRig(props: RigProps): null
200
- - TraumaState (interface): interface TraumaState
201
- - Vec3 (interface): interface Vec3
202
- - addTrauma (function): function addTrauma(state: TraumaState, amount: number): void — Add trauma (0..1) and clamp; larger hits raise the ceiling toward 1.
203
- - angleDelta (function): function angleDelta(a: number, b: number): number — Shortest signed angular delta from `a` to `b`, wrapped to (-PI, PI].
204
- - applyCameraBlendStep (function): function applyCameraBlendStep(scratch: CameraBlendScratch, camera: Camera, targetFov: number, dt: number): boolean
205
- - blendShoulder (function): function blendShoulder(hip: ResolvedShoulder, ads: ResolvedShoulder, t: number): ResolvedShoulder — Blend two shoulder framings by an ADS factor in [0,1].
206
- - cameraFollowStep (function): function cameraFollowStep(input: { camera: Vec3; target: Vec3; previousTarget: Vec3 | null; lockedDistance: number | null; }): CameraFollowState
207
- - cameraLookPitch (function): function cameraLookPitch(camera: Vec3, target: Vec3): number — Elevation the camera looks along (radians): negative = aiming down, positive = aiming up, 0 = level. Feeds aim.pitch so vertical aim tracks the camera.
208
- - cameraShake (function): function cameraShake(amplitude: number, decayPerSecond?: number): void — Feed the default camera-shake channel from anywhere (see G7 hitstop cross-cut).
209
- - captureCameraBlendFrom (function): function captureCameraBlendFrom(scratch: CameraBlendScratch, position: Vector3, quaternion: Quaternion, fov: number, duration: number): void
210
- - chaseDesiredPosition (function): function chaseDesiredPosition(follow: Vec3, yaw: number, resolved: ResolvedChase): Vec3 — Desired chase-camera position behind a vehicle facing `yaw` (before spring smoothing).
211
- - chaseLookAt (function): function chaseLookAt(follow: Vec3, yaw: number, resolved: ResolvedChase): Vec3 — Look point ahead of / above a chased vehicle.
212
- - cinematicSample (function): function cinematicSample(keyframes: readonly CameraKeyframe[], elapsed: number, loop: boolean, fallbackFov: number): CinematicSample — Sample a keyframe path at `elapsed` seconds. Each keyframe's `duration` is the travel time from the previous keyframe into it; segment easing is per the destination keyframe. Reports `done` once past the final keyframe (unless looping, which wraps `elapsed` into the total path duration).
213
- - clamp (function): function clamp(value: number, min: number, max: number): number
214
- - clampPlayerFov (function): function clampPlayerFov(value: unknown, min: number = PLAYER_FOV_MIN, max: number = PLAYER_FOV_MAX): number
215
- - composePlayerFov (function): function composePlayerFov(preference: number, poseFov: number, mode: "relative" | "absolute" = "relative", bounds: PlayerFovBounds = resolvePlayerFovBounds()): number — Composition model for perspective rigs: - preference is the player base FOV - poseFov is the rig's authored FOV (includes chase-speed modulation, ADS zoom, transitions) - relative mode shifts the authored FOV by (preference − default) so mods still stack - absolute mode (cinematic keyframes) keeps the authored FOV as-is
216
- - createCameraBlendScratch (function): function createCameraBlendScratch(Vector3Ctor: new () => Vector3, QuaternionCtor: new () => Quaternion): CameraBlendScratch
217
- - createCameraShakeChannel (function): function createCameraShakeChannel(defaultDecayPerSecond = 1.6): CameraShakeChannel
218
- - createTrauma (function): function createTrauma(): TraumaState
219
- - crossfadePose (function): function crossfadePose(from: CameraPose, to: CameraPose, t: number): CameraPose — Linear cross-fade between two full camera poses (position, lookAt, fov).
220
- - defaultCameraShakeChannel (const): const defaultCameraShakeChannel: CameraShakeChannel — Process-wide default channel. A shell mounts its own channel via `CameraShakeContext`, but game systems that have no React context (e.g. a `loop.onTick` reacting to `entity.died`) can import `cameraShake` and feed the default channel directly.
221
- - distanceBetween (function): function distanceBetween(a: Vec3, b: Vec3): number
222
- - forwardVector (function): function forwardVector(yaw: number): Vec3
223
- - lerp (function): function lerp(from: number, to: number, blend: number): number
224
- - lerpVec3 (function): function lerpVec3(from: Vec3, to: Vec3, blend: number): Vec3
225
- - loadPlayerFov (function): function loadPlayerFov(bounds: PlayerFovBounds = resolvePlayerFovBounds(), storage: Pick<Storage, "getItem"> | null | undefined = defaultStorage()): number
226
- - lockOnPose (function): function lockOnPose(player: Vec3, target: Vec3, config: LockOnCameraConfig | undefined, fov: number): { pose: CameraPose; yaw: number } — Lock-on pose: camera sits behind the player along the player→target vector so the target stays framed. The look point is biased between player and target by `framingBias`.
227
- - observerPose (function): function observerPose(subject: Vec3, angle: number, resolved: ResolvedObserver, fov: number): CameraPose — Detached spectator pose: orbits `subject` at a fixed distance/height, never reading player input.
228
- - orbitFollowStep (function): function orbitFollowStep(input: { state: OrbitFollowRuntimeState; desiredTarget: Vec3; deltaSeconds: number; config: ResolvedOrbitCameraConfig; dragging: boolean; }): OrbitFollowRuntimeState & { distance: number } — Pure orbit follow step — smooth target tracking, camera carries target delta (OrbitControls alone keeps camera fixed when only target moves), optional distance lock. Call each frame before OrbitControls.update() in the shell.
229
- - orbitYawFromCamera (function): function orbitYawFromCamera(cameraX: number, cameraZ: number, targetX: number, targetZ: number): number — Horizontal facing derived from an orbit camera orbiting a target on the XZ plane.
230
- - resolveChase (function): function resolveChase(config: ChaseCameraConfig | undefined): ResolvedChase
231
- - resolveDirectedCamera (function): function resolveDirectedCamera(director: DirectorCameraValues | undefined, staticConfig: StaticCameraValues): ResolvedDirectedCamera — Merges a `CameraDirector` runtime snapshot over the static `GameCameraConfig` (#196.2). `director` omitted, or its fields `undefined`/`null`, is a pure passthrough to `staticConfig` so mounting a director with no active override changes nothing.
232
- - resolveFollowTargetFromPosition (function): function resolveFollowTargetFromPosition(position: readonly [number, number, number], config: Pick<ResolvedOrbitCameraConfig, "targetHeight" | "targetOffset">): Vec3
233
- - resolveInspectionCameraConfig (function): function resolveInspectionCameraConfig(config?: InspectionCameraConfig): ResolvedInspectionCameraConfig
234
- - resolveInspectionZoomToCursor (function): function resolveInspectionZoomToCursor(anchor: InspectionZoomAnchor): boolean — Maps the anchor mode onto three-stdlib OrbitControls' native `zoomToCursor` flag.
235
- - resolveObserver (function): function resolveObserver(config: ObserverCameraConfig | undefined): ResolvedObserver
236
- - resolveOrbitCameraConfig (function): function resolveOrbitCameraConfig(patch?: OrbitCameraConfig): ResolvedOrbitCameraConfig
237
- - resolvePlayerFovBounds (function): function resolvePlayerFovBounds(options?: { min?: number; max?: number; default?: number; }): PlayerFovBounds
238
- - resolveRigKind (function): function resolveRigKind(config: GameCameraConfig | undefined): CameraRigKind — Resolves which rig mounts from a `GameCameraConfig`. Precedence, most to least specific: an explicit `rig` field always wins; then `perspective: "first"` (the historical shorthand for `rig: "orbit" | "first"`); then the mere presence of a rig's own config block selects that rig, checked in the fixed order below (#207.8) so a config carrying more than one block resolves deterministically instead of depending on object key order. Set `rig` explicitly to break a tie.
239
- - resolveShoulder (function): function resolveShoulder(config: ShoulderCameraConfig | undefined, aiming: boolean): ResolvedShoulder
240
- - resolveSideScroll (function): function resolveSideScroll(config: SideScrollCameraConfig | undefined): ResolvedSideScroll
241
- - resolveSideScrollPose (function): function resolveSideScrollPose(entityPos: Vec3, resolved: ResolvedSideScroll, fov: number): CameraPose — Fixed lateral 2.5D follow pose: the camera sits perpendicular to the travel axis at `distance`, above the entity by `height`, and looks at the entity raised by `lookHeight`. Axis "x" watches from +z; axis "z" watches from +x.
242
- - resolveTargetSmoothing (function): function resolveTargetSmoothing(config: ResolvedOrbitCameraConfig, dragging: boolean): number
243
- - resolveTopDown (function): function resolveTopDown(config: TopDownCameraConfig | undefined): ResolvedTopDown
244
- - rightVector (function): function rightVector(yaw: number): Vec3 — Screen-right of a yaw: `forward × up` with up = +Y.
245
- - rtsPanKeysConflict (function): function rtsPanKeysConflict(input: ActionCodesMap | undefined): boolean
246
- - savePlayerFov (function): function savePlayerFov(value: number, bounds: PlayerFovBounds = resolvePlayerFovBounds(), storage: Pick<Storage, "setItem"> | null | undefined = defaultStorage()): number
247
- - seatPose (function): function seatPose(follow: Vec3, yaw: number, local: { x?: number; y?: number; z?: number }, fov: number): CameraPose — World-space seat pose (cockpit/hood/rear) rigidly attached to the vehicle.
248
- - seedInspectionCamera (function): function seedInspectionCamera(config: ResolvedInspectionCameraConfig): { camera: Vec3; target: Vec3 } — Seeds the camera/target world position before OrbitControls mounts. Falls back to `initialDistance` behind `target` on the -Z axis, raised by 40% of that distance, when `initialPosition` is unset.
249
- - seedOrbitFollowState (function): function seedOrbitFollowState(input: { entityPosition: readonly [number, number, number]; config: Pick<ResolvedOrbitCameraConfig, "targetHeight" | "targetOffset" | "initialDistance" | "initialHeight">; }): OrbitFollowRuntimeState
250
- - shakeOffset (function): function shakeOffset(state: TraumaState, config: { maxOffset?: number; maxRoll?: number; exponent?: number; frequency?: number; } | undefined): ShakeOffset — Positional + roll shake for the current trauma. Shake magnitude is `trauma^exponent` so small hits stay subtle; the oscillation is deterministic per-seed pseudo-noise (no per-frame RNG, so identical inputs reproduce).
251
- - shoulderPose (function): function shoulderPose(follow: Vec3, yaw: number, pitch: number, sideSign: number, shoulder: ResolvedShoulder): CameraPose — Over-the-shoulder camera pose. The boom sits behind the follow point along `yaw`, raised by `heightOffset`, and pushed sideways by `shoulderOffset` (sign set by `sideSign`: +1 right, -1 left). `pitch` tilts the look point.
252
- - sideScrollFollowBlend (function): function sideScrollFollowBlend(followSmoothing: number, dt: number): number — Frame-rate independent follow blend for the side-scroll rig; `followSmoothing <= 0` hard-locks (blend 1) instead of freezing.
253
- - smoothBlend (function): function smoothBlend(deltaSeconds: number, speed: number): number — Frame-rate independent exponential smoothing factor in [0, 1].
254
- - smoothYaw (function): function smoothYaw(current: number, desired: number, speed: number, dt: number): number — Exponential yaw smoothing that respects wrap-around.
255
- - smoothstep (function): function smoothstep(t: number): number
256
- - speedToFov (function): function speedToFov(speed: number, curve: { base?: number; max?: number; speedForMax?: number } | undefined): number — Speed→FOV curve: FOV climbs from base to max as speed rises to `speedForMax`.
257
- - springArmStep (function): function springArmStep(current: Vec3, desired: Vec3, damping: number, dt: number): Vec3 — Exponential spring-arm approach toward a desired point (frame-rate independent).
258
- - stepTrauma (function): function stepTrauma(state: TraumaState, decayPerSecond: number, dt: number): void — Decay trauma linearly toward 0 and advance the shake clock.
259
- - topDownPose (function): function topDownPose(follow: Vec3, resolved: ResolvedTopDown, fov: number): CameraPose — Camera pose for a fixed top-down / isometric rig. `pitch` is the elevation of the camera→target ray above the ground (PI/2 = straight down); `yaw` is the fixed azimuth (PI/4 reads isometric). Height sets zoom; horizontal boom is derived so the look angle stays constant as height changes.
260
- - useCameraShake (function): function useCameraShake(): CameraShakeChannel — The active rig's shake channel — call `.shake(...)` to add trauma from React UI.
261
- - usePlayerFov (function): function usePlayerFov(): PlayerFovState
262
- - yawTo (function): function yawTo(from: Vec3, to: Vec3): number — Yaw that points from `from` toward `to` on the XZ plane (matches shell forward = (sin, cos)).
263
-
264
- ### @jgengine/shell/camera/inspectionCameraMath
265
-
266
- - ResolvedInspectionCameraConfig (interface): interface ResolvedInspectionCameraConfig
267
- - resolveInspectionCameraConfig (function): function resolveInspectionCameraConfig(config?: InspectionCameraConfig): ResolvedInspectionCameraConfig
268
- - resolveInspectionZoomToCursor (function): function resolveInspectionZoomToCursor(anchor: InspectionZoomAnchor): boolean — Maps the anchor mode onto three-stdlib OrbitControls' native `zoomToCursor` flag.
269
- - seedInspectionCamera (function): function seedInspectionCamera(config: ResolvedInspectionCameraConfig): { camera: Vec3; target: Vec3 } — Seeds the camera/target world position before OrbitControls mounts. Falls back to `initialDistance` behind `target` on the -Z axis, raised by 40% of that distance, when `initialPosition` is unset.
270
-
271
- ### @jgengine/shell/camera/orbitCameraMath
272
-
273
- - CameraFollowState (interface): interface CameraFollowState
274
- - DEFAULT_ORBIT_CAMERA (const): const DEFAULT_ORBIT_CAMERA: ResolvedOrbitCameraConfig
275
- - GAME_SIM_FRAME_PRIORITY (const): const GAME_SIM_FRAME_PRIORITY: 0 — Run simulation/movement before orbit follow so poses are current.
276
- - ORBIT_CAMERA_FRAME_PRIORITY (const): const ORBIT_CAMERA_FRAME_PRIORITY: -1 — Orbit follow reads the latest entity pose after GAME_SIM_FRAME_PRIORITY.
277
- - OrbitCameraConfig (interface): interface OrbitCameraConfig
278
- - OrbitCollisionConfig (interface): interface OrbitCollisionConfig — Spring-arm occlusion config for the orbit rig.
279
- - OrbitFollowRuntimeState (interface): interface OrbitFollowRuntimeState
280
- - ResolvedOrbitCameraConfig (interface): interface ResolvedOrbitCameraConfig — Fully resolved shell config after merging with DEFAULT_ORBIT_CAMERA.
281
- - ResolvedOrbitCollision (interface): interface ResolvedOrbitCollision — An {@link OrbitCollisionConfig} with every field resolved to a concrete value.
282
- - Vec3 (interface): interface Vec3
283
- - cameraFollowStep (function): function cameraFollowStep(input: { camera: Vec3; target: Vec3; previousTarget: Vec3 | null; lockedDistance: number | null; }): CameraFollowState
284
- - cameraLookPitch (function): function cameraLookPitch(camera: Vec3, target: Vec3): number — Elevation the camera looks along (radians): negative = aiming down, positive = aiming up, 0 = level. Feeds aim.pitch so vertical aim tracks the camera.
285
- - distanceBetween (function): function distanceBetween(a: Vec3, b: Vec3): number
286
- - lerpVec3 (function): function lerpVec3(from: Vec3, to: Vec3, blend: number): Vec3
287
- - orbitFollowStep (function): function orbitFollowStep(input: { state: OrbitFollowRuntimeState; desiredTarget: Vec3; deltaSeconds: number; config: ResolvedOrbitCameraConfig; dragging: boolean; }): OrbitFollowRuntimeState & { distance: number } — Pure orbit follow step — smooth target tracking, camera carries target delta (OrbitControls alone keeps camera fixed when only target moves), optional distance lock. Call each frame before OrbitControls.update() in the shell.
288
- - orbitYawFromCamera (function): function orbitYawFromCamera(cameraX: number, cameraZ: number, targetX: number, targetZ: number): number — Horizontal facing derived from an orbit camera orbiting a target on the XZ plane.
289
- - resolveFollowTargetFromPosition (function): function resolveFollowTargetFromPosition(position: readonly [number, number, number], config: Pick<ResolvedOrbitCameraConfig, "targetHeight" | "targetOffset">): Vec3
290
- - resolveOrbitCameraConfig (function): function resolveOrbitCameraConfig(patch?: OrbitCameraConfig): ResolvedOrbitCameraConfig
291
- - resolveTargetSmoothing (function): function resolveTargetSmoothing(config: ResolvedOrbitCameraConfig, dragging: boolean): number
292
- - seedOrbitFollowState (function): function seedOrbitFollowState(input: { entityPosition: readonly [number, number, number]; config: Pick<ResolvedOrbitCameraConfig, "targetHeight" | "targetOffset" | "initialDistance" | "initialHeight">; }): OrbitFollowRuntimeState
293
- - smoothBlend (function): function smoothBlend(deltaSeconds: number, speed: number): number — Frame-rate independent exponential smoothing factor in [0, 1].
294
-
295
- ### @jgengine/shell/camera/rigMath
296
-
297
- - CameraPose (interface): interface CameraPose
298
- - CinematicSample (interface): interface CinematicSample
299
- - DirectorCameraValues (interface): interface DirectorCameraValues
300
- - ResolvedChase (interface): interface ResolvedChase
301
- - ResolvedDirectedCamera (interface): interface ResolvedDirectedCamera
302
- - ResolvedObserver (interface): interface ResolvedObserver
303
- - ResolvedShoulder (interface): interface ResolvedShoulder
304
- - ResolvedSideScroll (interface): interface ResolvedSideScroll
305
- - ResolvedTopDown (interface): interface ResolvedTopDown
306
- - ShakeOffset (interface): interface ShakeOffset
307
- - StaticCameraValues (interface): interface StaticCameraValues
308
- - TraumaState (interface): interface TraumaState
309
- - addTrauma (function): function addTrauma(state: TraumaState, amount: number): void — Add trauma (0..1) and clamp; larger hits raise the ceiling toward 1.
310
- - angleDelta (function): function angleDelta(a: number, b: number): number — Shortest signed angular delta from `a` to `b`, wrapped to (-PI, PI].
311
- - bankRollStep (function): function bankRollStep(currentRoll: number, yaw: number, previousYaw: number, dt: number, resolved: ResolvedChase): number — One smoothing step of the chase rig's turn-bank roll (#286.10): roll opposes yaw rate, clamped and exponentially damped.
312
- - blendShoulder (function): function blendShoulder(hip: ResolvedShoulder, ads: ResolvedShoulder, t: number): ResolvedShoulder — Blend two shoulder framings by an ADS factor in [0,1].
313
- - chaseDesiredPosition (function): function chaseDesiredPosition(follow: Vec3, yaw: number, resolved: ResolvedChase): Vec3 — Desired chase-camera position behind a vehicle facing `yaw` (before spring smoothing).
314
- - chaseLookAt (function): function chaseLookAt(follow: Vec3, yaw: number, resolved: ResolvedChase): Vec3 — Look point ahead of / above a chased vehicle.
315
- - cinematicSample (function): function cinematicSample(keyframes: readonly CameraKeyframe[], elapsed: number, loop: boolean, fallbackFov: number): CinematicSample — Sample a keyframe path at `elapsed` seconds. Each keyframe's `duration` is the travel time from the previous keyframe into it; segment easing is per the destination keyframe. Reports `done` once past the final keyframe (unless looping, which wraps `elapsed` into the total path duration).
316
- - clamp (function): function clamp(value: number, min: number, max: number): number
317
- - createTrauma (function): function createTrauma(): TraumaState
318
- - crossfadePose (function): function crossfadePose(from: CameraPose, to: CameraPose, t: number): CameraPose — Linear cross-fade between two full camera poses (position, lookAt, fov).
319
- - forwardVector (function): function forwardVector(yaw: number): Vec3
320
- - leadFollowPoint (function): function leadFollowPoint(follow: Vec3, previous: Vec3, dt: number, resolved: ResolvedChase): Vec3 — Velocity-lead the follow point (#286.9): aim `leadTime` seconds along the target's frame velocity, clamped to `leadMax`.
321
- - lerp (function): function lerp(from: number, to: number, blend: number): number
322
- - lockOnPose (function): function lockOnPose(player: Vec3, target: Vec3, config: LockOnCameraConfig | undefined, fov: number): { pose: CameraPose; yaw: number } — Lock-on pose: camera sits behind the player along the player→target vector so the target stays framed. The look point is biased between player and target by `framingBias`.
323
- - observerPose (function): function observerPose(subject: Vec3, angle: number, resolved: ResolvedObserver, fov: number): CameraPose — Detached spectator pose: orbits `subject` at a fixed distance/height, never reading player input.
324
- - resolveChase (function): function resolveChase(config: ChaseCameraConfig | undefined): ResolvedChase
325
- - resolveDirectedCamera (function): function resolveDirectedCamera(director: DirectorCameraValues | undefined, staticConfig: StaticCameraValues): ResolvedDirectedCamera — Merges a `CameraDirector` runtime snapshot over the static `GameCameraConfig` (#196.2). `director` omitted, or its fields `undefined`/`null`, is a pure passthrough to `staticConfig` so mounting a director with no active override changes nothing.
326
- - resolveObserver (function): function resolveObserver(config: ObserverCameraConfig | undefined): ResolvedObserver
327
- - resolveShoulder (function): function resolveShoulder(config: ShoulderCameraConfig | undefined, aiming: boolean): ResolvedShoulder
328
- - resolveSideScroll (function): function resolveSideScroll(config: SideScrollCameraConfig | undefined): ResolvedSideScroll
329
- - resolveSideScrollPose (function): function resolveSideScrollPose(entityPos: Vec3, resolved: ResolvedSideScroll, fov: number): CameraPose — Fixed lateral 2.5D follow pose: the camera sits perpendicular to the travel axis at `distance`, above the entity by `height`, and looks at the entity raised by `lookHeight`. Axis "x" watches from +z; axis "z" watches from +x.
330
- - resolveTopDown (function): function resolveTopDown(config: TopDownCameraConfig | undefined): ResolvedTopDown
331
- - rightVector (function): function rightVector(yaw: number): Vec3 — Screen-right of a yaw: `forward × up` with up = +Y.
332
- - rtsPanKeysConflict (function): function rtsPanKeysConflict(input: ActionCodesMap | undefined): boolean
333
- - seatPose (function): function seatPose(follow: Vec3, yaw: number, local: { x?: number; y?: number; z?: number }, fov: number): CameraPose — World-space seat pose (cockpit/hood/rear) rigidly attached to the vehicle.
334
- - shakeOffset (function): function shakeOffset(state: TraumaState, config: { maxOffset?: number; maxRoll?: number; exponent?: number; frequency?: number; } | undefined): ShakeOffset — Positional + roll shake for the current trauma. Shake magnitude is `trauma^exponent` so small hits stay subtle; the oscillation is deterministic per-seed pseudo-noise (no per-frame RNG, so identical inputs reproduce).
335
- - shoulderPose (function): function shoulderPose(follow: Vec3, yaw: number, pitch: number, sideSign: number, shoulder: ResolvedShoulder): CameraPose — Over-the-shoulder camera pose. The boom sits behind the follow point along `yaw`, raised by `heightOffset`, and pushed sideways by `shoulderOffset` (sign set by `sideSign`: +1 right, -1 left). `pitch` tilts the look point.
336
- - sideScrollFollowBlend (function): function sideScrollFollowBlend(followSmoothing: number, dt: number): number — Frame-rate independent follow blend for the side-scroll rig; `followSmoothing <= 0` hard-locks (blend 1) instead of freezing.
337
- - smoothYaw (function): function smoothYaw(current: number, desired: number, speed: number, dt: number): number — Exponential yaw smoothing that respects wrap-around.
338
- - smoothstep (function): function smoothstep(t: number): number
339
- - speedToFov (function): function speedToFov(speed: number, curve: { base?: number; max?: number; speedForMax?: number } | undefined): number — Speed→FOV curve: FOV climbs from base to max as speed rises to `speedForMax`.
340
- - springArmStep (function): function springArmStep(current: Vec3, desired: Vec3, damping: number, dt: number): Vec3 — Exponential spring-arm approach toward a desired point (frame-rate independent).
341
- - stepTrauma (function): function stepTrauma(state: TraumaState, decayPerSecond: number, dt: number): void — Decay trauma linearly toward 0 and advance the shake clock.
342
- - topDownPose (function): function topDownPose(follow: Vec3, resolved: ResolvedTopDown, fov: number): CameraPose — Camera pose for a fixed top-down / isometric rig. `pitch` is the elevation of the camera→target ray above the ground (PI/2 = straight down); `yaw` is the fixed azimuth (PI/4 reads isometric). Height sets zoom; horizontal boom is derived so the look angle stays constant as height changes.
343
- - yawTo (function): function yawTo(from: Vec3, to: Vec3): number — Yaw that points from `from` toward `to` on the XZ plane (matches shell forward = (sin, cos)).
344
-
345
- ### @jgengine/shell/camera/rigResolve
346
-
347
- - resolveRigKind (function): function resolveRigKind(config: GameCameraConfig | undefined): CameraRigKind — Resolves which rig mounts from a `GameCameraConfig`. Precedence, most to least specific: an explicit `rig` field always wins; then `perspective: "first"` (the historical shorthand for `rig: "orbit" | "first"`); then the mere presence of a rig's own config block selects that rig, checked in the fixed order below (#207.8) so a config carrying more than one block resolves deterministically instead of depending on object key order. Set `rig` explicitly to break a tie.
348
- - turntableAsObserver (function): function turntableAsObserver(config: GameCameraConfig | undefined): GameCameraConfig — The turntable rig is a flat facade over the observer's point-orbit mode: map its `target`/`distance`/… onto an observer block so ObserverRig runs unchanged.
349
-
350
- ### @jgengine/shell/camera/shakeChannel
351
-
352
- - CameraShakeChannel (interface): interface CameraShakeChannel
353
- - CameraShakeContext (const): const CameraShakeContext: React.Context<CameraShakeChannel>
354
- - cameraShake (function): function cameraShake(amplitude: number, decayPerSecond?: number): void — Feed the default camera-shake channel from anywhere (see G7 hitstop cross-cut).
355
- - createCameraShakeChannel (function): function createCameraShakeChannel(defaultDecayPerSecond = 1.6): CameraShakeChannel
356
- - defaultCameraShakeChannel (const): const defaultCameraShakeChannel: CameraShakeChannel — Process-wide default channel. A shell mounts its own channel via `CameraShakeContext`, but game systems that have no React context (e.g. a `loop.onTick` reacting to `entity.died`) can import `cameraShake` and feed the default channel directly.
357
- - useCameraShake (function): function useCameraShake(): CameraShakeChannel — The active rig's shake channel — call `.shake(...)` to add trauma from React UI.
358
-
359
- ### @jgengine/shell/camera/shakeChannelMath
360
-
361
- - CameraShakeChannel (interface): interface CameraShakeChannel
362
- - createCameraShakeChannel (function): function createCameraShakeChannel(defaultDecayPerSecond = 1.6): CameraShakeChannel
363
-
364
- ### @jgengine/shell/cartridge
365
-
366
- - CartridgeAbilitySlot (interface): interface CartridgeAbilitySlot
367
- - CartridgeConfig (type): type CartridgeConfig = CartridgeSpec & { name: string; panels: CartridgePanels; hud: { storageKey?: string; panels: readonly CartridgeHudPanelSpec[] }; screens: CartridgeScreens; theme?: Record<string, string>; world?: GameConfig["world"]; physics?: GameConfig["physics"]; assets?: GameConfig["assets…
368
- - CartridgeHudPanelSpec (interface): interface CartridgeHudPanelSpec
369
- - CartridgePanelItem (type): type CartridgePanelItem = | { kind: "vital"; stat: string; label: string; tone?: string; width?: number } | { kind: "xp"; width?: number } | { kind: "timer"; label: string } | { kind: "score"; source: "kills"; label: string; digits?: number } | { kind: "abilityBar"; icons: Record<string, string> } |…
370
- - CartridgePanels (interface): interface CartridgePanels
371
- - CartridgeResultLine (type): type CartridgeResultLine = { label: string; accent?: boolean } & ( | { source: "kills" | "level" } | { value: string | number } )
372
- - CartridgeScreens (interface): interface CartridgeScreens
373
- - cartridge (function): function cartridge(config: CartridgeConfig): PlayableGame
374
-
375
- ### @jgengine/shell/commandSink
376
-
377
- - CommandSink (interface): interface CommandSink — Where a gameplay command goes when the shell dispatches it — run locally, or sent to the authoritative host.
378
- - localCommandSink (function): function localCommandSink(ctx: GameContext): CommandSink — Runs commands on the local `ctx` — the default, client-authoritative path.
379
- - remoteCommandSink (function): function remoteCommandSink(backend: Pick<LiveGameBackend, "transport">, serverId: string): CommandSink — Sends commands to the authoritative host over the transport; the result replicates back through world sync.
380
- - resolveCommandSink (function): function resolveCommandSink(ctx: GameContext, opts: { serverAuthoritative: boolean; backend: Pick<LiveGameBackend, "transport"> | null; serverId: string | null; }): CommandSink — The sink a server-authoritative shell should dispatch gameplay commands through: remote when the game opts into `authority: "server"` and a server is joined, local otherwise. Client-only UI commands (targeting, hotbar scroll) keep calling `ctx.game.commands.run` directly — only authoritative gameplay verbs route to the host.
381
-
382
- ### @jgengine/shell/defineGame
383
-
384
- - GameConfig (type): type GameConfig<TAssetRef extends ModelAssetRef = ModelAssetRef> = EngineFields<TAssetRef> & PresentationFields
385
- - defineGame (function): function defineGame<TAssetRef extends ModelAssetRef = ModelAssetRef>(config: GameConfig<TAssetRef>): PlayableGame
386
-
387
- ### @jgengine/shell/devtools/CollisionDebugWorld
388
-
389
- - CollisionDebugWorld (function): function CollisionDebugWorld(): React.JSX.Element | null — World-space collision debugger. Performs zero scene scans and zero raycasts when every layer is off. Mount only when shell devtools are enabled.
390
-
391
- ### @jgengine/shell/devtools/DevtoolsOverlay
392
-
393
- - DevtoolsOverlay (function): function DevtoolsOverlay({ open, ctx, playable, multiplayer, }: { open: boolean; ctx: GameContext; playable: PlayableGame; multiplayer: ShellMultiplayer | null; }): React.JSX.Element | null
394
- - DevtoolsRendererProbe (function): function DevtoolsRendererProbe(): null
395
- - applyStoredDevtoolsOverrides (function): function applyStoredDevtoolsOverrides(gameName: string): void
396
- - buildFullReport (function): function buildFullReport(playable: PlayableGame): DevtoolsSnapshot & { game: string }
397
- - buildLeanReport (function): function buildLeanReport(playable: PlayableGame): { game: any; at: any; why: string | null; frame: { fps: number; avgFrameMs: number; p95FrameMs: number; maxFrameMs: number; avgSimMs: number; maxSimMs: number; avgOutsideMs: number; maxOutsideMs: number; longFrames: any; samples: any; phases: any; } …
398
- - persistDevtoolsOverrides (function): function persistDevtoolsOverrides(gameName: string): DevtoolsOverrides
399
- - withDevtoolsLatency (function): function withDevtoolsLatency(multiplayer: ShellMultiplayer): ShellMultiplayer
400
-
401
- ### @jgengine/shell/devtools/collisionDebug
402
-
403
- - AimProbeConfig (interface): interface AimProbeConfig
404
- - COLLISION_DEBUG_LAYERS (const): const COLLISION_DEBUG_LAYERS: readonly CollisionDebugLayer[]
405
- - CollisionDebugController (interface): interface CollisionDebugController
406
- - CollisionDebugLayer (type): type CollisionDebugLayer = | "hitboxes" | "bodies" | "projectiles" | "muzzles" | "aimLaser"
407
- - CollisionDebugLayers (type): type CollisionDebugLayers = Record<CollisionDebugLayer, boolean>
408
- - CollisionDebugListener (type): type CollisionDebugListener = () => void
409
- - CollisionDebugState (interface): interface CollisionDebugState
410
- - ProjectileDebugTrace (interface): interface ProjectileDebugTrace
411
- - aimProbeNeeded (function): function aimProbeNeeded(layers: CollisionDebugLayers): boolean
412
- - anyCollisionLayerOn (function): function anyCollisionLayerOn(layers: CollisionDebugLayers): boolean
413
- - colliderScanNeeded (function): function colliderScanNeeded(layers: CollisionDebugLayers): boolean
414
- - collisionDebug (const): const collisionDebug: CollisionDebugController
415
- - createCollisionDebugController (function): function createCollisionDebugController(initial: CollisionDebugState = createDefaultCollisionDebugState()): CollisionDebugController
416
- - createDefaultCollisionDebugState (function): function createDefaultCollisionDebugState(): CollisionDebugState
417
- - projectileListenNeeded (function): function projectileListenNeeded(layers: CollisionDebugLayers): boolean
418
-
419
- ### @jgengine/shell/devtools/collisionDebugMath
420
-
421
- - AIM_DAMAGE_COLOR (const): const AIM_DAMAGE_COLOR: "#f87171"
422
- - AIM_LASER_COLOR (const): const AIM_LASER_COLOR: "#a3e635"
423
- - AIM_MISS_COLOR (const): const AIM_MISS_COLOR: "#94a3b8"
424
- - AIM_SOLID_COLOR (const): const AIM_SOLID_COLOR: "#fbbf24"
425
- - AimEndpointKind (type): type AimEndpointKind = "damage" | "solid" | "miss"
426
- - AimLaserDebug (interface): interface AimLaserDebug
427
- - BODY_WIRE_COLOR (const): const BODY_WIRE_COLOR: "#38bdf8"
428
- - CollectDebugShapesInput (interface): interface CollectDebugShapesInput
429
- - ComputeAimLaserInput (interface): interface ComputeAimLaserInput
430
- - DebugShapeEntry (interface): interface DebugShapeEntry
431
- - HITBOX_WIRE_COLOR (const): const HITBOX_WIRE_COLOR: "#f472b6"
432
- - PROJECTILE_PATH_COLOR (const): const PROJECTILE_PATH_COLOR: "#fde68a"
433
- - classifyAimEndpoint (function): function classifyAimEndpoint(hit: Pick<SceneRaycastHit, "damageEligible"> | null | undefined): AimEndpointKind
434
- - collectDebugShapes (function): function collectDebugShapes(input: CollectDebugShapesInput): DebugShapeEntry[] — Collects world-space collider wireframe entries for enabled layers. Returns [] and performs no entity/object iteration when both hitbox/body layers are off.
435
- - computeAimLaser (function): function computeAimLaser(input: ComputeAimLaserInput): AimLaserDebug | null — Builds the authoritative aim-laser segment using resolveShot + scene raycast (same seam as projectile prediction/settlement). Zero queries when aimLaser is off.
436
- - muzzleMarkerFromOrigin (function): function muzzleMarkerFromOrigin(origin: EntityPosition): { center: EntityPosition; radius: number; color: string; }
437
- - pointAlongRay (function): function pointAlongRay(origin: EntityPosition, direction: EntityPosition, distance: number): EntityPosition
438
- - shapeWorldCenter (function): function shapeWorldCenter(collider: ResolvedCollider, position: EntityPosition, rotationY: number): EntityPosition
439
-
440
- ### @jgengine/shell/environment
441
-
442
- - Daylight (function): function Daylight({ sky, fog, sun, ambient, lights = true }: DaylightProps = {}): React.JSX.Element
443
- - DaylightCycleConfig (interface): interface DaylightCycleConfig
444
- - DaylightProps (interface): interface DaylightProps
445
- - DaylightState (interface): interface DaylightState
446
- - EnvironmentScene (function): function EnvironmentScene({ feature }: EnvironmentSceneProps): React.JSX.Element
447
- - EnvironmentSceneProps (interface): interface EnvironmentSceneProps
448
- - SKY_PRESET_DAY_FRACTION (const): const SKY_PRESET_DAY_FRACTION: Record<"day" | "dusk" | "night", number>
449
- - SkyDaylight (function): function SkyDaylight({ sky, lights = true }: SkyDaylightProps): React.JSX.Element — Renders a fixed sky/sun/fog look sampled from `sky`'s preset (or, when `timeOfDay` is on but no clock drives it, its noon look). No per-frame updates.
450
- - SkyDaylightProps (interface): interface SkyDaylightProps
451
- - SkyDome (function): function SkyDome({ topColor = SKY_TOP, horizonColor = SKY_HORIZON, radius = 260, offset = 24, exponent = 0.65, sunDirection, sunColor = "#fff4d6", sunIntensity = 1, materialRef, }: SkyDomeProps = {}): React.JSX.Element
452
- - SkyDomeProps (interface): interface SkyDomeProps
453
- - SkyLightOwnership (type): type SkyLightOwnership = "authored" | "sky-default" — Policy for composing sky backdrops with `PlayableGame.lighting`: - authored lighting present → sky renders dome + fog only; lights stay game-owned - no authored lighting → sky may emit its default sun/hemisphere with the dome Time-of-day never rewrites configured lights; it only drives sky colors/fog (and sky-owned lights when the game did not author lighting).
454
- - TimeOfDayDaylight (function): function TimeOfDayDaylight({ sky, clock, lights = true }: TimeOfDayDaylightProps): React.JSX.Element — Drives sky/fog (and optional default lights) from the world clock when `sky.timeOfDay` and `clock` are both present. Authored `PlayableGame.lighting` is never rewritten — pass `lights={false}` so only dome colors and fog track the day fraction.
455
- - TimeOfDayDaylightProps (interface): interface TimeOfDayDaylightProps
456
- - daylightStateAt (function): function daylightStateAt(dayFraction: number, config: DaylightCycleConfig = {}): DaylightState — Samples the daylight cycle at a point in the day (0 = midnight, 0.25 = dawn, 0.5 = noon, 0.75 = dusk), lerping sun position/intensity, ambient intensity, and sky colors through a dawn/day/dusk/night keyframe table. `config` overrides the noon (peak-day) colors and intensities only.
457
- - lerpHexColor (function): function lerpHexColor(a: string, b: string, t: number): string
458
- - resolveSkyLightOwnership (function): function resolveSkyLightOwnership(hasAuthoredLighting: boolean): SkyLightOwnership
459
- - skyEmitsLights (function): function skyEmitsLights(ownership: SkyLightOwnership): boolean
460
-
461
- ### @jgengine/shell/environment/Daylight
462
-
463
- - Daylight (function): function Daylight({ sky, fog, sun, ambient, lights = true }: DaylightProps = {}): React.JSX.Element
464
- - DaylightProps (interface): interface DaylightProps
465
- - SkyDaylight (function): function SkyDaylight({ sky, lights = true }: SkyDaylightProps): React.JSX.Element — Renders a fixed sky/sun/fog look sampled from `sky`'s preset (or, when `timeOfDay` is on but no clock drives it, its noon look). No per-frame updates.
466
- - SkyDaylightProps (interface): interface SkyDaylightProps
467
- - SkyDome (function): function SkyDome({ topColor = SKY_TOP, horizonColor = SKY_HORIZON, radius = 260, offset = 24, exponent = 0.65, sunDirection, sunColor = "#fff4d6", sunIntensity = 1, materialRef, }: SkyDomeProps = {}): React.JSX.Element
468
- - SkyDomeProps (interface): interface SkyDomeProps
469
- - TimeOfDayDaylight (function): function TimeOfDayDaylight({ sky, clock, lights = true }: TimeOfDayDaylightProps): React.JSX.Element — Drives sky/fog (and optional default lights) from the world clock when `sky.timeOfDay` and `clock` are both present. Authored `PlayableGame.lighting` is never rewritten — pass `lights={false}` so only dome colors and fog track the day fraction.
470
- - TimeOfDayDaylightProps (interface): interface TimeOfDayDaylightProps
471
-
472
- ### @jgengine/shell/environment/EnvironmentScene
473
-
474
- - EnvironmentScene (function): function EnvironmentScene({ feature }: EnvironmentSceneProps): React.JSX.Element
475
- - EnvironmentSceneProps (interface): interface EnvironmentSceneProps
476
-
477
- ### @jgengine/shell/environment/GroundPad
478
-
479
- - GroundPad (function): function GroundPad({ pad, field }: GroundPadProps): React.JSX.Element
480
- - GroundPadProps (interface): interface GroundPadProps
481
-
482
- ### @jgengine/shell/environment/RoadRibbons
483
-
484
- - RoadRibbons (function): function RoadRibbons({ road, field }: { road: RoadEnvironmentDescriptor; field: TerrainField }): React.JSX.Element | null — Renders one `road()` descriptor: an asphalt ribbon plus optional dashed centerline, draped on the terrain.
485
-
486
- ### @jgengine/shell/environment/daylightCycle
487
-
488
- - DEFAULT_DAY_AMBIENT_INTENSITY (const): const DEFAULT_DAY_AMBIENT_INTENSITY: 0.6
489
- - DEFAULT_DAY_SKY_BOTTOM (const): const DEFAULT_DAY_SKY_BOTTOM: "#e3f4ff"
490
- - DEFAULT_DAY_SKY_TOP (const): const DEFAULT_DAY_SKY_TOP: "#3fa4f2"
491
- - DEFAULT_DAY_SUN_INTENSITY (const): const DEFAULT_DAY_SUN_INTENSITY: 1
492
- - DaylightCycleConfig (interface): interface DaylightCycleConfig
493
- - DaylightState (interface): interface DaylightState
494
- - SKY_PRESET_DAY_FRACTION (const): const SKY_PRESET_DAY_FRACTION: Record<"day" | "dusk" | "night", number>
495
- - daylightStateAt (function): function daylightStateAt(dayFraction: number, config: DaylightCycleConfig = {}): DaylightState — Samples the daylight cycle at a point in the day (0 = midnight, 0.25 = dawn, 0.5 = noon, 0.75 = dusk), lerping sun position/intensity, ambient intensity, and sky colors through a dawn/day/dusk/night keyframe table. `config` overrides the noon (peak-day) colors and intensities only.
496
- - lerpHexColor (function): function lerpHexColor(a: string, b: string, t: number): string
497
-
498
- ### @jgengine/shell/environment/groundPadMath
499
-
500
- - PAD_THICKNESS (const): const PAD_THICKNESS: 0.1
501
- - PadShape (type): type PadShape = { circular: true; radius: number } | { circular: false; width: number; depth: number }
502
- - resolvePadMeshY (function): function resolvePadMeshY(groundHeight: number, pad: Pick<PadEnvironmentDescriptor, "height" | "elevation">): number
503
- - resolvePadShape (function): function resolvePadShape(size: PadSize): PadShape
504
- - resolvePadSurfaceY (function): function resolvePadSurfaceY(groundHeight: number, pad: Pick<PadEnvironmentDescriptor, "height" | "elevation">): number
505
-
506
- ### @jgengine/shell/environment/index
507
-
508
- - Daylight (function): function Daylight({ sky, fog, sun, ambient, lights = true }: DaylightProps = {}): React.JSX.Element
509
- - DaylightCycleConfig (interface): interface DaylightCycleConfig
510
- - DaylightProps (interface): interface DaylightProps
511
- - DaylightState (interface): interface DaylightState
512
- - EnvironmentScene (function): function EnvironmentScene({ feature }: EnvironmentSceneProps): React.JSX.Element
513
- - EnvironmentSceneProps (interface): interface EnvironmentSceneProps
514
- - SKY_PRESET_DAY_FRACTION (const): const SKY_PRESET_DAY_FRACTION: Record<"day" | "dusk" | "night", number>
515
- - SkyDaylight (function): function SkyDaylight({ sky, lights = true }: SkyDaylightProps): React.JSX.Element — Renders a fixed sky/sun/fog look sampled from `sky`'s preset (or, when `timeOfDay` is on but no clock drives it, its noon look). No per-frame updates.
516
- - SkyDaylightProps (interface): interface SkyDaylightProps
517
- - SkyDome (function): function SkyDome({ topColor = SKY_TOP, horizonColor = SKY_HORIZON, radius = 260, offset = 24, exponent = 0.65, sunDirection, sunColor = "#fff4d6", sunIntensity = 1, materialRef, }: SkyDomeProps = {}): React.JSX.Element
518
- - SkyDomeProps (interface): interface SkyDomeProps
519
- - SkyLightOwnership (type): type SkyLightOwnership = "authored" | "sky-default" — Policy for composing sky backdrops with `PlayableGame.lighting`: - authored lighting present → sky renders dome + fog only; lights stay game-owned - no authored lighting → sky may emit its default sun/hemisphere with the dome Time-of-day never rewrites configured lights; it only drives sky colors/fog (and sky-owned lights when the game did not author lighting).
520
- - TimeOfDayDaylight (function): function TimeOfDayDaylight({ sky, clock, lights = true }: TimeOfDayDaylightProps): React.JSX.Element — Drives sky/fog (and optional default lights) from the world clock when `sky.timeOfDay` and `clock` are both present. Authored `PlayableGame.lighting` is never rewritten — pass `lights={false}` so only dome colors and fog track the day fraction.
521
- - TimeOfDayDaylightProps (interface): interface TimeOfDayDaylightProps
522
- - daylightStateAt (function): function daylightStateAt(dayFraction: number, config: DaylightCycleConfig = {}): DaylightState — Samples the daylight cycle at a point in the day (0 = midnight, 0.25 = dawn, 0.5 = noon, 0.75 = dusk), lerping sun position/intensity, ambient intensity, and sky colors through a dawn/day/dusk/night keyframe table. `config` overrides the noon (peak-day) colors and intensities only.
523
- - lerpHexColor (function): function lerpHexColor(a: string, b: string, t: number): string
524
- - resolveSkyLightOwnership (function): function resolveSkyLightOwnership(hasAuthoredLighting: boolean): SkyLightOwnership
525
- - skyEmitsLights (function): function skyEmitsLights(ownership: SkyLightOwnership): boolean
526
-
527
- ### @jgengine/shell/environment/skyLightingPolicy
528
-
529
- - SkyLightOwnership (type): type SkyLightOwnership = "authored" | "sky-default" — Policy for composing sky backdrops with `PlayableGame.lighting`: - authored lighting present → sky renders dome + fog only; lights stay game-owned - no authored lighting → sky may emit its default sun/hemisphere with the dome Time-of-day never rewrites configured lights; it only drives sky colors/fog (and sky-owned lights when the game did not author lighting).
530
- - resolveSkyLightOwnership (function): function resolveSkyLightOwnership(hasAuthoredLighting: boolean): SkyLightOwnership
531
- - skyEmitsLights (function): function skyEmitsLights(ownership: SkyLightOwnership): boolean
532
-
533
- ### @jgengine/shell/input/mouseLook
534
-
535
- - MouseLookAim (interface): interface MouseLookAim
536
- - MouseLookOptions (interface): interface MouseLookOptions
537
- - MouseLookTracker (interface): interface MouseLookTracker — The analog mouse-look service chase/orbit-cam games hand-rolled (#282.8) — pointer-lock lifecycle plus delta accumulation into a yaw/pitch aim, decoupled from the first-person rig. Attach it to the canvas, read `aim()` from `onTick`/`useFrame`, dispose on unmount.
538
- - createMouseLookTracker (function): function createMouseLookTracker(element: HTMLElement, options: MouseLookOptions = {}): MouseLookTracker
539
-
540
- ### @jgengine/shell/inputSink
541
-
542
- - InputSink (interface): interface InputSink — Where the local player's per-frame input goes: discarded in single-player, sent to the authoritative host under `authority: "server"`.
543
- - inputFramesEqual (function): function inputFramesEqual(a: InputFrame, b: InputFrame): boolean — Whether two input frames carry identical intent — the shell skips resending unchanged frames so a still player floods the host with nothing.
544
- - noopInputSink (function): function noopInputSink(): InputSink — Discards input — the single-player / client-authoritative default, where the client integrates movement itself.
545
- - remoteInputSink (function): function remoteInputSink(backend: Pick<LiveGameBackend, "transport">, serverId: string): InputSink — Sends each frame's input to the authoritative host over the transport, reusing the `runCommand` path via {@link INPUT_COMMAND}.
546
- - resolveInputSink (function): function resolveInputSink(opts: { serverAuthoritative: boolean; backend: Pick<LiveGameBackend, "transport"> | null; serverId: string | null; }): InputSink — The sink a server-authoritative shell sends its per-frame input through: remote when `authority: "server"` and a server is joined, a no-op otherwise.
547
-
548
- ### @jgengine/shell/map/MapMarkerBeacons
549
-
550
- - MapMarkerBeacons (function): function MapMarkerBeacons({ markers, kindStyles, height = 5 }: MapMarkerBeaconsProps): React.JSX.Element — World-space beacons for map markers (the visible in-world side of a ping): a floating diamond over a soft light beam, colored by marker kind. Wire it through `PlayableGame.WorldOverlay`.
551
- - MapMarkerBeaconsProps (interface): interface MapMarkerBeaconsProps
552
-
553
- ### @jgengine/shell/map/index
554
-
555
- - BakeTerrainMapOptions (interface): interface BakeTerrainMapOptions
556
- - BakedMap (interface): interface BakedMap
557
- - MapBakeBounds (interface): interface MapBakeBounds
558
- - MapMarkerBeacons (function): function MapMarkerBeacons({ markers, kindStyles, height = 5 }: MapMarkerBeaconsProps): React.JSX.Element — World-space beacons for map markers (the visible in-world side of a ping): a floating diamond over a soft light beam, colored by marker kind. Wire it through `PlayableGame.WorldOverlay`.
559
- - MapMarkerBeaconsProps (interface): interface MapMarkerBeaconsProps
560
- - bakeTerrainMap (function): function bakeTerrainMap(field: TerrainField, bounds: MapBakeBounds, options: BakeTerrainMapOptions = {}): BakedMap | null — Bake a top-down image of a `TerrainField` (or `RegionField`) over `bounds` for the react `Minimap` / `WorldMap` background. Runs in the browser via a 2D canvas; renderer-side, so it lives in the shell.
561
-
562
- ### @jgengine/shell/map/terrainMap
563
-
564
- - BakeTerrainMapOptions (interface): interface BakeTerrainMapOptions
565
- - BakedMap (interface): interface BakedMap
566
- - MapBakeBounds (interface): interface MapBakeBounds
567
- - bakeTerrainMap (function): function bakeTerrainMap(field: TerrainField, bounds: MapBakeBounds, options: BakeTerrainMapOptions = {}): BakedMap | null — Bake a top-down image of a `TerrainField` (or `RegionField`) over `bounds` for the react `Minimap` / `WorldMap` background. Runs in the browser via a 2D canvas; renderer-side, so it lives in the shell.
568
-
569
- ### @jgengine/shell/materialOverride
570
-
571
- - MaterialOverrideOptions (interface): interface MaterialOverrideOptions
572
- - applyMaterialOverride (function): function applyMaterialOverride(root: THREE.Object3D, override: ModelMaterialOverride, options?: MaterialOverrideOptions): void
573
-
574
- ### @jgengine/shell/multiplayer
575
-
576
- - DEFAULT_FEED_ACTIONS (const): const DEFAULT_FEED_ACTIONS: string[]
577
- - ResolveShellMultiplayerArgs (type): type ResolveShellMultiplayerArgs = { game: GameDefinition; gameId: string; url?: string; userId?: string; force?: boolean; feedActions?: string[]; }
578
- - ShellMultiplayer (type): type ShellMultiplayer = MultiplayerSession
579
- - randomPlayerId (function): function randomPlayerId(): string
580
- - resolvePeerShellMultiplayer (function): function resolvePeerShellMultiplayer(args: { gameId: string; role: "host" | "join"; room?: string; userId?: string; feedActions?: string[]; }): Promise<ShellMultiplayer & { close: () => void }>
581
- - resolveShellMultiplayer (function): function resolveShellMultiplayer(args: ResolveShellMultiplayerArgs): ShellMultiplayer | null
582
-
583
- ### @jgengine/shell/pointer/PointerOverlays
584
-
585
- - ContextMenuView (function): function ContextMenuView({ menu, x, y, onPick, onClose, }: { menu: ContextMenu; x: number; y: number; onPick: (verb: ContextVerb) => void; onClose: () => void; }): React.JSX.Element
586
- - MarqueeBox (function): function MarqueeBox({ rect }: { rect: ScreenRect }): React.JSX.Element
587
-
588
- ### @jgengine/shell/pointer/PointerProbe
589
-
590
- - PointerProbe (function): function PointerProbe({ service }: { service: PointerService }): null
591
-
592
- ### @jgengine/shell/pointer/pointerService
593
-
594
- - POINTER_ENTITY_KEY (const): const POINTER_ENTITY_KEY: "jgEntityId"
595
- - POINTER_OBJECT_KEY (const): const POINTER_OBJECT_KEY: "jgObjectId"
596
- - PointerHitFilter (type): type PointerHitFilter = (object: THREE.Object3D) => boolean
597
- - PointerService (interface): interface PointerService
598
- - createPointerService (function): function createPointerService(): PointerService
599
-
600
- ### @jgengine/shell/postfx/PostProcessing
601
-
602
- - PostProcessing (function): function PostProcessing({ config }: { config: PostProcessingConfig }): null — Mounts an `EffectComposer` inside the shell Canvas and takes over rendering (priority-1 `useFrame`, which disables R3F auto-render) to run the configured post chain: RenderPass → GTAO → UnrealBloom → OutputPass → Grade. Rendered only when `PlayableGame.postProcessing` is set, so games without it draw unchanged.
603
-
604
- ### @jgengine/shell/postfx/gradeShader
605
-
606
- - createGradePass (function): function createGradePass(config: GradeConfig = {}): ShaderPass — Build the display-space colour-grade pass (lift/gain/gamma, saturation, vignette, grain). Advance `uniforms.uTime.value` each frame to animate the grain.
607
-
608
- ### @jgengine/shell/registry
609
-
610
- - GameRegistry (type): type GameRegistry = Record<string, () => Promise<PlayableGame>>
611
- - PlayableGame (type): type PlayableGame = EnginePlayableGame<ComponentType, ComponentType, RenderEntity, RenderObject>
612
- - RenderEntity (type): type RenderEntity = (entity: SceneEntity) => ReactNode
613
- - RenderObject (type): type RenderObject = (object: SceneObject) => ReactNode
614
- - resolveGameLoader (function): function resolveGameLoader(registry: GameRegistry, gameId: string, fallbackGameId?: string): (() => Promise<PlayableGame>) | undefined
615
-
616
- ### @jgengine/shell/render/modelRender
617
-
618
- - MaterialCache (interface): interface MaterialCache
619
- - PAINT_TEXTURE_SIZE (const): const PAINT_TEXTURE_SIZE: 512
620
- - PaintCanvas (interface): interface PaintCanvas
621
- - applyPaintTexture (function): function applyPaintTexture(root: THREE.Object3D, paint: PaintCanvas): void
622
- - applyPaintTextureToMaterials (function): function applyPaintTextureToMaterials(materials: readonly THREE.MeshStandardMaterial[], paint: PaintCanvas): void
623
- - cacheStandardMaterials (function): function cacheStandardMaterials(root: THREE.Object3D, into?: MaterialCache | null): MaterialCache
624
- - cloneModelScene (function): function cloneModelScene(source: THREE.Object3D, options?: { cloneMaterials?: boolean }): THREE.Object3D
625
- - createPaintCanvas (function): function createPaintCanvas(seed: THREE.MeshStandardMaterial, size = PAINT_TEXTURE_SIZE): PaintCanvas
626
- - disposeClonedMaterials (function): function disposeClonedMaterials(root: THREE.Object3D): void
627
- - drawPaintStrokes (function): function drawPaintStrokes(paint: PaintCanvas, strokes: readonly PaintStroke[]): void
628
- - standardMaterialsOf (function): function standardMaterialsOf(root: THREE.Object3D): THREE.MeshStandardMaterial[]
629
- - syncPaintCanvas (function): function syncPaintCanvas(paint: PaintCanvas, seedColor: THREE.Color, strokes: readonly PaintStroke[], drawnCount: number): number
630
-
631
- ### @jgengine/shell/render/resolveModel
632
-
633
- - ModelResolveContext (interface): interface ModelResolveContext
634
- - resolveModel (function): function resolveModel(value: string | ModelConfig | undefined, assets: AssetCatalog, context?: ModelResolveContext): ModelConfig | undefined — Resolve a string asset id or a direct ModelConfig. Missing/misspelled catalog ids throw — silent generic-primitive fallback only happens when the mapping omits the key entirely (or uses tryResolveCatalogModel for optional ids).
635
- - tryResolveCatalogModel (function): function tryResolveCatalogModel(id: string, assets: AssetCatalog): ModelConfig | undefined — Soft lookup used when an object catalog id may double as a model asset id.
636
-
637
- ### @jgengine/shell/replay/useSessionRecorder
638
-
639
- - RecordedPose (interface): interface RecordedPose
640
- - useSessionRecorder (function): function useSessionRecorder(entityId: string, options?: RecordingBufferOptions): RecordingBuffer<RecordedPose> — Session-recording buffer (#120) for replay / photo mode / kill-cam: records an entity's pose on game-time every frame into a `RecordingBuffer`, which a game can then `seek()` to scrub, drive an observer cam ghost, or export a kill-cam clip. Recording rides on `ctx.time.now()`, so pause/fast-forward scrub the recording exactly like the live sim.
641
-
642
- ### @jgengine/shell/settings/QuickControls
643
-
644
- - QuickControls (function): function QuickControls({ controller }: { controller: SettingsController }): React.JSX.Element | null
645
-
646
- ### @jgengine/shell/settings/SettingsChrome
647
-
648
- - SettingsChrome (function): function SettingsChrome(): React.JSX.Element | null
649
-
650
- ### @jgengine/shell/settings/SettingsMenu
651
-
652
- - SettingsMenu (function): function SettingsMenu({ controller, onClose, initialTab, }: { controller: SettingsController; onClose: () => void; initialTab?: string; }): React.JSX.Element | null
653
-
654
- ### @jgengine/shell/settings/SettingsRuntime
655
-
656
- - SettingsRuntime (function): function SettingsRuntime({ variant, surface, actions, children, ...input }: SettingsRuntimeProps): React.JSX.Element
657
- - SettingsRuntimeProps (interface): interface SettingsRuntimeProps extends SettingsControllerInput
658
-
659
- ### @jgengine/shell/settings/appliedSettings
660
-
661
- - AudioSettingsBridge (function): function AudioSettingsBridge({ store, engine, buses, }: { store: SettingsStore; engine: AudioEngine; buses: Record<string, AudioBusDef> | undefined; }): null
662
- - useGraphicsSettings (function): function useGraphicsSettings(store: SettingsStore, shadowsDefault: boolean): { shadows: boolean; dpr: number; uiScale: number }
663
- - useSettingsRevision (function): function useSettingsRevision(store: SettingsStore): number
664
-
665
- ### @jgengine/shell/settings/settingsController
666
-
667
- - SettingsControllerInput (interface): interface SettingsControllerInput
668
- - useSettingsCategories (function): function useSettingsCategories(config: SettingsControllerInput): SettingsCategoryView[]
669
-
670
- ### @jgengine/shell/structures
671
-
672
- - BuildingBlock (function): function BuildingBlock({ part, palette }: BuildingBlockProps): React.JSX.Element
673
- - BuildingBlockProps (interface): interface BuildingBlockProps
674
- - GeneratedBuilding (function): function GeneratedBuilding({ building, palette, kit, visibleKinds }: GeneratedBuildingProps): React.JSX.Element
675
- - GeneratedBuildingProps (interface): interface GeneratedBuildingProps
676
- - InstancedBuildingPlacement (interface): interface InstancedBuildingPlacement
677
- - InstancedBuildings (function): function InstancedBuildings({ buildings, palette, visibleKinds }: InstancedBuildingsProps): React.JSX.Element | null
678
- - InstancedBuildingsProps (interface): interface InstancedBuildingsProps
679
- - PlacementGhost (function): function PlacementGhost({ preview, height = 1, validColor = "#34d399", invalidColor = "#f87171", }: PlacementGhostProps): React.JSX.Element | null
680
- - PlacementGhostProps (interface): interface PlacementGhostProps
681
-
682
- ### @jgengine/shell/structures/GeneratedBuilding
683
-
684
- - BuildingBlock (function): function BuildingBlock({ part, palette }: BuildingBlockProps): React.JSX.Element
685
- - BuildingBlockProps (interface): interface BuildingBlockProps
686
- - BuildingFacade (type): type BuildingFacade = "front" | "back" | "left" | "right" | "roof"
687
- - BuildingKitRenderer (interface): interface BuildingKitRenderer
688
- - BuildingMaterialPalette (interface): interface BuildingMaterialPalette
689
- - BuildingPartKind (type): type BuildingPartKind = | "wall" | "window" | "awning" | "airConditioner" | "clothesline" | "storefront" | "shutter" | "storeSign" | "roof" | "roofProp" | "guardrail" | "corner"
690
- - BuildingPartPlacement (interface): interface BuildingPartPlacement
691
- - GeneratedBuilding (function): function GeneratedBuilding({ building, palette, kit, visibleKinds }: GeneratedBuildingProps): React.JSX.Element
692
- - GeneratedBuildingData (interface): interface GeneratedBuildingData
693
- - GeneratedBuildingProps (interface): interface GeneratedBuildingProps
694
- - InstancedBuildingPlacement (interface): interface InstancedBuildingPlacement
695
- - InstancedBuildings (function): function InstancedBuildings({ buildings, palette, visibleKinds }: InstancedBuildingsProps): React.JSX.Element | null
696
- - InstancedBuildingsProps (interface): interface InstancedBuildingsProps
697
-
698
- ### @jgengine/shell/structures/PlacementGhost
699
-
700
- - PlacementGhost (function): function PlacementGhost({ preview, height = 1, validColor = "#34d399", invalidColor = "#f87171", }: PlacementGhostProps): React.JSX.Element | null
701
- - PlacementGhostProps (interface): interface PlacementGhostProps
702
-
703
- ### @jgengine/shell/structures/index
704
-
705
- - BuildingBlock (function): function BuildingBlock({ part, palette }: BuildingBlockProps): React.JSX.Element
706
- - BuildingBlockProps (interface): interface BuildingBlockProps
707
- - GeneratedBuilding (function): function GeneratedBuilding({ building, palette, kit, visibleKinds }: GeneratedBuildingProps): React.JSX.Element
708
- - GeneratedBuildingProps (interface): interface GeneratedBuildingProps
709
- - InstancedBuildingPlacement (interface): interface InstancedBuildingPlacement
710
- - InstancedBuildings (function): function InstancedBuildings({ buildings, palette, visibleKinds }: InstancedBuildingsProps): React.JSX.Element | null
711
- - InstancedBuildingsProps (interface): interface InstancedBuildingsProps
712
- - PlacementGhost (function): function PlacementGhost({ preview, height = 1, validColor = "#34d399", invalidColor = "#f87171", }: PlacementGhostProps): React.JSX.Element | null
713
- - PlacementGhostProps (interface): interface PlacementGhostProps
714
-
715
- ### @jgengine/shell/terrain
716
-
717
- - CarvedTerrain (function): function CarvedTerrain({ field, size, segments, center, colors, heightRange, paletteAt, roughness = 0.95, metalness = 0, surfaceMaterial, receiveShadow = true, epoch = 0, ...meshProps }: CarvedTerrainProps): React.JSX.Element — Renders a `TerrainField` as a deformed ground mesh — the crater/mound view for destructible terrain. Because the geometry samples `field.sampleHeight`, a `CarvableField.carve(...)` shows as a real bowl once `epoch` changes. Pair with `InstancedBodies` to see debris resting in the crater it blasted.
718
- - CarvedTerrainProps (interface): interface CarvedTerrainProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
719
- - DEFAULT_GRASS_WIND (const): const DEFAULT_GRASS_WIND: Required<GrassWindOptions>
720
- - EditableGround (function): function EditableGround({ terrain, bounds, segments = 96, version = 0, baseColor = "#3f6b3a", surfaceColors = DEFAULT_SURFACE_COLORS, }: EditableGroundProps): React.JSX.Element
721
- - EditableGroundProps (interface): interface EditableGroundProps
722
- - FieldGroundOptions (interface): interface FieldGroundOptions
723
- - GrassBladeGeometryOptions (interface): interface GrassBladeGeometryOptions
724
- - GrassField (function): function GrassField({ count = DEFAULT_GRASS_COUNT, density = DEFAULT_GRASS_DENSITY, budget, area = 40, seed = 1, segments = 4, bladeHeight, bladeWidth, bladeBend, heightAt, colorBase, colorTip, colorVariation, wind, roughness, castShadow = false, receiveShadow = true, frustumCulled = true, ...meshPr…
725
- - GrassFieldProps (interface): interface GrassFieldProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
726
- - GrassMaterialHandle (interface): interface GrassMaterialHandle
727
- - GrassMaterialOptions (interface): interface GrassMaterialOptions
728
- - GrassRange (type): type GrassRange = number | readonly [min: number, max: number]
729
- - GrassShaderUniforms (interface): interface GrassShaderUniforms
730
- - GrassWindOptions (interface): interface GrassWindOptions
731
- - ProceduralGround (function): function ProceduralGround({ terrain, colors, roughness = 0.94, metalness = 0, receiveShadow = true, ...meshProps }: ProceduralGroundProps): React.JSX.Element
732
- - ProceduralGroundProps (interface): interface ProceduralGroundProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
733
- - ProceduralTerrainConfig (interface): interface ProceduralTerrainConfig
734
- - ResolvedGrassBladeGeometryOptions (interface): interface ResolvedGrassBladeGeometryOptions
735
- - ResolvedTerrainSegments (interface): interface ResolvedTerrainSegments
736
- - ResolvedTerrainSize (interface): interface ResolvedTerrainSize
737
- - TerraformBrushCursor (function): function TerraformBrushCursor({ center, y = 0.05, radius, mode }: TerraformBrushCursorProps): React.JSX.Element | null
738
- - TerraformBrushCursorProps (interface): interface TerraformBrushCursorProps
739
- - TerrainArea (type): type TerrainArea = number | readonly [width: number, depth: number]
740
- - TerrainHeightSampler (type): type TerrainHeightSampler = (x: number, z: number) => number
741
- - TerrainSeed (type): type TerrainSeed = number | string
742
- - TerrainVertexColorOptions (interface): interface TerrainVertexColorOptions
743
- - createFieldGroundGeometry (function): function createFieldGroundGeometry(field: TerrainField, options: FieldGroundOptions = {}): THREE.BufferGeometry — Mesh any `TerrainField` — including a `CarvableField` with craters/mounds written into it — into a vertex-coloured ground geometry. `sampleHeight` drives the vertices, so runtime carves show up as real depressions the moment the field is re-sampled (bump the caller's rebuild key after a carve).
744
- - createGrassBladeGeometry (function): function createGrassBladeGeometry(options: GrassBladeGeometryOptions = {}): THREE.InstancedBufferGeometry
745
- - createGrassMaterial (function): function createGrassMaterial(options: GrassMaterialOptions = {}): GrassMaterialHandle
746
- - createProceduralGroundGeometry (function): function createProceduralGroundGeometry(config: ProceduralTerrainConfig = {}, colors: TerrainVertexColorOptions = {}): THREE.BufferGeometry
747
- - createProceduralTerrainSampler (function): function createProceduralTerrainSampler(config: ProceduralTerrainConfig = {}): TerrainHeightSampler
748
- - createSeededRandom (function): function createSeededRandom(seed: TerrainSeed = 1): () => number
749
- - hashNoise2 (function): function hashNoise2(x: number, z: number, seed: TerrainSeed = 1): number
750
- - normalizeHeightBlend (function): function normalizeHeightBlend(height: number, minHeight: number, maxHeight: number): number
751
- - resolveGrassBladeGeometryOptions (function): function resolveGrassBladeGeometryOptions(options: GrassBladeGeometryOptions = {}): ResolvedGrassBladeGeometryOptions
752
- - resolveGrassRange (function): function resolveGrassRange(value: GrassRange | undefined, fallback: readonly [number, number]): readonly [number, number]
753
- - resolveGrassWind (function): function resolveGrassWind(wind: GrassWindOptions | false | undefined): Required<GrassWindOptions>
754
- - resolveTerrainSegments (function): function resolveTerrainSegments(segments: ProceduralTerrainConfig["segments"] = 96): ResolvedTerrainSegments
755
- - resolveTerrainSize (function): function resolveTerrainSize(size: TerrainArea = 40): ResolvedTerrainSize
756
- - seedToUint32 (function): function seedToUint32(seed: TerrainSeed = 1): number
757
- - toNoiseFieldConfig (function): function toNoiseFieldConfig(config: ProceduralTerrainConfig = {}): NoiseFieldConfig
758
-
759
- ### @jgengine/shell/terrain/CarvedTerrain
760
-
761
- - CarvedTerrain (function): function CarvedTerrain({ field, size, segments, center, colors, heightRange, paletteAt, roughness = 0.95, metalness = 0, surfaceMaterial, receiveShadow = true, epoch = 0, ...meshProps }: CarvedTerrainProps): React.JSX.Element — Renders a `TerrainField` as a deformed ground mesh — the crater/mound view for destructible terrain. Because the geometry samples `field.sampleHeight`, a `CarvableField.carve(...)` shows as a real bowl once `epoch` changes. Pair with `InstancedBodies` to see debris resting in the crater it blasted.
762
- - CarvedTerrainProps (interface): interface CarvedTerrainProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
763
-
764
- ### @jgengine/shell/terrain/EditableGround
765
-
766
- - EditableGround (function): function EditableGround({ terrain, bounds, segments = 96, version = 0, baseColor = "#3f6b3a", surfaceColors = DEFAULT_SURFACE_COLORS, }: EditableGroundProps): React.JSX.Element
767
- - EditableGroundProps (interface): interface EditableGroundProps
768
-
769
- ### @jgengine/shell/terrain/GrassField
770
-
771
- - DEFAULT_GRASS_COUNT (const): const DEFAULT_GRASS_COUNT: 1500
772
- - DEFAULT_GRASS_DENSITY (const): const DEFAULT_GRASS_DENSITY: 1
773
- - GrassField (function): function GrassField({ count = DEFAULT_GRASS_COUNT, density = DEFAULT_GRASS_DENSITY, budget, area = 40, seed = 1, segments = 4, bladeHeight, bladeWidth, bladeBend, heightAt, colorBase, colorTip, colorVariation, wind, roughness, castShadow = false, receiveShadow = true, frustumCulled = true, ...meshPr…
774
- - GrassFieldProps (interface): interface GrassFieldProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
775
- - resolveGrassInstanceBudget (function): function resolveGrassInstanceBudget(count: number, density: number, budget?: number): number
776
-
777
- ### @jgengine/shell/terrain/ProceduralGround
778
-
779
- - ProceduralGround (function): function ProceduralGround({ terrain, colors, roughness = 0.94, metalness = 0, receiveShadow = true, ...meshProps }: ProceduralGroundProps): React.JSX.Element
780
- - ProceduralGroundProps (interface): interface ProceduralGroundProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
781
-
782
- ### @jgengine/shell/terrain/TerraformBrushCursor
783
-
784
- - TerraformBrushCursor (function): function TerraformBrushCursor({ center, y = 0.05, radius, mode }: TerraformBrushCursorProps): React.JSX.Element | null
785
- - TerraformBrushCursorProps (interface): interface TerraformBrushCursorProps
786
-
787
- ### @jgengine/shell/terrain/grassBudget
788
-
789
- - DEFAULT_GRASS_COUNT (const): const DEFAULT_GRASS_COUNT: 1500
790
- - DEFAULT_GRASS_DENSITY (const): const DEFAULT_GRASS_DENSITY: 1
791
- - resolveGrassInstanceBudget (function): function resolveGrassInstanceBudget(count: number, density: number, budget?: number): number
792
-
793
- ### @jgengine/shell/terrain/grassGeometry
794
-
795
- - GrassBladeGeometryOptions (interface): interface GrassBladeGeometryOptions
796
- - GrassRange (type): type GrassRange = number | readonly [min: number, max: number]
797
- - ResolvedGrassBladeGeometryOptions (interface): interface ResolvedGrassBladeGeometryOptions
798
- - createGrassBladeGeometry (function): function createGrassBladeGeometry(options: GrassBladeGeometryOptions = {}): THREE.InstancedBufferGeometry
799
- - resolveGrassBladeGeometryOptions (function): function resolveGrassBladeGeometryOptions(options: GrassBladeGeometryOptions = {}): ResolvedGrassBladeGeometryOptions
800
- - resolveGrassRange (function): function resolveGrassRange(value: GrassRange | undefined, fallback: readonly [number, number]): readonly [number, number]
801
-
802
- ### @jgengine/shell/terrain/grassMaterial
803
-
804
- - DEFAULT_GRASS_WIND (const): const DEFAULT_GRASS_WIND: Required<GrassWindOptions>
805
- - GrassMaterialHandle (interface): interface GrassMaterialHandle
806
- - GrassMaterialOptions (interface): interface GrassMaterialOptions
807
- - GrassShaderUniforms (interface): interface GrassShaderUniforms
808
- - GrassWindOptions (interface): interface GrassWindOptions
809
- - createGrassMaterial (function): function createGrassMaterial(options: GrassMaterialOptions = {}): GrassMaterialHandle
810
- - resolveGrassWind (function): function resolveGrassWind(wind: GrassWindOptions | false | undefined): Required<GrassWindOptions>
811
-
812
- ### @jgengine/shell/terrain/index
813
-
814
- - CarvedTerrain (function): function CarvedTerrain({ field, size, segments, center, colors, heightRange, paletteAt, roughness = 0.95, metalness = 0, surfaceMaterial, receiveShadow = true, epoch = 0, ...meshProps }: CarvedTerrainProps): React.JSX.Element — Renders a `TerrainField` as a deformed ground mesh — the crater/mound view for destructible terrain. Because the geometry samples `field.sampleHeight`, a `CarvableField.carve(...)` shows as a real bowl once `epoch` changes. Pair with `InstancedBodies` to see debris resting in the crater it blasted.
815
- - CarvedTerrainProps (interface): interface CarvedTerrainProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
816
- - DEFAULT_GRASS_WIND (const): const DEFAULT_GRASS_WIND: Required<GrassWindOptions>
817
- - EditableGround (function): function EditableGround({ terrain, bounds, segments = 96, version = 0, baseColor = "#3f6b3a", surfaceColors = DEFAULT_SURFACE_COLORS, }: EditableGroundProps): React.JSX.Element
818
- - EditableGroundProps (interface): interface EditableGroundProps
819
- - FieldGroundOptions (interface): interface FieldGroundOptions
820
- - GrassBladeGeometryOptions (interface): interface GrassBladeGeometryOptions
821
- - GrassField (function): function GrassField({ count = DEFAULT_GRASS_COUNT, density = DEFAULT_GRASS_DENSITY, budget, area = 40, seed = 1, segments = 4, bladeHeight, bladeWidth, bladeBend, heightAt, colorBase, colorTip, colorVariation, wind, roughness, castShadow = false, receiveShadow = true, frustumCulled = true, ...meshPr…
822
- - GrassFieldProps (interface): interface GrassFieldProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
823
- - GrassMaterialHandle (interface): interface GrassMaterialHandle
824
- - GrassMaterialOptions (interface): interface GrassMaterialOptions
825
- - GrassRange (type): type GrassRange = number | readonly [min: number, max: number]
826
- - GrassShaderUniforms (interface): interface GrassShaderUniforms
827
- - GrassWindOptions (interface): interface GrassWindOptions
828
- - ProceduralGround (function): function ProceduralGround({ terrain, colors, roughness = 0.94, metalness = 0, receiveShadow = true, ...meshProps }: ProceduralGroundProps): React.JSX.Element
829
- - ProceduralGroundProps (interface): interface ProceduralGroundProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
830
- - ProceduralTerrainConfig (interface): interface ProceduralTerrainConfig
831
- - ResolvedGrassBladeGeometryOptions (interface): interface ResolvedGrassBladeGeometryOptions
832
- - ResolvedTerrainSegments (interface): interface ResolvedTerrainSegments
833
- - ResolvedTerrainSize (interface): interface ResolvedTerrainSize
834
- - TerraformBrushCursor (function): function TerraformBrushCursor({ center, y = 0.05, radius, mode }: TerraformBrushCursorProps): React.JSX.Element | null
835
- - TerraformBrushCursorProps (interface): interface TerraformBrushCursorProps
836
- - TerrainArea (type): type TerrainArea = number | readonly [width: number, depth: number]
837
- - TerrainHeightSampler (type): type TerrainHeightSampler = (x: number, z: number) => number
838
- - TerrainSeed (type): type TerrainSeed = number | string
839
- - TerrainVertexColorOptions (interface): interface TerrainVertexColorOptions
840
- - createFieldGroundGeometry (function): function createFieldGroundGeometry(field: TerrainField, options: FieldGroundOptions = {}): THREE.BufferGeometry — Mesh any `TerrainField` — including a `CarvableField` with craters/mounds written into it — into a vertex-coloured ground geometry. `sampleHeight` drives the vertices, so runtime carves show up as real depressions the moment the field is re-sampled (bump the caller's rebuild key after a carve).
841
- - createGrassBladeGeometry (function): function createGrassBladeGeometry(options: GrassBladeGeometryOptions = {}): THREE.InstancedBufferGeometry
842
- - createGrassMaterial (function): function createGrassMaterial(options: GrassMaterialOptions = {}): GrassMaterialHandle
843
- - createProceduralGroundGeometry (function): function createProceduralGroundGeometry(config: ProceduralTerrainConfig = {}, colors: TerrainVertexColorOptions = {}): THREE.BufferGeometry
844
- - createProceduralTerrainSampler (function): function createProceduralTerrainSampler(config: ProceduralTerrainConfig = {}): TerrainHeightSampler
845
- - createSeededRandom (function): function createSeededRandom(seed: TerrainSeed = 1): () => number
846
- - hashNoise2 (function): function hashNoise2(x: number, z: number, seed: TerrainSeed = 1): number
847
- - normalizeHeightBlend (function): function normalizeHeightBlend(height: number, minHeight: number, maxHeight: number): number
848
- - resolveGrassBladeGeometryOptions (function): function resolveGrassBladeGeometryOptions(options: GrassBladeGeometryOptions = {}): ResolvedGrassBladeGeometryOptions
849
- - resolveGrassRange (function): function resolveGrassRange(value: GrassRange | undefined, fallback: readonly [number, number]): readonly [number, number]
850
- - resolveGrassWind (function): function resolveGrassWind(wind: GrassWindOptions | false | undefined): Required<GrassWindOptions>
851
- - resolveTerrainSegments (function): function resolveTerrainSegments(segments: ProceduralTerrainConfig["segments"] = 96): ResolvedTerrainSegments
852
- - resolveTerrainSize (function): function resolveTerrainSize(size: TerrainArea = 40): ResolvedTerrainSize
853
- - seedToUint32 (function): function seedToUint32(seed: TerrainSeed = 1): number
854
- - toNoiseFieldConfig (function): function toNoiseFieldConfig(config: ProceduralTerrainConfig = {}): NoiseFieldConfig
855
-
856
- ### @jgengine/shell/terrain/random
857
-
858
- - TerrainSeed (type): type TerrainSeed = number | string
859
- - createSeededRandom (function): function createSeededRandom(seed: TerrainSeed = 1): () => number
860
- - hashNoise2 (function): function hashNoise2(x: number, z: number, seed: TerrainSeed = 1): number
861
- - seedToUint32 (function): function seedToUint32(seed: TerrainSeed = 1): number
862
-
863
- ### @jgengine/shell/terrain/terrainDetailMaterial
864
-
865
- - TerrainDetailMaterialHandle (interface): interface TerrainDetailMaterialHandle — The built procedural detail terrain material, ready to mount on the ground mesh.
866
- - createTerrainDetailMaterial (function): function createTerrainDetailMaterial(detail: ResolvedTerrainDetail): TerrainDetailMaterialHandle — A `MeshStandardMaterial` whose fragment shader keeps the biome-tinted vertex colour as the base ground and blends procedural, noise-broken rock (by slope), sand (by waterline), and snow (by height) over it — textured-reading terrain with no image assets. Full PBR: lit, shadowed, and fogged like any standard material, so it composes with the post-processing chain.
867
-
868
- ### @jgengine/shell/terrain/terrainMath
869
-
870
- - FieldGroundOptions (interface): interface FieldGroundOptions
871
- - ProceduralTerrainConfig (interface): interface ProceduralTerrainConfig
872
- - ResolvedTerrainSegments (interface): interface ResolvedTerrainSegments
873
- - ResolvedTerrainSize (interface): interface ResolvedTerrainSize
874
- - TerrainArea (type): type TerrainArea = number | readonly [width: number, depth: number]
875
- - TerrainHeightSampler (type): type TerrainHeightSampler = (x: number, z: number) => number
876
- - TerrainPaletteSampler (type): type TerrainPaletteSampler = (x: number, z: number) => { low: string; high: string; waterline?: string } — Per-position palette override for multi-biome ground coloring — `createTerrainPaletteSampler` from `@jgengine/core/world/terrain` returns exactly this shape.
877
- - TerrainVertexColorOptions (interface): interface TerrainVertexColorOptions
878
- - createFieldGroundGeometry (function): function createFieldGroundGeometry(field: TerrainField, options: FieldGroundOptions = {}): THREE.BufferGeometry — Mesh any `TerrainField` — including a `CarvableField` with craters/mounds written into it — into a vertex-coloured ground geometry. `sampleHeight` drives the vertices, so runtime carves show up as real depressions the moment the field is re-sampled (bump the caller's rebuild key after a carve).
879
- - createProceduralGroundGeometry (function): function createProceduralGroundGeometry(config: ProceduralTerrainConfig = {}, colors: TerrainVertexColorOptions = {}): THREE.BufferGeometry
880
- - createProceduralTerrainSampler (function): function createProceduralTerrainSampler(config: ProceduralTerrainConfig = {}): TerrainHeightSampler
881
- - normalizeHeightBlend (function): function normalizeHeightBlend(height: number, minHeight: number, maxHeight: number): number
882
- - resolveTerrainSegments (function): function resolveTerrainSegments(segments: ProceduralTerrainConfig["segments"] = 96): ResolvedTerrainSegments
883
- - resolveTerrainSize (function): function resolveTerrainSize(size: TerrainArea = 40): ResolvedTerrainSize
884
- - toNoiseFieldConfig (function): function toNoiseFieldConfig(config: ProceduralTerrainConfig = {}): NoiseFieldConfig
885
-
886
- ### @jgengine/shell/touch/OrientationHint
887
-
888
- - OrientationHint (function): function OrientationHint({ wanted }: { wanted: "landscape" | "portrait" }): React.JSX.Element | null
889
-
890
- ### @jgengine/shell/touch/TouchControlsOverlay
891
-
892
- - TouchCodeSink (interface): interface TouchCodeSink
893
- - TouchControlsDock (function): function TouchControlsDock({ scheme, sink, scale = 1 }: { scheme: TouchScheme; sink: TouchCodeSink; scale?: number }): React.JSX.Element
894
- - TouchPlaySurface (function): function TouchPlaySurface({ scheme, sink, yawRef, pitchRef, maxPitch, onPrimaryTap, }: { scheme: TouchScheme; sink: TouchCodeSink; yawRef: MutableRefObject<number>; pitchRef: MutableRefObject<number>; maxPitch: number; onPrimaryTap: () => void; }): React.JSX.Element
895
- - primaryButtonOffsets (function): function primaryButtonOffsets(count: number, scale = 1): { right: number; bottom: number }[] | null — Thumb-arc placement for primary buttons around the bottom-right corner: up to three on an inner ring, the rest on an outer ring. Null means too many buttons for an arc — the dock falls back to a wrapping grid.
896
- - touchDockClearance (function): function touchDockClearance(scheme: TouchScheme | null, scale = 1): number — Vertical space (px, excluding device safe areas) the dock occupies above the bottom edge. The shell publishes it as `--jg-hud-dock-clearance` so `HudCanvas` regions never collide with touch controls.
897
-
898
- ### @jgengine/shell/visibility/CullingProvider
899
-
900
- - CullingProvider (function): function CullingProvider({ config, children }: { config: VisibilityConfig | undefined; children: ReactNode }): ReactNode — Drives automatic frustum + distance culling for every entity and placed object. It reads the live render camera each frame, updates the engine VisibilitySystem, and exposes a predicate the entity/object markers consult to toggle `group.visible` — objects fully outside the view (plus a conservative preload margin) are never submitted to the renderer, without unmounting them or touching gameplay. UI, sky, terrain, and environment live outside this subtree and are unaffected.
901
- - useRenderVisibility (function): function useRenderVisibility(): MutableRefObject<VisiblePredicate> — Read the current render-visibility predicate. Backward compatible: with no CullingProvider mounted (or culling disabled) it returns an always-visible ref, so a marker that consults it behaves exactly as before this feature existed.
902
-
903
- ### @jgengine/shell/vision/FrustumSensorHud
904
-
905
- - FrustumSensorProbeOptions (interface): interface FrustumSensorProbeOptions extends FramingConfig
906
- - FrustumSensorReadout (function): function FrustumSensorReadout(props: FrustumSensorProbeOptions & { wrapperClassName?: string; className?: string }): React.JSX.Element — Renders inside the Canvas (needs the live camera via `useFrame`/`useThree`) but portals a real HTML readout via drei's `Html fullscreen` — a photo-mode "is this subject framed" HUD.
907
- - frustumSampleDisplayEqual (function): function frustumSampleDisplayEqual(a: FrustumSample | null, b: FrustumSample | null): boolean
908
- - useFrustumSensor (function): function useFrustumSensor(options: FrustumSensorProbeOptions): FrustumSample | null
909
-
910
- ### @jgengine/shell/vision/HiddenStateProbeHud
911
-
912
- - SensorReadoutMeter (function): function SensorReadoutMeter({ label, reading, className }: SensorReadoutMeterProps): React.JSX.Element — A handheld-sensor readout: needle strength bar + the raw reading, or a "no signal" idle state.
913
- - SensorReadoutMeterProps (interface): interface SensorReadoutMeterProps
914
- - useHiddenStateProbe (function): function useHiddenStateProbe(origin: EntityPosition, sources: readonly HiddenStateSource[], options: SensorProbeOptions): any — Reads a hidden zone/entity state variable in range (EMF / thermometer / geiger style sensor verb, #116).
915
-
916
- ### @jgengine/shell/vision/RevealVision
917
-
918
- - RevealHighlights (function): function RevealHighlights(props: RevealHighlightsProps): React.JSX.Element | null — Screen-space reveal effect (#115) — highlights tagged entities through occluders (Dark Sight / detective-vision / wallhack style). Renders with `depthTest: false` so the highlight draws over any wall standing between the origin and the revealed entity, rather than the usual depth-sorted scene.
919
- - RevealHighlightsProps (interface): interface RevealHighlightsProps extends RevealVisionOptions
920
- - RevealScreenTint (function): function RevealScreenTint({ enabled, color = "rgba(56, 189, 248, 0.16)", className }: RevealScreenTintProps): React.JSX.Element | null — Full-screen desaturating tint that reads as "vision mode is on" (Dark Sight / thermal / detective vision).
921
- - RevealScreenTintProps (interface): interface RevealScreenTintProps
922
- - RevealVisionOptions (interface): interface RevealVisionOptions
923
- - useRevealHits (function): function useRevealHits(options: RevealVisionOptions): readonly RevealHit[] — Occlusion-ignoring tagged-entity radius query (#115), bound to the live scene.
924
-
925
- ### @jgengine/shell/vision/frustumSampleEqual
926
-
927
- - frustumSampleDisplayEqual (function): function frustumSampleDisplayEqual(a: FrustumSample | null, b: FrustumSample | null): boolean
928
-
929
- ### @jgengine/shell/water
930
-
931
- - DEFAULT_OCEAN_CONFIG (const): const DEFAULT_OCEAN_CONFIG: ResolvedOceanConfig
932
- - DEFAULT_OCEAN_WAVE_SCALE (const): const DEFAULT_OCEAN_WAVE_SCALE: 18 — Shared with `@jgengine/core/world/water` — primary wavelength in world units.
933
- - MAX_OCEAN_WAVES (const): const MAX_OCEAN_WAVES: 6
934
- - OCEAN_QUALITY_PRESETS (const): const OCEAN_QUALITY_PRESETS: Record<OceanQualityPreset, { size: number; resolution: number }>
935
- - Ocean (function): function Ocean({ config, ...meshProps }: OceanProps): React.JSX.Element
936
- - OceanColorConfig (interface): interface OceanColorConfig
937
- - OceanConfig (interface): interface OceanConfig
938
- - OceanDirectionVector (interface): interface OceanDirectionVector
939
- - OceanFoamConfig (interface): interface OceanFoamConfig
940
- - OceanMaterialUniforms (interface): interface OceanMaterialUniforms
941
- - OceanProps (interface): interface OceanProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
942
- - OceanQualityPreset (type): type OceanQualityPreset = "low" | "medium" | "high" | "ultra"
943
- - OceanShaderMaterial (type): type OceanShaderMaterial = THREE.ShaderMaterial & { uniforms: OceanMaterialUniforms }
944
- - OceanWaveConfig (interface): interface OceanWaveConfig
945
- - OceanWaveDirection (type): type OceanWaveDirection = number | OceanDirectionVector
946
- - ResolvedOceanColorConfig (interface): interface ResolvedOceanColorConfig
947
- - ResolvedOceanConfig (interface): interface ResolvedOceanConfig
948
- - ResolvedOceanFoamConfig (interface): interface ResolvedOceanFoamConfig
949
- - ResolvedOceanWaveConfig (interface): interface ResolvedOceanWaveConfig
950
- - buildOceanWaveUniforms (function): function buildOceanWaveUniforms(config: ResolvedOceanConfig): { directions: THREE.Vector2[]; params: THREE.Vector4[]; }
951
- - createOceanConfig (function): function createOceanConfig(patch: OceanConfig = {}): ResolvedOceanConfig
952
- - createOceanMaterial (function): function createOceanMaterial(config: ResolvedOceanConfig): OceanShaderMaterial
953
- - syncOceanMaterial (function): function syncOceanMaterial(material: OceanShaderMaterial, config: ResolvedOceanConfig, elapsedSeconds: number): void
954
-
955
- ### @jgengine/shell/water/Ocean
956
-
957
- - Ocean (function): function Ocean({ config, ...meshProps }: OceanProps): React.JSX.Element
958
- - OceanProps (interface): interface OceanProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
959
-
960
- ### @jgengine/shell/water/OceanConfig
961
-
962
- - DEFAULT_OCEAN_CONFIG (const): const DEFAULT_OCEAN_CONFIG: ResolvedOceanConfig
963
- - DEFAULT_OCEAN_WAVE_SCALE (const): const DEFAULT_OCEAN_WAVE_SCALE: 18 — Shared with `@jgengine/core/world/water` — primary wavelength in world units.
964
- - MAX_OCEAN_WAVES (const): const MAX_OCEAN_WAVES: 6
965
- - OCEAN_QUALITY_PRESETS (const): const OCEAN_QUALITY_PRESETS: Record<OceanQualityPreset, { size: number; resolution: number }>
966
- - OceanColorConfig (interface): interface OceanColorConfig
967
- - OceanConfig (interface): interface OceanConfig
968
- - OceanDirectionVector (interface): interface OceanDirectionVector
969
- - OceanFoamConfig (interface): interface OceanFoamConfig
970
- - OceanQualityPreset (type): type OceanQualityPreset = "low" | "medium" | "high" | "ultra"
971
- - OceanWaveConfig (interface): interface OceanWaveConfig
972
- - OceanWaveDirection (type): type OceanWaveDirection = number | OceanDirectionVector
973
- - ResolvedOceanColorConfig (interface): interface ResolvedOceanColorConfig
974
- - ResolvedOceanConfig (interface): interface ResolvedOceanConfig
975
- - ResolvedOceanFoamConfig (interface): interface ResolvedOceanFoamConfig
976
- - ResolvedOceanWaveConfig (interface): interface ResolvedOceanWaveConfig
977
- - buildOceanWaveUniforms (function): function buildOceanWaveUniforms(config: ResolvedOceanConfig): { directions: THREE.Vector2[]; params: THREE.Vector4[]; }
978
- - createOceanConfig (function): function createOceanConfig(patch: OceanConfig = {}): ResolvedOceanConfig
979
-
980
- ### @jgengine/shell/water/OceanMaterial
981
-
982
- - OceanMaterialUniforms (interface): interface OceanMaterialUniforms
983
- - OceanShaderMaterial (type): type OceanShaderMaterial = THREE.ShaderMaterial & { uniforms: OceanMaterialUniforms }
984
- - createOceanMaterial (function): function createOceanMaterial(config: ResolvedOceanConfig): OceanShaderMaterial
985
- - syncOceanMaterial (function): function syncOceanMaterial(material: OceanShaderMaterial, config: ResolvedOceanConfig, elapsedSeconds: number): void
986
-
987
- ### @jgengine/shell/water/OceanShader
988
-
989
- - oceanFragmentShader (const): const oceanFragmentShader: "\nuniform vec3 uShallowColor;\nuniform vec3 uDeepColor;\nuniform vec3 uCrestColor;\nuniform vec3 uFoamColor;\nuniform float uOpacity;\nuniform float uFresnelStrength;\nuniform float uHorizonBlend;\nuniform float uFoamIntensity;\n\nvarying vec3 vWorldPosition;\nvarying vec…
990
- - oceanVertexShader (const): const oceanVertexShader: "\nuniform float uTime;\nuniform vec2 uWaveDirections[6];\nuniform vec4 uWaveParams[6];\nuniform float uChoppiness;\nuniform float uFoamThreshold;\nuniform float uFoamSoftness;\nuniform float uFoamCoverage;\n\nvarying vec3 vWorldPosition;\nvarying vec3 vNormal;\nvarying floa…
991
-
992
- ### @jgengine/shell/water/index
993
-
994
- - DEFAULT_OCEAN_CONFIG (const): const DEFAULT_OCEAN_CONFIG: ResolvedOceanConfig
995
- - DEFAULT_OCEAN_WAVE_SCALE (const): const DEFAULT_OCEAN_WAVE_SCALE: 18 — Shared with `@jgengine/core/world/water` — primary wavelength in world units.
996
- - MAX_OCEAN_WAVES (const): const MAX_OCEAN_WAVES: 6
997
- - OCEAN_QUALITY_PRESETS (const): const OCEAN_QUALITY_PRESETS: Record<OceanQualityPreset, { size: number; resolution: number }>
998
- - Ocean (function): function Ocean({ config, ...meshProps }: OceanProps): React.JSX.Element
999
- - OceanColorConfig (interface): interface OceanColorConfig
1000
- - OceanConfig (interface): interface OceanConfig
1001
- - OceanDirectionVector (interface): interface OceanDirectionVector
1002
- - OceanFoamConfig (interface): interface OceanFoamConfig
1003
- - OceanMaterialUniforms (interface): interface OceanMaterialUniforms
1004
- - OceanProps (interface): interface OceanProps extends Omit<ThreeElements["mesh"], "args" | "children" | "geometry" | "material">
1005
- - OceanQualityPreset (type): type OceanQualityPreset = "low" | "medium" | "high" | "ultra"
1006
- - OceanShaderMaterial (type): type OceanShaderMaterial = THREE.ShaderMaterial & { uniforms: OceanMaterialUniforms }
1007
- - OceanWaveConfig (interface): interface OceanWaveConfig
1008
- - OceanWaveDirection (type): type OceanWaveDirection = number | OceanDirectionVector
1009
- - ResolvedOceanColorConfig (interface): interface ResolvedOceanColorConfig
1010
- - ResolvedOceanConfig (interface): interface ResolvedOceanConfig
1011
- - ResolvedOceanFoamConfig (interface): interface ResolvedOceanFoamConfig
1012
- - ResolvedOceanWaveConfig (interface): interface ResolvedOceanWaveConfig
1013
- - buildOceanWaveUniforms (function): function buildOceanWaveUniforms(config: ResolvedOceanConfig): { directions: THREE.Vector2[]; params: THREE.Vector4[]; }
1014
- - createOceanConfig (function): function createOceanConfig(patch: OceanConfig = {}): ResolvedOceanConfig
1015
- - createOceanMaterial (function): function createOceanMaterial(config: ResolvedOceanConfig): OceanShaderMaterial
1016
- - syncOceanMaterial (function): function syncOceanMaterial(material: OceanShaderMaterial, config: ResolvedOceanConfig, elapsedSeconds: number): void
1017
-
1018
- ### @jgengine/shell/weather/FireSpreadLayer
1019
-
1020
- - FireSpreadLayer (function): function FireSpreadLayer({ grid, cellSize, origin = [0, 0], heightAt, flameHeight = 1.6, burningColor = "#ff6a1a", emberColor = "#4a1206", }: FireSpreadLayerProps): React.JSX.Element
1021
- - FireSpreadLayerProps (interface): interface FireSpreadLayerProps
1022
-
1023
- ### @jgengine/shell/weather/LightningStrike
1024
-
1025
- - LightningStrike (function): function LightningStrike({ origin, target, strikeKey = 0, seed = 451, visible = true, duration = 0.18, color = DEFAULT_COLOR, glow = 2.4, branches = 5, jaggedness = 0.08, impactLight = 26, renderOrder = 20, }: LightningStrikeProps): React.JSX.Element
1026
- - LightningStrikeProps (interface): interface LightningStrikeProps
1027
-
1028
- ### @jgengine/shell/weather/RainField
1029
-
1030
- - RainField (function): function RainField({ count = DEFAULT_RAIN_COUNT, density = DEFAULT_RAIN_DENSITY, budget, volume = DEFAULT_VOLUME, wind, origin = DEFAULT_ORIGIN, followCamera = true, speed = 22, length = 1.35, width = 0.018, opacity = 0.48, color = DEFAULT_RAIN_COLOR, lightning, timeScale, seed = 11939, renderOrder …
1031
- - RainFieldProps (interface): interface RainFieldProps
1032
-
1033
- ### @jgengine/shell/weather/SnowField
1034
-
1035
- - SnowField (function): function SnowField({ count = DEFAULT_SNOW_COUNT, density = DEFAULT_SNOW_DENSITY, budget, volume = DEFAULT_VOLUME, wind, origin = DEFAULT_ORIGIN, followCamera = true, speed = 3.2, size = 0.11, sway = 0.62, opacity = 0.86, color = DEFAULT_SNOW_COLOR, timeScale, seed = 72931, renderOrder = 11, frustumC…
1036
- - SnowFieldProps (interface): interface SnowFieldProps
1037
-
1038
- ### @jgengine/shell/weather/WeatherLayer
1039
-
1040
- - WeatherLayer (function): function WeatherLayer({ mode = "clear", intensity = 1, wind, lightning, timeScale, rain, snow, enabled = true, children, }: WeatherLayerProps): React.JSX.Element | null
1041
- - WeatherLayerMode (type): type WeatherLayerMode = "clear" | "rain" | "snow" | "mixed"
1042
- - WeatherLayerProps (interface): interface WeatherLayerProps
1043
-
1044
- ### @jgengine/shell/weather/fireSpreadPose
1045
-
1046
- - setBillboardQuaternion (function): function setBillboardQuaternion(quaternion: Quaternion, euler: Euler, yaw: number): void
1047
-
1048
- ### @jgengine/shell/weather/index
1049
-
1050
- - FireSpreadLayer (function): function FireSpreadLayer({ grid, cellSize, origin = [0, 0], heightAt, flameHeight = 1.6, burningColor = "#ff6a1a", emberColor = "#4a1206", }: FireSpreadLayerProps): React.JSX.Element
1051
- - FireSpreadLayerProps (interface): interface FireSpreadLayerProps
1052
- - LightningStrike (function): function LightningStrike({ origin, target, strikeKey = 0, seed = 451, visible = true, duration = 0.18, color = DEFAULT_COLOR, glow = 2.4, branches = 5, jaggedness = 0.08, impactLight = 26, renderOrder = 20, }: LightningStrikeProps): React.JSX.Element
1053
- - LightningStrikeProps (interface): interface LightningStrikeProps
1054
- - RainField (function): function RainField({ count = DEFAULT_RAIN_COUNT, density = DEFAULT_RAIN_DENSITY, budget, volume = DEFAULT_VOLUME, wind, origin = DEFAULT_ORIGIN, followCamera = true, speed = 22, length = 1.35, width = 0.018, opacity = 0.48, color = DEFAULT_RAIN_COLOR, lightning, timeScale, seed = 11939, renderOrder …
1055
- - RainFieldProps (interface): interface RainFieldProps
1056
- - SnowField (function): function SnowField({ count = DEFAULT_SNOW_COUNT, density = DEFAULT_SNOW_DENSITY, budget, volume = DEFAULT_VOLUME, wind, origin = DEFAULT_ORIGIN, followCamera = true, speed = 3.2, size = 0.11, sway = 0.62, opacity = 0.86, color = DEFAULT_SNOW_COLOR, timeScale, seed = 72931, renderOrder = 11, frustumC…
1057
- - SnowFieldProps (interface): interface SnowFieldProps
1058
- - WeatherLayer (function): function WeatherLayer({ mode = "clear", intensity = 1, wind, lightning, timeScale, rain, snow, enabled = true, children, }: WeatherLayerProps): React.JSX.Element | null
1059
- - WeatherLayerMode (type): type WeatherLayerMode = "clear" | "rain" | "snow" | "mixed"
1060
- - WeatherLayerProps (interface): interface WeatherLayerProps
1061
- - WeatherUniformOptions (interface): interface WeatherUniformOptions
1062
- - WeatherUniformProvider (function): function WeatherUniformProvider({ children, ...options }: WeatherUniformOptions & { children: ReactNode }): React.JSX.Element
1063
- - WeatherUniformSet (interface): interface WeatherUniformSet
1064
- - WeatherVector (type): type WeatherVector = readonly [number, number, number]
1065
- - createWeatherUniformSet (function): function createWeatherUniformSet(options: WeatherUniformOptions = {}): WeatherUniformSet
1066
- - useWeatherUniformSet (function): function useWeatherUniformSet(options: WeatherUniformOptions = {}): WeatherUniformSet
1067
-
1068
- ### @jgengine/shell/weather/weatherGeometry
1069
-
1070
- - createWeatherQuadGeometry (function): function createWeatherQuadGeometry(maxCount: number, seed: number): THREE.InstancedBufferGeometry
1071
-
1072
- ### @jgengine/shell/weather/weatherMath
1073
-
1074
- - DEFAULT_RAIN_COUNT (const): const DEFAULT_RAIN_COUNT: 2000
1075
- - DEFAULT_RAIN_DENSITY (const): const DEFAULT_RAIN_DENSITY: 0.45
1076
- - DEFAULT_SNOW_COUNT (const): const DEFAULT_SNOW_COUNT: 1500
1077
- - DEFAULT_SNOW_DENSITY (const): const DEFAULT_SNOW_DENSITY: 0.5
1078
- - WeatherSeedAttributes (interface): interface WeatherSeedAttributes
1079
- - clampWeatherRatio (function): function clampWeatherRatio(value: number): number
1080
- - createWeatherSeedAttributes (function): function createWeatherSeedAttributes(maxCount: number, seed: number): WeatherSeedAttributes
1081
- - resolveWeatherInstanceCount (function): function resolveWeatherInstanceCount(maxCount: number, density: number, budget?: number): number
1082
-
1083
- ### @jgengine/shell/weather/weatherUniforms
1084
-
1085
- - WeatherUniformOptions (interface): interface WeatherUniformOptions
1086
- - WeatherUniformProvider (function): function WeatherUniformProvider({ children, ...options }: WeatherUniformOptions & { children: ReactNode }): React.JSX.Element
1087
- - WeatherUniformSet (interface): interface WeatherUniformSet
1088
- - WeatherVector (type): type WeatherVector = readonly [number, number, number]
1089
- - createWeatherUniformSet (function): function createWeatherUniformSet(options: WeatherUniformOptions = {}): WeatherUniformSet
1090
- - useWeatherUniformSet (function): function useWeatherUniformSet(options: WeatherUniformOptions = {}): WeatherUniformSet
1091
-
1092
- ### @jgengine/shell/world/DataObjects
1093
-
1094
- - DataObjects (function): function DataObjects<T>({ data, position, height, color, cellSize = 0.28, hovered = null, hoverColor = "#ffffff", onHover, grow, castShadow = true, receiveShadow = true, renderItem, }: DataObjectsProps<T>): React.JSX.Element | null
1095
- - DataObjectsProps (interface): interface DataObjectsProps<T> — Renders one placed 3D object per data item — a 3D bar chart, a heatmap, a city of buildings, a crowd. By default each item is an extruded box (all boxes share one `InstancedMesh`, so hundreds cost one draw call), sized and colored from the item; `renderItem` swaps the box for arbitrary content (a sprite, a GLB, a full entity). Genre-agnostic: the caller owns the data `T`, this owns the placement.
1096
-
1097
- ### @jgengine/shell/world/GridWorldScene
1098
-
1099
- - GridWorldScene (function): function GridWorldScene({ feature }: GridWorldSceneProps): React.JSX.Element | null — Data-driven renderer for the `biomes()`/`voxel()`/`plots()`/`tilemap()` world-feature kinds (#207.1): one `InstancedMesh` of extruded, colored boxes built from each feature's declared `cells`, following the same direct-buffer pattern as `InstancedBodies`.
1100
- - GridWorldSceneProps (interface): interface GridWorldSceneProps
1101
-
1102
- ### @jgengine/shell/world/InstancedBodies
1103
-
1104
- - InstancedBodies (function): function InstancedBodies({ world, debugTint = false, baseColors, epoch = 0 }: InstancedBodiesProps): React.JSX.Element — Renders a PhysicsWorld's box bodies as a single InstancedMesh — one draw call per batch. Transforms are written directly into `instanceMatrix.array` each frame (bodies never touch the per-entity React path). Reusable by any game: hand it a physics world and go.
1105
- - InstancedBodiesProps (interface): interface InstancedBodiesProps
1106
-
1107
- ### @jgengine/shell/world/InstancedJoints
1108
-
1109
- - InstancedJoints (function): function InstancedJoints({ world, color = "#f5c542" }: InstancedJointsProps): React.JSX.Element — Debug overlay drawing a PhysicsWorld's joints (suspension, ragdoll links, carry tethers) as one LineSegments batch. Endpoints are streamed each frame from `world.readJointSegments`; pair with `InstancedBodies` to see the constraint structure over the bodies.
1110
- - InstancedJointsProps (interface): interface InstancedJointsProps
1111
-
1112
- ### @jgengine/shell/world/SpriteBatch
1113
-
1114
- - SpriteBatch (function): function SpriteBatch({ url, columns = 1, rows = 1, capacity = DEFAULT_CAPACITY, instances, plane = "xy", billboard = false, pixelated = true, alphaTest = DEFAULT_ALPHA_TEST, opacity = 1, }: SpriteBatchProps): React.JSX.Element — Renders a sprite sheet / tile atlas as a single InstancedMesh — one draw call for the whole batch. Each instance picks its atlas frame via a per-instance UV offset attribute patched into the material's vertex shader, so platformer/puzzle-grid presentation never needs one draw call per sprite. Transforms and UV offsets are written directly into the mesh's typed arrays each frame from a plain instance list (bodies never touch the per-entity React path).
1115
- - SpriteBatchInstance (interface): interface SpriteBatchInstance
1116
- - SpriteBatchProps (interface): interface SpriteBatchProps
1117
-
1118
- ### @jgengine/shell/world/WorldHud
1119
-
1120
- - CombatCameraShake (function): function CombatCameraShake(): null
1121
- - ProjectileTracers (function): function ProjectileTracers({ lifeMs = 130 }: { lifeMs?: number }): React.JSX.Element
1122
- - Reticle (function): function Reticle({ className }: { className?: string }): React.JSX.Element
1123
- - WorldBarSample (interface): interface WorldBarSample
1124
- - WorldEntityBars (function): function WorldEntityBars({ statId, height = 2.2, roles, resolveRole, maxDistance = 60, }: { statId: string; height?: number; roles?: readonly CatalogEntityRole[]; resolveRole?: (entity: SceneEntity) => CatalogEntityRole | undefined; /** Hide bars for entities farther than this from the player (world…
1125
- - WorldFloatText (function): function WorldFloatText({ height = 1.9, lifeMs = 950 }: { height?: number; lifeMs?: number }): React.JSX.Element
1126
- - WorldTelegraphs (function): function WorldTelegraphs(): React.JSX.Element
1127
- - collectWorldBarSamples (function): function collectWorldBarSamples(ctx: GameContext, statId: string, height: number, roles: readonly CatalogEntityRole[] | undefined, resolveRole: ((entity: SceneEntity) => CatalogEntityRole | undefined) | undefined, camera: { matrixWorldInverse: unknown; projectionMatrix: unknown }, viewport: { width:…
1128
- - paintWorldBarSamples (function): function paintWorldBarSamples(canvas: { width: number; height: number; getContext(kind: "2d"): CanvasRenderingContext2D | null }, samples: readonly WorldBarSample[], dpr: number, barWidthPx = 112, barHeightPx = 10): void
1129
- - telegraphPulseOpacity (function): function telegraphPulseOpacity(bornMs: number, windupMs: number, nowMs: number): number
1130
-
1131
- ### @jgengine/shell/world/WorldItems
1132
-
1133
- - WorldItems (function): function WorldItems({ config }: { config?: WorldItemRenderConfig }): React.JSX.Element — Rarity→beam/color/label render binding + loot-filter overlay (#32/#33) for every dropped `worldItem`.
1134
-
1135
- ### @jgengine/shell/world/entityPose
1136
-
1137
- - PoseSource (interface): interface PoseSource
1138
- - PoseWritable (interface): interface PoseWritable
1139
- - posesEqual (function): function posesEqual(a: PoseSource, b: PoseSource): boolean
1140
- - writeEntityPose (function): function writeEntityPose(target: PoseWritable, source: PoseSource): void
1141
-
1142
- ### @jgengine/shell/world/floatTextStyle
1143
-
1144
- - FloatTextInfo (interface): interface FloatTextInfo
1145
- - FloatTextStyle (interface): interface FloatTextStyle
1146
- - resolveFloatTextStyle (function): function resolveFloatTextStyle(info: FloatTextInfo): FloatTextStyle
1147
-
1148
- ### @jgengine/shell/world/telegraphPulse
1149
-
1150
- - telegraphPulseOpacity (function): function telegraphPulseOpacity(bornMs: number, windupMs: number, nowMs: number): number
1151
-
1152
- ### @jgengine/shell/world/worldBarSamples
1153
-
1154
- - Projectable (interface): interface Projectable
1155
- - WorldBarSample (interface): interface WorldBarSample
1156
- - collectWorldBarSamples (function): function collectWorldBarSamples(ctx: GameContext, statId: string, height: number, roles: readonly CatalogEntityRole[] | undefined, resolveRole: ((entity: SceneEntity) => CatalogEntityRole | undefined) | undefined, camera: { matrixWorldInverse: unknown; projectionMatrix: unknown }, viewport: { width:…
1157
- - paintWorldBarSamples (function): function paintWorldBarSamples(canvas: { width: number; height: number; getContext(kind: "2d"): CanvasRenderingContext2D | null }, samples: readonly WorldBarSample[], dpr: number, barWidthPx = 112, barHeightPx = 10): void
1158
-
1159
- ### @jgengine/shell/worldSync
1160
-
1161
- - attachWorldSync (function): function attachWorldSync(feeds: Pick<GameRuntimeFeeds, "subscribeServer">, serverId: string, ctx: Pick<GameContext, "hydrate">): () => void — Client half of host-authoritative play: subscribe to the server-state channel and mirror each authoritative `WorldSnapshot` (carried in `serverState`) into the local `ctx`, so the game renders the host's world instead of a locally-simulated one. Pure and transport-agnostic — the backend's `feeds.subscribeServer` is the only dependency; returns the unsubscribe. The shell attaches this (and gates its local sim) when the game's adapter opts into `authority: "server"`.
1162
-
1163
- ## Guides
1164
-
1165
- # JGengine
1166
-
1167
- JGengine is a pure-TypeScript game-engine SDK for games built by AI coding agents. Its skills teach the agent how to use the SDK. When a user says “make X with JGengine” or “make X with jgengine.com,” treat that as sufficient intake. If the skills are not installed, run `npx jgengine skills`; then use this skill and build on the SDK. Do not make the user discover or name skills.
1168
-
1169
- ## Intake
1170
-
1171
- State the reading as a short numbered list that is easy to correct, then proceed unless the user changes it. Prefer concrete values and actions over prose:
1172
-
1173
- 1. **POV:** first-person
1174
- 2. **World:** custom 3D wasteland with three settlements
1175
- 3. **Core loop:** get quests by talking to people → defeat enemies → return to redeem quests
1176
- 4. **Interaction:** collect ground items by walking over them; interact with people and doors at close range
1177
- 5. **Combat:** ranged weapons, damage, death, loot
1178
- 6. **Progression:** inventory, currency, quest rewards, upgrades
1179
- 7. **Players:** single-player, or name the multiplayer topology and synchronized systems
1180
- 8. **UI:** visible controls, objective tracker, health, inventory feedback
1181
- 9. **Art direction:** one aesthetic, palette, asset family, and UI voice
1182
- 10. **Done looks like:** one observable end-to-end play scenario
1183
-
1184
- Keep this compact—roughly one line per item. It is a build map, not a large specification or an approval gate. Infer conventional details from the named game or genre. Ask only when two plausible readings would fundamentally change the game.
1185
-
1186
- ## Route selectively
1187
-
1188
- This skill is the foundation for every task (packages, project shape, defineGame, context, catalogs). After intake, also read only the domain skills the work needs:
1189
-
1190
- | Need | Read |
1191
- | --- | --- |
1192
- | Terrain, scenes, camera, movement, physics, maps, sensors | `jgengine-world` |
1193
- | Seeded generation, terrain/environment generation, grids, buildings, simulation | `jgengine-procedural` |
1194
- | Damage, effects, weapons, targeting, projectiles, loot, death | `jgengine-combat` |
1195
- | Items, quests, dialogue, economy, crafting, objectives, turns, social systems | `jgengine-gameplay` |
1196
- | Networking adapters, authority, rooms/topology, persistence/backend seams | `jgengine-multiplayer` |
1197
- | React HUD, shell affordances, controls, feedback, accessibility | `jgengine-ui` |
1198
- | Models, sprites, textures, audio, catalogs, attribution | `jgengine-assets` |
1199
- | Proof and screenshots | `jgengine-verify` after implementation |
1200
-
1201
- Do not read every domain by default. Build through documented engine surfaces; do not infer APIs from gallery games. Inspect engine source only when a documented surface appears wrong or a missing primitive blocks the work.
1202
-
1203
- ## Build behavior
1204
-
1205
- Scaffold with `npx jgengine create game-name --name "Game Name"` when needed. Build the requested game continuously from the intake, keeping systems end-to-end rather than leaving registered-but-unusable pieces. Use real assets and visible feedback early. Verify at completion with `jgengine-verify`.
1206
-
1207
- Cartridge-shaped games (declarative config, engine-owned loop): see [reference-cartridge.md](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine/reference-cartridge.md).
1208
-
1209
- ---
1210
-
1211
- The engine ships **verbs and primitives**; your game ships **nouns** (catalogs) and thin handlers. This skill is that foundation plus intake. Use domain skills only when needed; use `jgengine-verify` afterward. UI guidance lives in [`../jgengine-ui/reference.md`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-ui/reference.md); assets live in `jgengine-assets`.
1212
-
1213
- Load detailed references only for the selected domain: [`jgengine-combat`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-combat/reference.md), [`jgengine-world`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-world/reference.md), [`jgengine-multiplayer`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-multiplayer/reference.md), and [`jgengine-ui`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-ui/reference.md). Each domain skill explains when its reference is needed.
1214
-
1215
- ## Packages
1216
-
1217
- All published on npm, source at [github.com/Noisemaker111/jgengine](https://github.com/Noisemaker111/jgengine) (AGPL-3.0):
1218
-
1219
- | Package | Role | May import |
1220
- |---------|------|------------|
1221
- | `@jgengine/core` | Everything below: defineGame, GameContext, scene, combat, game systems, movement, input, world features, runtime/transport contracts | nothing platform-specific — no React, Convex, three.js, browser |
1222
- | `@jgengine/react` | `GameProvider`, hooks, headless UI primitives | react + core |
1223
- | `@jgengine/shell` | `GamePlayerShell` — R3F canvas, camera rig library (orbit, first-person, top-down/iso, RTS, over-the-shoulder, lock-on, chase, cinematic + shake channel), input tracking, HUD mounting, `GameUiPreview`, demo game; you supply a `GameRegistry` | react + three + core |
1224
- | `@jgengine/ws` | Browser-safe `GameBackend` over a pluggable string-pipe transport (WebSocket/socket.io/WebRTC/loopback), protocol codec, HTTP reads, browser-safe authoritative host + router (`host`/`hostRouter`), and P2P (`peer`) | core |
1225
- | `@jgengine/node` | Node process bindings over `@jgengine/ws`'s host/router: `ws`-package server, socket.io server attach, file persistence (re-exports `createGameHost`/`memoryPersistence` unchanged) | node + ws + core |
1226
- | `@jgengine/sql` | `HostPersistence` on Postgres (structural pool, no hard `pg` dep) | core |
1227
- | `@jgengine/convex` | The Convex **adapter** behind the `GameBackend` seam | react + convex + core |
1228
-
1229
- Import by deep path: `@jgengine/core/<domain>/<file>` (e.g. `@jgengine/core/runtime/gameContext`).
1230
-
1231
- ## Hit a snag? File an issue
1232
-
1233
- Any hiccup with JGengine — a doc that's wrong, a missing primitive, a rough edge, or a feature/improvement idea — file it fast at [github.com/Noisemaker111/jgengine/issues](https://github.com/Noisemaker111/jgengine/issues). A 30-second issue (what you were building, the glue it forced, the API you wanted) is worth more than a silent workaround — that's the fastest way gaps and doc errors get closed. Don't reverse-engineer around a broken doc in silence; report it.
1234
-
1235
- ## Upgrading? Read the changelog
1236
-
1237
- All eight packages version in lockstep. When you bump (e.g. `0.6` → `0.7`) to pick up new capabilities, read [`CHANGELOG.md`](https://github.com/Noisemaker111/jgengine/blob/main/CHANGELOG.md) — each release leads with a **Migrate** block listing the concrete steps to move a game onto the new APIs. It ships inside every package too (`node_modules/@jgengine/core/CHANGELOG.md`), and as typed values: `import { VERSION, CHANGELOG } from "@jgengine/core/meta/changelog"` to diff your installed version against the latest programmatically.
1238
-
1239
- ## Concept → Type Reference
1240
-
1241
- Exact import paths and export names — **do not invent paths**; every row below resolves to a real file under `packages/core/src`. Import the deep path form `@jgengine/core/<path>`.
1242
-
1243
- | Concept | Import path (`@jgengine/core/…`) | Export(s) |
1244
- |---------|----------------------------------|-----------|
1245
- | Game boot | `game/defineGame` | `defineGame`, `GameDefinition`, `GameLoop`, `InventoryDeclaration`, `PhysicsConfig`, `GameServerConfig`, `TimeConfig` |
1246
- | Simulation clock | `time/simClock` | `createSimClock`, `SimClock`, `TimeConfig`, `ClockSnapshot`, `CalendarTime` |
1247
- | Runner contract | `game/playableGame` | `PlayableGame`, `GameCameraConfig`, `CameraRigKind`, `CameraProjection`, `SideScrollCameraConfig`, `TopDownCameraConfig`, `RtsCameraConfig`, `ShoulderCameraConfig`, `LockOnCameraConfig`, `ChaseCameraConfig`, `ObserverCameraConfig`, `CameraShakeConfig`, `CinematicCameraConfig`, `CameraKeyframe`, `EntitySpriteConfig` |
1248
- | Runtime ctx | `runtime/gameContext` | `createGameContext`, `GameContext`, `GameContextContent`, `GameContextItemEntry`, `GameContextEntityEntry`, `GameContextObjectEntry`, `CatalogEntityRole` |
1249
- | Behaviour lifecycle | `behaviour/behaviour` | `Behaviour` (`onAwake`→`onEnable`→`onStart`→`onUpdate(dt)`→`onDisable`→`onDestroy`), `BehaviourModule`, `createBehaviourWorld`, `BehaviourWorld`, `JGEngineRegister`, `RegisterField`, `BehaviourModules` — Unity-style lifecycle over an id-keyed node tree (`setActive` cascade, lazy update dispatch); key nodes by entity instance ids. Games augment `JGEngineRegister` via `declare module "@jgengine/core/behaviour/behaviour"` for typed `world.modules`. Three.js binding: `Object3DBehaviour`, `attachObject3D`, `useBehaviourWorld` from `@jgengine/shell/behaviour` |
1250
- | Reactive keyed store | `store/observableKeyedStore` | `createObservableKeyedStore`, `ObservableKeyedStore` — backs `ctx.game.store` |
1251
- | Scene instance role | `scene/entityStore` | `EntityRole`, `SceneEntity`, `SpawnOptions`, `EntityPose` |
1252
- | Object spatial queries | `scene/objectQuery` | `raycastObjects`, `raycastObjectsAll`, `ObjectRaycastInput`, `ObjectRaycastHit` — backs `ctx.scene.object.raycast`/`raycastAll` |
1253
- | Runtime paint layer | `scene/paintLayer` | `createPaintLayer`, `PaintLayer`, `PaintStroke` — backs `ctx.scene.entity.paint` |
1254
- | Possession | `scene/possession` | `createPossession`, `Possession`, `PossessionDeps`, `PossessionSwappedEvent` |
1255
- | Form / shapeshift | `scene/form` | `createForms`, `Forms`, `FormDef`, `FormsDeps`, `FormChangedEvent` |
1256
- | Multiplayer adapters | `runtime/adapter` | `offline`, `ws`, `convex`, `socketIo`, `p2p`, `lan`, `fly`, `servers`, `MultiplayerTopology`, `ServersPoolConfig` |
1257
- | Loot | `game/lootTable` | `lootTable`, `LootTableDef`, `LootEntry`, `Drop` |
1258
- | Dropped-item entity | `game/worldItem` | `WORLD_ITEM_ENTITY_NAME`, `WorldItemRecord`, `WorldItemSpawnInput`, `createWorldItemStore`, `resolveDeathDrops`, `scatterOffset`, `scatterPosition`, `selectNearestWorldItem`, `resolveWorldItemPresentation`, `RarityStyle`, `WorldItemPresentation`, `DEFAULT_RARITY`, `DEFAULT_PICKUP_RADIUS`, `DEFAULT_SCATTER` |
1259
- | Loot filter | `game/lootFilter` | `lootFilter`, `evaluateLootFilter`, `LootFilterRule`, `LootFilterCondition`, `LootFilterItem`, `LootFilterOverride` |
1260
- | Loadout | `game/loadout` | `LoadoutDef`, `LoadoutItemEntry`, `Loadouts` |
1261
- | Cosmetic loadout | `game/cosmetics` | `createCosmetics`, `Cosmetics`, `CosmeticLoadoutDef` |
1262
- | Quest | `game/quest` | `QuestDef`, `QuestRewards`, `QuestObjective`, `QuestJournal` |
1263
- | World features | `world/features` | `WorldFeature`, `biomes`, `voxel`, `plots`, `tilemap`, `flat`, `environment`, `terrain`, `rain`, `snow`, `grass`, `ocean`, `building`, `road` |
1264
- | Street layout | `world/streets` | `laneCenters`, `sidewalkPaths`, `furnitureSpots`, `parkingSpots`, `sidewalkPoint`, `offsetPath`, `sidewalkWidthOf`, `StreetLane`, `FurnitureSpot`, `ParkingSpot` — where things belong on a `road()`: lanes for traffic, sidewalks for peds, curb anchors for furniture |
1265
- | Road ribbons | `world/roads` | `buildRoadRibbon`, `dashSegments`, `nearestOnPath`, `isOnRoad`, `pathLength`, `RoadRibbon`, `RoadSample`, `RoadPoint` — geometry + queries behind the `road()` environment feature |
1266
- | Voxel field | `world/voxelField` | `createVoxelField`, `VoxelField`, `VoxelCell`, `VoxelHit`, `VoxelBounds`, `VoxelFieldSummary`, `VoxelFace`, `VOXEL_FACES`, `VOXEL_FACE_NORMALS` — a chunked block lattice, distinct from the `voxel()` `WorldFeature` descriptor |
1267
- | Terrain field | `world/terrain` | `TerrainField`, `noiseField`, `resolveTerrainField`, `rollingField`, `fractalNoise`, `valueNoise`, `withNormal`, `arenaField`, `flatField`, `resolveGroundStep`, `snapToGround`, `snapEntityToGround`, `resolveTerrainPalette`, `TERRAIN_MATERIAL_PALETTES` |
1268
- | Seeded RNG | `random/rng` | `seededRng`, `seededStreams` |
1269
- | Seed share link | `random/seedLink` | `withSeedParam`, `seedFromUrl`, `seedFromSearch`, `dailySeed`, `DEFAULT_SEED_PARAM` — encode/decode a world seed to/from a shareable URL query param; `dailySeed` is the UTC daily-run seed |
1270
- | Name generator | `random/nameGen` | `createNameGenerator`, `pickFrom`, `fillTemplate`, `NameGenerator`, `NameGeneratorOptions`, `SyllableBank` |
1271
- | Regions | `world/regions` | `createRegionField`, `isRegionField`, `RegionDef`, `RegionField`, `RegionSample` |
1272
- | Wind field | `world/wind` | `windField`, `WindField`, `WindFieldConfig`, `WindVector` |
1273
- | Water surface | `world/water` | `waterSurface`, `waterSurfaceFromDescriptor`, `synthesizeWaves`, `WaterSurface`, `GerstnerWave` |
1274
- | Scatter | `world/scatter` | `scatter`, `scatterAabb`, `ScatterConfig`, `ScatterPoint` |
1275
- | Content scatter | `world/scatterItems` | `scatterItems`, `pickWeighted`, `ScatterLayer`, `ScatterInstance` |
1276
- | Building generator | `world/buildings` | `generateBuilding`, `generateBuildingDistrict`, `createBuildingGrid`, `GeneratedBuilding` |
1277
- | Building index | `world/buildingIndex` | `buildingIndex`, `BuildingIndex`, `BuildingHit` |
1278
- | Scene summary | `world/environmentSummary` | `summarizeEnvironment`, `resolveStructureBuildings`, `EnvironmentSummary` |
1279
- | Map markers | `world/markers` | `createMarkerSet`, `MarkerSet`, `MapMarker`, `MarkerInput`, `MarkerKindStyle`, `DEFAULT_MARKER_KINDS`, `markerKindStyle` |
1280
- | Fog of war | `world/fog` | `createFogField`, `FogField`, `FogConfig`, `FogBounds`, `FogCells` |
1281
- | Minimap math | `world/minimap` | `projectToMinimap`, `clampToMinimapEdge`, `compassBearing`, `headingToBearing`, `bearingToCardinal`, `relativeBearing`, `MinimapView` |
1282
- | Ping | `game/ping` | `createPingSystem`, `classifyPing`, `PingSystem`, `PingPayload`, `PingCategory`, `PingCategoryDef`, `DEFAULT_PING_CATEGORIES`, `PING_FEED_ACTION` |
1283
- | Proximity prompt | `interaction/proximityPrompt` | `proximityPrompt`, `ProximityPrompt`, `ProximityPromptDisplay`, `keybind`, `gauge`, `label`, `command` |
1284
- | Skill-check minigame | `interaction/skillCheck` | `evaluateSkillCheck`, `skillCheckMarkerPosition`, `skillCheckZoneAt`, `SkillCheckConfig`, `SkillCheckZone`, `SkillCheckResult` |
1285
- | QTE sequencer | `interaction/qte` | `evaluateQteSequence`, `pendingQteStep`, `qteProgress`, `QteStep`, `QteInputEvent`, `QteOutcome` |
1286
- | Item use | `item/use` | `createItemUse`, `ItemUseHandler`, `ItemUseInput`, `ItemUseResult`, `ItemUseRejection` |
1287
- | Durability | `item/durability` | `createDurability`, `wear`, `repairQuote`, `isDisabled`, `createDurabilityTracker`, `DurabilitySpec`, `DurabilityState`, `RepairSpec`, `RepairQuote` |
1288
- | Affix roller | `item/affix` | `createAffixRoller`, `seededRng`, `AffixRoller`, `RollerConfig`, `AffixPool`, `AffixDef`, `RarityTier`, `ItemBaseDef`, `RolledItem`, `RolledAffix` |
1289
- | Modular item | `item/modularItem` | `createModularItem`, `install`, `computeEffectiveStats`, `missingRequiredSlots`, `ModularItemDef`, `MountSlotDef`, `PartDef`, `InstalledPart` |
1290
- | Storage tier | `inventory/storageTier` | `partitionOnDeath`, `createDeliveryQueue`, `insureLost`, `resolveConsolation`, `tierOf`, `StorageTier`, `ContainerSnapshot`, `DeathPartition`, `DeliveryQueue`, `InsurancePolicy`, `ConsolationPolicy` |
1291
- | Contested channel | `session/contestedChannel` | `createContestedChannel`, `ContestedChannel`, `ContestedChannelConfig`, `ContestedEvent`, `ContestedPhase`, `ContestedSnapshot` |
1292
- | Round state | `session/roundState` | `createRoundState`, `lossBonusFor`, `RoundState`, `RoundConfig`, `RoundPhase`, `RoundTeam`, `RoundEvent`, `RoundEconomy`, `RoundSnapshot`, `LossBonusRule` |
1293
- | Shrinking ring | `session/ring` | `createRing`, `ringSampleAt`, `Ring`, `RingConfig`, `RingPhase`, `RingSample`, `RingHit`, `RingPoint` |
1294
- | Extraction session | `session/extraction` | `createRaidSession`, `RaidSession`, `RaidSessionConfig`, `ExtractPoint`, `ExtractionResult`, `DeathResult`, `RaidStatus` |
1295
- | Role assignment | `session/roles` | `assignRoles`, `RoleSpec` |
1296
- | Downed / revive | `combat/downed` | `createDownedState`, `DownedState`, `DownedConfig`, `DownedPhase`, `DownedEntry`, `DownedEvent` |
1297
- | Persistence scopes | `runtime/persistenceScope` | `partitionScopes`, `resetRun`, `mergeScopes`, `clearRunFields`, `applyRunReset`, `planScenarioReset`, `ScopeSchema`, `ScenarioReset`, `PersistenceScope` |
1298
- | Inventory | `inventory/inventoryModel` | `InventoryLayout`, `InventorySet`, `ItemTraits` |
1299
- | Progression | `game/progression` | `curve`, `evalCurve`, `leveling`, `Curve`, `LevelingTrack`, `LevelProgress` |
1300
- | Talent tree | `game/talents` | `createTalentTree`, `TalentTree`, `TalentTreeConfig`, `TalentNodeDef`, `TalentRequirement`, `TalentAllocateResult`, `ResolvedTalents`, `TalentSnapshot` — point spends gated by prereqs + points-in-branch, resolved once into a cached flat `StatModifierSet` + ability grants |
1301
- | Inventory slots | `inventory/slotModel` | `createSlots`, `placeAt`, `removeAt`, `moveSlot`, `firstEmpty`, `compactSlots`, `Slot`, `SlotGrid` |
1302
- | Shaped inventory | `inventory/shapedGrid` | `createShapedGrid`, `placeShaped`, `moveShaped`, `removeShaped`, `canPlace`, `rotateFootprint`, `occupiedCells`, `gridAdjacencyQuery`, `cellFromPoint`, `ShapedGrid`, `Footprint`, `Placement`, `Rotation` |
1303
- | Card piles | `cards/cardPile` | `createCardPile`, `createCardPileState`, `draw`, `moveCards`, `shuffleZone`, `pileRng`, `CardPile`, `CardPileState`, `CardPileConfig` |
1304
- | Modifier pipeline | `cards/modifierPipeline` | `createModifierPipeline`, `runPipeline`, `Modifier`, `TraceStep`, `PipelineResult` |
1305
- | Lane board | `board/laneBoard` | `createLaneBoard`, `laneAggregate`, `laneOutcome`, `boardTotals`, `lanesWon`, `LaneBoard`, `LaneRule`, `LaneBoardConfig` |
1306
- | Timeline board | `board/timelineBoard` | `createTimelineBoard`, `tickTimeline`, `TimelineBoard`, `TimelineSlot`, `TimelineFire` |
1307
- | World geometry | `world/geometry` | `footprintAabb`, `aabbOverlap`, `snapToGrid`, `resolveMove`, `Aabb`, `Footprint` |
1308
- | Placement | `world/placement` | `validatePlacement`, `footprintObstacle`, `PlacementRules`, `PlacementResult` |
1309
- | Placement ghost | `world/placementController` | `createPlacementController`, `PlacementController`, `PlacementPreview`, `PlacementCommit`, `SnapMode`, `quarterTurnsToRotationY` |
1310
- | Connector sockets | `world/connectors` | `snapToNearest`, `socketsCompatible`, `worldSockets`, `socketWorldPosition`, `ConnectorSocket`, `ConnectorPieceDef`, `PlacedPiece`, `SnapResult` |
1311
- | Structural support | `world/support` | `solveSupport`, `toDebrisBodies`, `SupportPiece`, `SupportLink`, `SupportResult` |
1312
- | Wall/roof authoring | `world/walls` | `createWallDrawTool`, `footprintFromWalls`, `autoRoof`, `wallSegments`, `createSurfacePaint`, `WallDrawTool`, `RoofPlan`, `EnclosedFootprint` |
1313
- | Placed structures | `world/placedStructureStore` | `createPlacedStructureStore`, `PlacedStructure`, `PlacedStructureStore`, `PlacedStructureSnapshot` |
1314
- | Terraform | `world/terraform` | `createEditableTerrain`, `createTerraformBrush`, `brushWeight`, `EditableTerrain`, `TerraformBrush`, `TerraformEdit`, `TerraformMode` |
1315
- | Build permissions | `world/buildPermissions` | `createPlotPermissions`, `createContributionPool`, `PlotPermissions`, `ContributionPool`, `BuildRole`, `ContributionGoal` |
1316
- | Interiors | `world/interiors` | `createInteriors`, `Interior`, `Exterior`, `SpaceRef` |
1317
- | Game clock | `time/gameClock` | `getScaledElapsedMs`, `computeGameDay`, `SECONDS_PER_GAME_DAY` |
1318
- | Idle / offline catch-up | `time/idleProgress` | `idleWindow`, `linearCatchUp`, `exponentialCatchUp`, `steppedCatchUp`, `IdleWindow`, `IdleWindowConfig`, `SteppedCatchUpResult` — elapsed-real-time production/growth/decay for a game reopened after being closed |
1319
- | Scene behaviors | `scene/behaviors` | `wander`, `patrol`, `promptable`, `talkable`, `player` |
1320
- | Capture check | `scene/captureCheck` | `captureChance`, `rollCapture`, `CaptureCheckInput` |
1321
- | Owned roster | `scene/roster` | `createRoster`, `Roster`, `RosterEntry`, `RosterCaptureOptions` |
1322
- | Economy wallet | `economy/wallet` | `createEmptyWallet`, `balance`, `grant`, `charge`, `canAfford`, `chargeAll` |
1323
- | Tech tree | `economy/techTree` | `createTechTree`, `TechTree`, `TechNodeDef`, `canUnlockTech`, `availableTech`, `unlockedRecipes`, `grantTech`, `techPrerequisitesMet` |
1324
- | Recipe graph | `crafting/recipe` | `createRecipeGraph`, `RecipeGraph`, `RecipeDef`, `RecipeItem`, `canCraft`, `craft`, `missingInputs`, `stationSatisfied`, `craftSeconds` |
1325
- | Production building | `crafting/production` | `productionBuilding`, `ProductionBuildingDef`, `createProductionState`, `tickProduction`, `feedProduction`, `drainOutput`, `advanceTransport`, `resolvePowerGrid` |
1326
- | Crop tile / farming | `crafting/crop` | `createCropField`, `CropField`, `CropDef`, `CropTileState`, `tillTile`, `plantCrop`, `waterTile`, `advanceCropDay`, `harvestCrop`, `applyToolToTiles`, `squarePattern`, `diamondPattern`, `createDayTicker` |
1327
- | Skill-check roll | `stats/rollCheck` | `rollCheck`, `CheckInput`, `CheckResult`, `CheckAdvantage` |
1328
- | Input bindings (full) | `input/actionBindings` | `hotbarSlotBindings`, `actionLabel`, `bindingLabel`, `resolveActionCommand`, `bindingMatches`, `createActionStateTracker` |
1329
- | Touch controls | `input/touchScheme` | `deriveTouchScheme`, `touchCode`, `touchActionLabel`, `withTouchCodes`, `TouchControlsConfig`, `TouchGestureBindings`, `TouchDragBinding`, `TouchButtonSpec`, `TouchScheme`, `TouchJoystick`, `TouchButton` |
1330
- | Pointer hit | `input/pointer` | `PointerHit`, `PointerButton`, `aimToPoint`, `moveTargetFromHit`, `groundOf`, `PointerVec3` |
1331
- | Navmesh + A* | `nav/navGrid` | `createNavGrid`, `findPath`, `smoothPath`, `NavGrid`, `NavGridConfig`, `NavPoint`, `FindPathOptions` |
1332
- | Path follow | `nav/pathFollow` | `createPathFollow`, `advancePathFollow`, `pathFromNav`, `PathFollowConfig`, `PathFollowState`, `Waypoint` |
1333
- | Nav-grid movement constraint | `nav/navConstrain` | `constrainToNavGrid`, `NavConstrainProposed`, `NavConstrainEntity`, `NavConstrainOptions` — a standalone walkable-pass-through + wall-slide helper; adapt its `(proposed, entity)` shape to `PlayerMovementConfig.beforeCommit`'s `(frame) => [x,y,z]` with a small closure |
1334
- | Selection set | `scene/selection` | `createSelectionSet`, `SelectionSet`, `screenRect`, `selectWithinRect`, `rectContainsPoint`, `isMarquee`, `ScreenRect` |
1335
- | Context menu | `interaction/contextMenu` | `contextVerb`, `buildContextMenu`, `contextVerbInput`, `ContextVerb`, `ContextMenu` |
1336
- | Shared / group wallet | `economy/sharedWallet` | `createWalletBook`, `WalletBook`, `WalletScope`, `userScope`, `groupScope`, `balanceIn`, `grantTo`, `chargeFrom`, `contributionOf`, `contributorsOf` |
1337
- | Analog axis input | `input/axisInput` | `AxisInput`, `AxisChannel`, `AxisBindingMap`, `DRIVE_AXIS_BINDINGS`, `clampAxis`, `rampToward`, `NEUTRAL_AXIS` |
1338
- | Raw control polling | `runtime/inputSnapshot` | `createInputSnapshot`, `InputSnapshot` — backs `ctx.input` |
1339
- | Physics world | `physics/physicsWorld` | `PhysicsWorld`, `PhysicsWorldConfig`, `PhysicsBounds`, `PhysicsStats`, `AddBodyOptions` (`{ shape: "box", halfExtents }` \| `{ shape: "sphere", radius }`), `JointOptions`, `JointKind`, `CollisionEvent` |
1340
- | Ballistic collision sweep | `physics/ballisticSweep` | `createBallisticSweep`, `BallisticSweep`, `BallisticSweepHit`, `BallisticSweepOptions` |
1341
- | Tweening / easing | `anim/easing` | `Easing`, `lerp`, `clamp01`, `smoothstep`, `easeInQuad`, `easeOutQuad`, `easeInOutQuad`, `easeInCubic`, `easeOutCubic`, `easeInOutCubic`, `easeOutBack`, `easeOutElastic`, `tween`, `timedProgress` |
1342
- | Async data source | `data/dataSource` | `createDataSource`, `DataSource`, `DataSourceState`, `DataSourceStatus`, `DataSourceOptions`, `DataSourceClock`, `RefreshOptions` |
1343
- | JSON fetch | `data/fetchJson` | `fetchJson`, `FetchJsonOptions`, `FetchImpl`, `HttpStatusError`, `JsonParseError` |
1344
- | JSON data source | `data/jsonDataSource` | `createJsonDataSource`, `JsonDataSourceOptions` |
1345
- | Dev proxy routing | `data/devProxy` | `proxiedUrl`, `parseDevProxyTable`, `DevProxyTable`, `ProxiedUrlOptions`, `DEFAULT_DEV_PROXY_PREFIX` |
1346
- | Grid-cell world rendering | `world/gridInstances` | `resolveGridInstances`, `GridInstanceTransform` |
1347
- | Swarm LOD scheduler | `world/lod` | `createLodScheduler`, `LodScheduler`, `LodSchedulerConfig`, `LodBand` — distance→band index for render detail, `step(id, distance, dt)` throttles per-entity updates by band interval (staggered, accumulates skipped time); pairs with `@jgengine/shell/world/SpriteBatch` for 1000+ entity swarms |
1348
- | Turn loop | `turn/turnLoop` | `createTurnLoop`, `TurnLoop`, `TurnLoopConfig`, `TurnState`, `PoolConfig`, `PoolState`, `TurnLoopSnapshot` |
1349
- | Declared-action intent board | `turn/intent` | `createIntentBoard`, `IntentBoard`, `DeclaredIntent` — `declare(participantId, intent)`, `peek`, `all`, `consume`, `clear` |
1350
- | Commit modes | `turn/commit` | `createCommitController`, `CommitController`, `CommitMode`, `CommitOutcome`, `SubmittedAction` |
1351
- | Intent board | `turn/intent` | `createIntentBoard`, `IntentBoard`, `DeclaredIntent` |
1352
- | Tactical grid | `tactics/tacticalGrid` | `createTacticalGrid`, `TacticalGrid`, `TacticalGridConfig`, `Tile`, `ReachableTile`, `PushResult`, `PushCollision` |
1353
- | Predictive query | `tactics/predictiveQuery` | `predictAreaEffect`, `predictArcEffect`, `predictTiles`, `PredictiveDeps`, `PredictedTarget` |
1354
- | Sim snapshot | `tactics/snapshot` | `createSnapshotStore`, `SnapshotStore`, `SnapshotSlice`, `Snapshot`, `deepClone` |
1355
- | Surfaces | `tactics/surface` | `createSurfaceLayer`, `SurfaceLayer`, `SurfaceLayerConfig`, `SurfaceKindDef`, `SurfaceReaction`, `SurfaceEvent` |
1356
- | Area targeting | `combat/effects` | `resolveAreaTargets`, `AreaTarget`, `AreaTargetInput` (shared AoE targeting behind `effect` + the predictive query) |
1357
- | Environment field | `world/envField` | `createEnvironmentField`, `EnvironmentField`, `EnvironmentSample`, `EnvironmentFieldConfig`, `OccluderRect`, `HeatSource` |
1358
- | Weather + fire | `world/weather` | `resolveWeather`, `WeatherState`, `WeatherModifier`, `WeatherModifierTable`, `ResolvedWeather`, `createFireGrid`, `FireGrid`, `FireCell`, `FireGridConfig` |
1359
- | Realm composition | `world/realm` | `composeRealm`, `RealmCard`, `RealmBase`, `ComposedRealm`, `RealmEnvironmentParams`, `SpawnTableOverride` |
1360
- | Decay meters | `survival/decayMeter` | `createDecayMeterSet`, `DecayMeterSet`, `DecayMeterConfig`, `MeterThreshold`, `DecayMeterState` |
1361
- | Status moodles | `survival/moodle` | `createMoodleStack`, `stackMoodles`, `MoodleStack`, `Moodle`, `MoodleSeverity`, `TimedMoodleInput` |
1362
- | Multi-region health | `survival/regionHealth` | `createMultiRegionHealth`, `MultiRegionHealth`, `HealthRegionConfig`, `AilmentConfig`, `RegionHealthState`, `AilmentInstance` |
1363
- | Audio contract | `audio/audioFalloff` | `computeFalloffGain`, `resolveEmitterGain`, `distance3`, `AudioFalloffConfig`, `FalloffCurve`, `SoundDef`, `AudioBusDef`, `AudioBusId` |
1364
- | Beat clock | `time/beatClock` | `createBeatClock`, `createBeatInputBuffer`, `nextBeatTime`, `BeatClock`, `BeatClockConfig`, `BeatSnapshot`, `BeatInputBuffer`, `BufferedAction` |
1365
- | Spawn director | `ai/spawnDirector` | `createSpawnDirectorState`, `advanceSpawnDirector`, `advanceWave`, `raiseAlert`, `pickSpawnPoint`, `SpawnDirectorConfig`, `WaveManifest`, `SpawnEntry`, `SpawnRequest`, `DirectorContext` |
1366
- | Threat table | `ai/threat` | `createThreatTable`, `ThreatTable`, `ThreatTableConfig`, `ThreatEntry`, `HighestThreatOptions` |
1367
- | Group-assist aggro | `ai/groupAssist` | `createAssistNetwork`, `AssistNetwork`, `AssistNetworkConfig`, `AssistMember` — propagates one member's threat gains to same-group members (optional radius + `distanceBetween` gating) so a single pull rallies the group |
1368
- | Job board | `ai/jobBoard` | `createJobBoard`, `JobBoard`, `JobDef`, `Job`, `JobPhase`, `WorkerState`, `JobReport`, `JobTickContext` |
1369
- | Crowd flow | `ai/crowd` | `computeFlowField`, `createCrowdField`, `selectPoi`, `FlowField`, `FlowFieldOptions`, `CrowdField`, `Poi`, `SelectPoiOptions` |
1370
- | Factions & reputation | `faction/factions`, `faction/reputation` | `createFactionGraph`, `createFactionRoster`, `FactionRelation`, `FactionDef`, `FactionGraph`, `FactionRoster`, `createReputationLedger`, `DEFAULT_REPUTATION_TIERS`, `tierForStanding`, `effectiveRelation`, `ReputationTier`, `ReputationLedger` |
1371
- | Physics actors | `physics/ragdoll`, `physics/carryable`, `physics/forceVolume`, `physics/spatialGrid` | `createRagdoll`, `Ragdoll`, `Carryable`, `carrySpeedMultiplier`, `ForceVolume`, `PlatformCarry`, `SpatialGrid` |
1372
- | Traversal (grapple/glide) | `physics/traversal` | `Grapple`, `GrappleConfig`, `Glide`, `GlideConfig` |
1373
- | Structural destruction | `physics/structure` | `StructureGraph`, `StructureNodeSpec`, `StructureEdgeSpec`, `StructureMaterial`, `StructureMaterialTable`, `CollapseEvent`, `DebrisConfig` |
1374
- | Destructible terrain | `world/carve` | `VoxelVolume`, `VoxelMaterial`, `VoxelMaterialTable`, `CarvableField`, `carvableTerrain`, `CarveOp`, `DepositOp`, `CraterOp`, `MoundOp`, `EMPTY_VOXEL` |
1375
- | Vehicle body | `physics/vehicleBody` | `createVehicleBody`, `VehicleBody`, `VehicleBodyConfig`, `WheelSpec`, `GripCurve`, `sampleGripCurve`, `DEFAULT_GRIP_CURVE` |
1376
- | Buoyant boat | `physics/buoyancy` | `createBuoyantBody`, `BuoyantBody`, `BuoyantBodyConfig` |
1377
- | Crash damage | `physics/damageZones` | `createDamageModel`, `DamageModel`, `DamageZoneDef`, `DamageTransition` |
1378
- | Mounts / rideables | `scene/mount` | `createMountController`, `MountController`, `MountKit`, `MountSeat`, `RideableConfig` |
1379
- | Shared-vehicle stations | `scene/stationClaim` | `createStationClaim`, `StationClaim`, `Station`, `SharedVehicleConfig`, `ClaimResult` |
1380
- | Lag compensation | `multiplayer/lagCompensation` | `createPositionHistory`, `PositionHistory`, `rewindTimestamp`, `resolveHitscan`, `raySphereDistance`, `HitscanRay`, `HitscanTarget` |
1381
- | Simultaneous commit | `multiplayer/simultaneousCommit` | `createCommitRound`, `CommitRound`, `SealedCommit`, `resolveCommits` |
1382
- | Combat-snapshot replay | `multiplayer/combatSnapshot` | `serializeBoard`, `cloneSnapshot`, `replayCombat`, `BoardSnapshot`, `SnapshotUnit`, `CombatRules`, `ReplayResult` |
1383
- | Session matchmaking | `multiplayer/matchmaking` | `browseSessions`, `findByJoinCode`, `quickMatch`, `matchesFilter`, `normalizeJoinCode`, `generateJoinCode`, `SessionListing`, `MatchFilter` |
1384
- | Auth identity | `multiplayer/identity` | `AuthSession`, `PlayerIdentity`, `sessionPlayer`, `resolveGuestSession` |
1385
- | Text chat | `game/chat`, `multiplayer/chatContract` | `createChat`, `Chat`, `ChatMessage`, `ChatChannelDef`, `whisperChannelId`, `createChatRateLimiter`, `ChatTransport`, `ChatSync`, `createLocalChatTransport` |
1386
- | Chat filter | `game/chatFilter` | `createChatFilter`, `normalizeChatText`, `ChatFilter`, `ChatFilterConfig`, `ChatFilterResult` — mask/reject blocked words (leet-normalized token match); wire via `ChatDeps.filter` (word lists are game data, the engine ships the mechanism) |
1387
- | Voice seam | `multiplayer/voiceContract` | `VoiceTransport`, `VoiceParticipant`, `VoiceRoute`, `createLocalVoiceTransport`, `createPushToTalk`, `PushToTalkMode` |
1388
- | Race state | `game/race` | `raceTrack`, `RaceTrack`, `createRaceState`, `RaceState`, `RaceEvent`, `RaceWinCondition`, `firstPastPost`, `topK`, `lastStanding`, `everyoneFinishes` |
1389
- | Reveal query | `sensor/revealQuery` | `createRevealQuery`, `RevealQuery`, `RevealQueryOptions`, `RevealHit` |
1390
- | Hidden-state probe | `sensor/hiddenStateProbe` | `probeHiddenState`, `probeHiddenStateAll`, `HiddenStateSource`, `HiddenStateValue`, `SensorProbeOptions`, `SensorReading` |
1391
- | View-frustum sensor | `sensor/frustumSensor` | `createFrustumSensor`, `projectToView`, `framingScore`, `FrustumCamera`, `FrustumTarget`, `FrustumProjection`, `FrustumSample`, `FrustumSensor`, `FramingConfig` |
1392
- | Recording buffer | `sensor/recordingBuffer` | `createRecordingBuffer`, `RecordingBuffer`, `RecordingFrame`, `RecordingBufferOptions` |
1393
- | Concealment scoring | `sensor/concealment` | `colorDistance`, `concealmentScore`, `createConcealmentSensor`, `ColorHex`, `ConcealmentTarget`, `ConcealmentSample`, `ConcealmentSensor` |
1394
- | Freeze violation monitor | `sensor/freezeMonitor` | `createFreezeMonitor`, `FreezeMonitor`, `FreezeSubject`, `FreezeViolation` |
1395
- | Animation SM | `combat/animationState` | `createAnimationState`, `AnimationState`, `AnimationClip`, `FramePhase`, `FrameRange`, `phasesAtFrame`, `activeRangeAtFrame`, `frameAtMs` |
1396
- | Accumulator meter | `stats/accumulatorMeter` | `createAccumulatorMeter`, `AccumulatorMeter`, `AccumulatorMeterConfig`, `MeterTier`, `MeterAddResult`, `tierAt` |
1397
- | Stagger / buildup | `combat/breakMeters` | `createStaggerMeter`, `createBuildupMeter`, `StaggerMeter`, `BuildupMeter`, `BuildupProc` |
1398
- | Attack tags | `combat/attackTags` | `attackMeta`, `AttackTag`, `AttackMeta`, `hasTag`, `isBlockable`, `isParryable`, `isDodgeable`, `counters` |
1399
- | Defensive window | `combat/defensiveWindow` | `createDefensiveWindow`, `resolveDefense`, `DefensiveWindowConfig`, `DefenseKind`, `DefenseOutcome`, `windowActiveAt`, `iframeActiveAt` |
1400
- | Combo string | `combat/comboString` | `createComboRunner`, `advanceCombo`, `ComboString`, `ComboStep`, `AdvanceComboResult` |
1401
- | Hit reaction | `combat/hitReaction` | `resolveHitReaction`, `HitReaction`, `HitReactionConfig`, `CameraShake`, `applyImpulse` |
1402
- | Telegraph | `combat/telegraph` | `pointInTelegraph`, `telegraphProgress`, `telegraphFired`, `telegraphTurnProgress`, `telegraphFiredAtTurn`, `telegraphTurnsRemaining`, `TelegraphShape`, `TelegraphConfig` |
1403
- | Dash / dodge | `movement/dash` | `createDashState`, `DashState`, `DashConfig`, `DashBurst`, `iframeActive`, `dashOffset` |
1404
- | Ability kit | `combat/abilityKit` | `createAbilityKit`, `AbilityKit`, `AbilitySlotConfig`, `AbilitySlotSnapshot`, `AbilitySlotState`, `AbilityCastType`, `AbilityCastResult`, `AbilitySlotRetune` |
1405
- | Resource pool | `combat/resourcePool` | `createResourcePool`, `ResourcePool`, `ResourcePoolConfig` — current/max with per-second regen/decay and spend/gain; `pool.current()` is the ability kit's `resourceAvailable` |
1406
- | Combo points | `combat/comboPoints` | `createComboPoints`, `ComboPoints`, `ComboPointsConfig` — discrete points accrued on action, expiring after a timeout from the last gain, spent in bulk |
1407
- | Event meter | `stats/eventMeter` | `createEventMeter`, `EventMeter`, `EventMeterConfig`, `EventMeterFeedResult` |
1408
- | Auto-target policy | `scene/autoTarget` | `selectAutoTarget`, `createAutoTargeter`, `AutoTargetPolicy`, `AutoTargeter`, `AutoTargetDeps` |
1409
- | Resistance matrix | `combat/resistance` | `resolveResistance`, `resistanceScale`, `ResistanceMatrix`, `ResistVerdict`, `ResistanceResult` |
1410
- | Run draft | `game/runDraft` | `createRunDraft`, `createRunModifierStack`, `RunDraft`, `RunModifierStack`, `RunModifierOffer` |
1411
- | Uniform-cell grid | `puzzle/cellGrid` | `CellGrid`, `CellRun`, `createCellGrid`, `cellAt`, `inGridBounds`, `withCell`, `withCells`, `fullRows`, `clearRows`, `collapseColumns`, `findRuns` |
1412
- | Falling piece | `puzzle/fallingPiece` | `FallingPiece`, `ShapeTable`, `LockDelayState`, `pieceCells`, `pieceCollides`, `mergePiece`, `dropDistance`, `gravityInterval`, `levelForLines`, `lineScore`, `createLockDelay`, `stepLockDelay` |
1413
- | Falling tile grid | `tactics/fallingGrid` | `createFallingGrid`, `FallingGrid`, `FallingGridConfig`, `FallingGridCell`, `FallingGridSnapshot`, `LockState`, `gravityIntervalMs`, `GravityIntervalConfig` — a generic tile-drop grid (any `TCell` payload), distinct from `puzzle/cellGrid`+`puzzle/fallingPiece`'s row-clear/shape-table pair |
1414
- | Spawn/respawn points | `game/spawnPoints` | `createSpawnPoints`, `SpawnPoints`, `SpawnPointPose`, `RespawnTarget` |
1415
- | Level sequence | `game/levelSequence` | `createLevelSequence`, `LevelSequence`, `LevelSequenceConfig`, `LevelDescriptor`, `CurrentLevel`, `LevelSequenceStatus`, `LevelSequenceProgress` |
1416
- | Devtools overlay + tunables | `devtools/devtools` | `devtools`, `createDevtools`, `tunable`, `snapshotDevtools`, `instrumentLatency`, `Tunable`, `TunableOptions`, `TunableAccessor`, `DevtoolsControl`, `DiscoveredEntry`, `DevtoolsOverrides`, `DevtoolsSnapshot` |
1417
- | Tunable auto-discovery | `devtools/transformTunables` | `transformTunableExports`, `tunableModuleTable`, `tunableDiscoveryPlugin`, `TunableTransformResult` |
1418
-
1419
- ## Getting started (new project)
1420
-
1421
- Fastest path — the `jgengine` CLI scaffolds the entire canonical shape below (harness, skeleton, stub game, verify test, AGENTS.md) as a booting game:
1422
-
1423
- ```sh
1424
- npx jgengine create my-game # then: cd my-game && bun dev
1425
- npx jgengine doctor # later, if the setup drifts (version skew, unstyled HUD, shape strays)
1426
- ```
1427
-
1428
- Manual equivalent:
1429
-
1430
- ```sh
1431
- bun add @jgengine/core @jgengine/react @jgengine/shell react react-dom three three-stdlib @react-three/fiber @react-three/drei
1432
- bun add -d @tailwindcss/vite tailwindcss # HUD styling (Vite + Tailwind v4)
1433
- ```
1434
-
1435
- A single game's standalone entry mounts `GameHost` (`@jgengine/shell/GameHost`) over the `game` your `game.config.ts` exports. The full standalone harness is four small files plus a script — this is exactly the shape every `Games/*` game ships, so `bun dev` plays it on its own with no host app:
1436
-
1437
- ```html
1438
- <!-- index.html -->
1439
- <!doctype html>
1440
- <html lang="en">
1441
- <head>
1442
- <meta charset="UTF-8" />
1443
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1444
- <title>My Game</title>
1445
- </head>
1446
- <body>
1447
- <div id="root"></div>
1448
- <script type="module" src="/src/main.tsx"></script>
1449
- </body>
1450
- </html>
1451
- ```
1452
-
1453
- ```ts
1454
- // vite.config.ts — monorepo-aware: the alias branch only fires when this folder
1455
- // sits inside the engine repo checkout; copied anywhere else, @jgengine/* resolves
1456
- // from npm dist and the alias list is empty
1457
- import { existsSync } from "node:fs";
1458
- import { fileURLToPath } from "node:url";
1459
- import tailwindcss from "@tailwindcss/vite";
1460
- import react from "@vitejs/plugin-react";
1461
- import { defineConfig } from "vite";
1462
-
1463
- const engineSrc = (pkg: string) => fileURLToPath(new URL(`../../packages/${pkg}/src`, import.meta.url));
1464
-
1465
- export default defineConfig({
1466
- plugins: [react(), tailwindcss()],
1467
- resolve: {
1468
- alias: existsSync(engineSrc("core"))
1469
- ? [
1470
- { find: /^@jgengine\/core\/(.*)$/, replacement: `${engineSrc("core")}/$1` },
1471
- { find: /^@jgengine\/react\/(.*)$/, replacement: `${engineSrc("react")}/$1` },
1472
- { find: /^@jgengine\/ws\/(.*)$/, replacement: `${engineSrc("ws")}/$1` },
1473
- { find: /^@jgengine\/shell\/(.*)$/, replacement: `${engineSrc("shell")}/$1` },
1474
- { find: /^@jgengine\/assets$/, replacement: `${engineSrc("assets")}/index.ts` },
1475
- { find: /^@jgengine\/assets\/(.*)$/, replacement: `${engineSrc("assets")}/$1` },
1476
- ]
1477
- : [],
1478
- },
1479
- });
1480
- ```
1481
-
1482
- ```css
1483
- /* src/index.css */
1484
- @import "tailwindcss";
1485
- @source "../node_modules/@jgengine/react/dist";
1486
- @source "../node_modules/@jgengine/shell/dist";
1487
- ```
1488
-
1489
- Inside the engine repo the two `@source` lines point at `../../../packages/react/src` and `../../../packages/shell/src` instead (see any `Games/*/src/index.css`) — same file, different `@source` targets depending on where dist lives.
1490
-
1491
- ```tsx
1492
- // main.tsx
1493
- import "./index.css";
1494
-
1495
- import { createRoot } from "react-dom/client";
1496
- import { GameHost } from "@jgengine/shell/GameHost";
1497
- import { game } from "./game.config";
1498
-
1499
- const root = document.getElementById("root");
1500
- if (root === null) throw new Error("main: missing #root mount element");
1501
- createRoot(root).render(<GameHost playable={game} />);
1502
- ```
1503
-
1504
- Add `"dev": "vite"` to `package.json`'s `scripts` — `bun dev` then launches the game standalone.
1505
-
1506
- `GameHost` resolves multiplayer itself from `game.multiplayer` (falling back to offline when the adapter can't resolve, with a console warning) — pass `multiplayer` (a prebuilt `ShellMultiplayer | null`, used as-is with no resolution attempted) or `resolveMultiplayer` (`(args) => ShellMultiplayer | null`, tried before the built-in resolver, falling back to it on `null`) only when the host app needs to supply its own session, e.g. trying several transports in sequence.
1507
-
1508
- A multi-game host (a launcher, a dev registry) wires `GamePlayer` over a `GameRegistry`:
1509
-
1510
- ```tsx
1511
- import { GamePlayer } from "@jgengine/shell/GamePlayer";
1512
- import type { GameRegistry } from "@jgengine/shell/registry";
1513
-
1514
- const games: GameRegistry = {
1515
- "my-game": () => import("./my-game").then((m) => m.game),
1516
- };
1517
-
1518
- function App() {
1519
- return <GamePlayer gameId="my-game" registry={games} loading={<p>Loading…</p>} />;
1520
- }
1521
- ```
1522
-
1523
- `GamePlayer({ gameId, registry, fallbackGameId?, loading?, multiplayer? })` (`@jgengine/shell/GamePlayer`) is `GamePlayerShell` plus the lazy-load glue: it looks up `gameId` in `registry`, awaits the loader, renders `loading` (default `null`) until it resolves, then mounts `GamePlayerShell playable={...} multiplayer={...}`; switching `gameId` re-triggers the load, and an in-flight load is discarded if the id changes again first. `resolveGameLoader(registry, gameId, fallbackGameId?)` (`@jgengine/shell/registry`) is the underlying lookup — `registry[gameId] ?? registry[fallbackGameId]` — for hosts that want the fallback behavior without the component.
1524
-
1525
- HUD styling is Tailwind v4 via the `index.css` above — without its `@source` lines the HUD renders unstyled. Then build the game itself under `src/` per the layout below — `src/game.config.ts` is the single entry, defined with `defineGame` from `@jgengine/shell/defineGame`.
1526
-
1527
- ## Scope
1528
-
1529
- This file documents engine primitives and conventions only — never game domain. Example ids (`iron_block`, `mob_grunt`, `shop_town`) are placeholders, not content to copy.
1530
-
1531
- | Engine owns | Your game owns |
1532
- |-------------|----------------|
1533
- | Weighted loot RNG, trade validation, loadout application, quest journal state, social graph, stat clamp math, effect absorption, projectile geometry, death resolution, event bus, feeds, leaderboards, input capture, pose hitboxes | Catalog entries and ids, effect id names, XP curves, shop/item/quest/loadout definitions, use-handlers, AI logic, UI content |
1534
-
1535
- **Rules:**
1536
-
1537
- 1. **Catalog-first** — shape and behavior of every id lives in game-owned catalog files. Runtime calls pass ids, positions, instance keys.
1538
- 2. **Three buckets** — inventory items, scene objects, scene entities. Never merge them.
1539
- 3. **Dumb place/spawn** — no behaviors on `place()`/`spawn()`; the catalog owns them.
1540
- 4. **Commands for verbs** — input maps to actions, actions to commands/handlers; no raw keys in game logic.
1541
- 5. **Primitives over glue** — a loop several games need (loot roll, shop buy, kit seeding) belongs in the engine, not copy-pasted per game.
1542
- 6. **No speculative config** — `defineGame` fields exist only with a live engine consumer.
1543
- 7. **This file stays domain-free.**
1544
-
1545
- ## The three buckets
1546
-
1547
- | Bucket | What | API |
1548
- |--------|------|-----|
1549
- | **Inventory** | Stackable ids in containers | `ctx.player.inventory.put / take / move / has / count` |
1550
- | **Scene object** | Static world content | `ctx.scene.object.place / remove / move / rotate / list` |
1551
- | **Scene entity** | Movers driven per tick | `ctx.scene.entity.spawn / despawn / setPose / effect / …` |
1552
-
1553
- A voxel block is an object. A rack is an object with a slot inventory. A GPU is an inventory item inside it. A player, mob, or car is an entity. A dropped-item lying on the ground is also an entity — `ctx.scene.worldItem` (position + item ref + rarity, spawned under `game/worldItem`'s `WORLD_ITEM_ENTITY_NAME`) — never a fourth bucket and never merged into inventory or object.
1554
-
1555
- ## Game repo layout
1556
-
1557
- Every game is one shape, enforced by `check-game-shape` (part of `check-types`): the top of `src/` holds only the skeleton, and every game-specific module, UI component, and test lives under `src/game/`. In this repo the gate also requires a root `package.json` script `"games:<id>": "bun run --cwd Games/<id> dev"` for every `Games/*` directory — add it with the scaffold, or the very first `check-types` fails before the compiler even runs. Dense files — one `catalog.ts` per domain, never one file per entry.
1558
-
1559
- ```
1560
- src/
1561
- game.config.ts single entry — export const game = defineGame({...}) from "@jgengine/shell/defineGame"
1562
- index.tsx barrel — export { game } from "./game.config" (+ any UI-preview scenario re-export)
1563
- main.tsx standalone host — mounts <GameHost playable={game}/> from "@jgengine/shell/GameHost"
1564
- loop.ts onInit, onNewPlayer, onTick
1565
- world.ts WorldFeature + PhysicsConfig (only for games that have one)
1566
- game/
1567
- keybinds.ts ActionCodesMap — named actions + hotbarSlotBindings(n)
1568
- inventories.ts inventory declarations
1569
- assets.ts Render catalog
1570
- content.ts itemById / entityById lookups over all catalogs
1571
- loadouts.ts Loadout ids → items/economy/unlocks per inventory
1572
- world/ zones.ts, setup.ts (place/spawn from onInit)
1573
- items/ <domain>/catalog.ts + use-handlers.ts
1574
- objects/ catalog.ts (+ loot tables beside their domain)
1575
- entities/ players/ enemies/ npcs/ — catalog.ts per role (never actors/)
1576
- quests/catalog.ts when using game.quest
1577
- progression/ curves.ts — game-owned XP curve numbers fed to game/progression
1578
- ui/GameUI.tsx ALL layout/positioning
1579
- ui/components/ content-only pieces GameUI places
1580
- ```
1581
-
1582
- ## `defineGame` — the single authoring entry
1583
-
1584
- `@jgengine/shell/defineGame` is the game-authoring entry: one call in `game.config.ts` takes both engine fields (`name`, `assets`, `world`, `physics`, `inventories`, `input`, `server`, `save`, `time`, `feed`, `multiplayer`) and presentation fields (`content`, `loop`, `GameUI`, `camera`, `environment`, `WorldOverlay`, `renderEntity`, `renderObject`, `entitySprites`, `entityModels`, `objectModels`, `hotbarSelection`, `prompts`, `pointer`, `touch`, `worldHealthBars`, `audio`, `entitySounds`, `objectSounds`, `worldItem`, `shadows`, `collision`, `movement`, `devtools`) and returns a ready `PlayableGame` — no separate object to assemble. It is a thin wrapper over the core `defineGame` primitive (below) plus the `PlayableGame` runner assembly; see `packages/shell/src/defineGame.tsx` for the exact accepted fields. Never game tuning (walk speeds, damage, prompts — those live in catalogs).
1585
-
1586
- **Smart defaults** — omit any of these and the call still resolves: `multiplayer` → `offline()`; `assets` → an empty asset catalog; `loop` hooks (`onInit`/`onNewPlayer`/`onTick`) → no-ops; `content` → `{}`; `GameUI` → an empty component; `camera` → third-person orbit; `feed` → 20-entry ring buffers per action; a `world` of kind `environment()` auto-renders as the backdrop with no `environment` component supplied — a non-`environment()` world (`flat()`, `voxel()`, …) still needs the game to hand it one.
1587
-
1588
- **Opt-in `ctx.game.*` subsystems (`features`)** — core is genre-agnostic: the always-on base is `commands` / `events` / `store` / `feed` (plus `audio`), and genre subsystems are opt-in via `defineGame({ features: { roster, cards, turn, race, leaderboard, social, chat } })`. Omit one and `ctx.game.<name>` is `undefined` — a puzzle game isn't handed a card pile, race state, or party/chat it never asked for. Declare only what the game uses (`chat` implies `social`). (The content cluster — economy/quest/loot/trade — joins this manifest in a later slim-core phase.)
1589
-
1590
- ```ts
1591
- // game.config.ts — imports only, nothing inline
1592
- import { defineGame } from "@jgengine/shell/defineGame";
1593
- import { assets } from "./game/assets";
1594
- import { content } from "./game/content";
1595
- import { GameUI } from "./game/ui/GameUI";
1596
- import { inventories } from "./game/inventories";
1597
- import { keybinds } from "./game/keybinds";
1598
- import { loop } from "./loop";
1599
- import { physics, world } from "./world";
1600
-
1601
- export const game = defineGame({
1602
- name: "My Game",
1603
- assets,
1604
- world,
1605
- physics,
1606
- inventories,
1607
- input: keybinds,
1608
- server: "persistent", // or { mode: "ffa", scoreLimit: 30 } — rules live in game code
1609
- save: { auto: "5m", scope: "player+chunks" }, // or "none"
1610
- multiplayer: offline(), // or ws({ topology, url? }) / fly({ app }) / convex({ topology }) / socketIo({ topology, url? }) / p2p({ room? }) / lan({ port?, path? }) / servers({ …, adapter }) — defaults to offline()
1611
- content,
1612
- loop, // Partial<GameLoop<GameContext>> — missing hooks default to no-ops
1613
- GameUI,
1614
- camera: { perspective: "third" }, // optional — this is the default
1615
- });
1616
- ```
1617
-
1618
- ```ts
1619
- // game/keybinds.ts — named actions + generated hotbar slots; one key, one action
1620
- import { hotbarSlotBindings, type ActionCodesMap } from "@jgengine/core/input/actionBindings";
1621
-
1622
- export const keybinds: ActionCodesMap = {
1623
- moveForward: ["KeyW"], moveBack: ["KeyS"], moveLeft: ["KeyA"], moveRight: ["KeyD"],
1624
- jump: ["Space"], sprint: ["ShiftLeft"],
1625
- interact: ["KeyE"],
1626
- crouch: { hold: ["KeyC"], toggle: ["KeyZ"] },
1627
- aim: { hold: ["mouse2"], toggle: ["KeyV"] },
1628
- tabTarget: ["Tab"], clearTarget: ["Escape"],
1629
- ...hotbarSlotBindings(9), // hotbarSlot1..9 → Digit1..9 (a 10th slot gets Digit0)
1630
- };
1631
- ```
1632
-
1633
- ```ts
1634
- // game/inventories.ts
1635
- import type { InventoryDeclaration } from "@jgengine/core/game/defineGame";
1636
- export const inventories: Record<string, InventoryDeclaration> = {
1637
- hotbar: { slots: 9, hud: "hotbar" },
1638
- backpack: { slots: 28, traits: itemTraits },
1639
- equipment: { slots: 4, accepts: ["weapon", "armor"], applyModifiers: true },
1640
- };
1641
-
1642
- // world.ts — top of src/, not under game/
1643
- import type { PhysicsConfig } from "@jgengine/core/game/defineGame";
1644
- import { biomes, type WorldFeature } from "@jgengine/core/world/features";
1645
- export const world: WorldFeature = biomes({ map: "world/biomes", zones: "world/zones" });
1646
- export const physics: PhysicsConfig = { gravity: -32 };
1647
- ```
1648
-
1649
- - `PhysicsConfig.gravity`/`jumpVelocity` tune the shell's built-in walk controller's fall/jump feel (defaults ~`-24`/`7.1`) — the only two levers on gravity and jump height; everything else about movement (speed, poses) stays catalog `movement` fields.
1650
- - Input bindings are string arrays (hold semantics) or `{ hold, toggle, repeatMs? }` for the same verb. `repeatMs` turns a held action into an auto-repeat fire (build-mode place-on-drag, rapid-fire without a separate `wasPressed`/interval combo in game code) — the shell refires the command every `repeatMs` while the binding stays down, on top of its normal press-edge fire.
1651
- - **Keybind → command convention.** The shell fires a command for any bound action that isn't reserved: pressing an action runs a command of the **same name** if one is defined, else a `ui.<action>` fallback (so `openBackpack` → `ui.openBackpack`). Just declare the binding and a matching command — no per-game `keydown` listener. Reserved actions the shell consumes natively and never routes to a command: `moveForward/moveBack/moveLeft/moveRight`, `turnLeft/turnRight`, `sprint`, `jump`, `tabTarget`, `clearTarget`, `useAbility`, `interact`, and any `hotbarSlotN`/`slotN`. `tabTarget`/`clearTarget` run `target.cycle`/`target.clear` (native `cycleTarget`/`setTarget` fallback). Because `hotbarSlotN` never reaches a command, a game that drives selection from game code binds its own `selectSlot1..N` actions, defines matching commands that write a store key, and reads it back through `hotbarSelection: () => ...` on `defineGame` (see `loot-shooter`).
1652
- - **`interact`** is special: pressing it resolves the active proximity prompt from the `prompts` field of `defineGame({...})` and runs that prompt's `invoke` command. A prompt with `invoke: null` is display-only and does nothing on the key.
1653
- - UI keybind badges derive from `keybinds` via `actionLabel(keybinds, "openBackpack")` — `bindingLabel` maps codes to short labels (`Digit1`→`1`, `KeyB`→`B`, `mouse0`→`LMB`, `Escape`→`Esc`). Never hardcode label strings; they drift the moment a binding changes.
1654
- - `server.mode` is a string your loop/commands interpret — the engine ships no gamemode presets.
1655
- - Never in defineGame: player tuning, catalog helpers (`defineItems` etc.), game nouns, behaviors, prompts, or inline binding/inventory/world blobs. The one exception is `physics.gravity`/`physics.jumpVelocity` — global controller tuning, not a catalog value (see "Controller kinematics" below).
1656
- - `assets` may be omitted for a game with no models (a HUD-only card/board game, say) — `defineGame` injects an empty catalog, so `GameDefinition.assets` is always present downstream with no per-caller `?.` checks.
1657
- - `devtools` defaults to `true` — every game gets the F2-toggled debug overlay (Perf/Tune/Logs/Net/Keys) for free, and every top-level `export const` number/boolean/color and every exported flat table of them under `src/` is auto-discovered into the Tune tab with zero game code; set `false` to disable the toggle entirely. See "Devtools — F2 overlay and tunables" below.
1658
-
1659
- ### `@jgengine/core/game/defineGame` — the underlying primitive
1660
-
1661
- The low-level engine boot call the shell `defineGame` composes internally: engine fields only (`name`, `assets`, `world`, `physics`, `inventories`, `input`, `server`, `save`, `time`, `feed`, `multiplayer`, `loop`) — no `content`/`GameUI`/`camera`/render fields, those are the shell layer's job.
1662
-
1663
- ```ts
1664
- import { defineGame as defineEngineGame } from "@jgengine/core/game/defineGame";
1665
- import { offline } from "@jgengine/core/runtime/adapter";
1666
-
1667
- const game = defineEngineGame({
1668
- name: "My Game",
1669
- assets, world, physics, inventories,
1670
- input: keybinds,
1671
- server: "persistent",
1672
- save: { auto: "5m", scope: "player+chunks" },
1673
- multiplayer: offline(),
1674
- loop, // GameLoop<GameContext>
1675
- });
1676
- ```
1677
-
1678
- Reach for this directly only outside a React host — a headless server, a non-shell runner; a browser game authors through `@jgengine/shell/defineGame` above, which calls this and returns the `PlayableGame` a runner needs.
1679
-
1680
- ## `PlayableGame` — how a game plugs into a runner
1681
-
1682
- The type `@jgengine/shell/defineGame` returns and every runner (`GameHost`, `GamePlayerShell`) consumes. A game never builds this object by hand — `defineGame({...})` assembles it from the merged config. Source type at `@jgengine/core/game/playableGame`:
1683
-
1684
- ```ts
1685
- export type PlayableGame<TUi = unknown> = {
1686
- game: GameDefinition;
1687
- content: GameContextContent; // { itemById?, entityById?, objectById? }
1688
- loop: Required<GameLoop<GameContext>>; // onInit, onNewPlayer, onTick
1689
- GameUI: TUi; // React component in web runners
1690
- prompts?: (ctx: GameContext) => readonly PositionedPrompt[]; // interact-key + HUD source
1691
- };
1692
- ```
1693
-
1694
- `prompts` is the **single source** of positioned proximity prompts: the shell reads it to fire the `interact` key, and the HUD should read the same list through `useActivePrompt(playable.prompts?.(ctx))` rather than building its own — one list, no drift. A prompt is only actionable if its `invoke` is non-null.
1695
-
1696
- Optional render/world fields the shell also reads: `entitySprites` / `entityModels` (billboards / GLBs keyed by entity kind), `objectModels` (GLBs keyed by object catalog id), `renderObject` (per-object visual override — return your own mesh for a placed object and the shell still positions it; falls back to `objectModels` → colored box), `WorldOverlay` (canvas-layer VFX), `environment` (canvas-layer scenery — ground/sky/structures; when set, replaces the default ground plane + debug grid + rock field), `camera`, `shadows` (cast/receive shadows across the R3F canvas; default true), and `worldHealthBars` (`boolean | { statId?, roles? }` — `roles` restricts bars to entities whose catalog `role` is in the given `CatalogEntityRole` list, e.g. skip friendly NPCs). A model value is a catalog id (`string`, resolved via `game.assets`) or an inline `ModelConfig { url, scale?, y?, anchor?, dims?, material?, animation? }` (`material` overrides color/metalness/roughness/emissive/emissiveIntensity on the cloned mesh, leaving shared GLTF caches untouched; `animation?: { clip?, loop?, timeScale?, paused?, time? }` plays a GLTF clip — `clip` defaults to the first clip, `loop` defaults true — and `paused: true` + `time: <seconds>` holds the rig on one fixed frame, a pose library for inventory previews or held cutscene poses). Catalog-resolved models carry measured `dims` (`catalog.resolve(id).dims = { footprint:{w,d}, center:{x,z}, minY }`); with the default `anchor: "center"` the shell centers the footprint on the placement point and ground-snaps `minY` to it, so corner-pivot kit models place correctly with no per-game pivot math. Applies through both `entityModels` and `objectModels`.
1697
-
1698
- `renderEntity?: (entity: SceneEntity) => ReactNode` and `renderObject?: (object: SceneObject) => ReactNode` hand you the mesh for one entity/object while the shell still positions it and keeps it tagged for picking/selection; return null/undefined to fall through to model → sprite/box. `objectStyles?: Record<catalogId, { color?, opacity?, hidden? }>` styles the default colored-box object render — `color` overrides the hash color, `opacity < 1` sets transparent, `hidden` skips the mesh but keeps the picking tag.
1699
-
1700
- **Presentation mode.** `PlayableGame.presentation`: `"3d"` (default) mounts the canvas, camera rig, and pointer; `"hud"` mounts none of that — the game is `GameUI` plus the command/input loop, for board/card/menu games that need no 3D camera at all.
1701
-
1702
- **Auto environment.** When `world` is an `environment()` descriptor and `PlayableGame.environment` is unset, the shell renders that descriptor as the backdrop automatically — no manual `environment` wiring needed for the common case. Set `environment` explicitly only to override that default (a custom canvas component always wins). The same auto-render convention covers grid-cell worlds (`biomes`/`voxel`/`plots`/`tilemap`) — see "World features" below.
1703
-
1704
- **Lighting and backdrop.** `PlayableGame.lighting` (`LightingConfig`, `@jgengine/core/game/playableGame`) replaces the shell's hardcoded ambient/directional default when present, regardless of world kind: `ambient?: { color?, intensity? }`, `directional?: { color?, intensity?, position, castShadow? }[]`, `hemisphere?: { skyColor?, groundColor?, intensity? }`. `PlayableGame.backdrop` (`BackdropConfig`) is a generic background/sky/fog for **any** world kind, including a custom `environment` component: `background?: string` (CSS color), `sky?: SkyEnvironmentConfig` (same descriptor `environment()`'s `sky` field takes), `fog?: { color?, near?, far?, density? }` (`density` set switches to exponential `FogExp2` and `near`/`far` are ignored). Both are optional and additive to whatever the world/`environment` renderer already draws.
1705
-
1706
- **Visibility & streaming (automatic).** Every 3D game gets camera frustum + distance culling for free — the shell's `CullingProvider` reads the live camera each frame, runs the engine `createVisibilitySystem` (`@jgengine/core/visibility/visibilitySystem`) over the scene's entities and placed objects, and toggles `group.visible` so off-screen objects are never submitted to the renderer (never unmounted — gameplay and simulation are untouched). Defaults are conservative (a preload margin larger than the view, hysteresis, `Infinity` default render distance) so existing games only benefit. Tune or opt out via `PlayableGame.visibility` (`VisibilityConfig`, `@jgengine/core/visibility/config`): `enabled: false` disables it; `culling`/`streaming` patch the global `CullingSettings`/`StreamingSettings` (`@jgengine/core/visibility/settings`); `scene` sets scene-wide overrides; `entities`/`objects` override by kind name / catalog id (`alwaysVisible`, `maxRenderDistance`, custom `bounds`, `pinned`, `cullingDisabled`, …). The engine layer also ships `@jgengine/core/visibility/spatialIndex` (the 3D hash the culler queries instead of scanning every object), `@jgengine/core/visibility/assetStreaming` (dedup/budget/grace-period asset loading), and `@jgengine/core/visibility/simulationCulling` (opt-in, off by default — throttles low-priority off-screen updates, never protected entities). Full reference: `packages/core/src/visibility/README.md`.
1707
-
1708
- **Player movement tuning** — the `movement` field (`PlayerMovementConfig`) tunes the shell's local-player walk controller beyond `physics.gravity`/`jumpVelocity`: `mode` (`"free"` camera-relative default, `"axis"` locks travel to one world `axis`, `"grid"` snaps each committed step to `cellSize` centers), `collideObjects` (collide against placed scene objects as unit-box AABBs even without `collision.voxel`), and `beforeCommit(frame)` — an escape hatch called each frame with `{ entityId, current, next, dt }` that can return a replacement `[x, y, z]` to constrain or redirect the step (rails, bounds, custom collision) before it commits and before `onTick` runs.
1709
-
1710
- The runner boots `createGameContext({ definition, content, player: { userId, isNew } })`, calls `loop.onInit(ctx)` then `loop.onNewPlayer(ctx)`, and drives `loop.onTick(ctx, dt)` per frame. **Convention: `onNewPlayer` spawns the player entity with `id === ctx.player.userId`** — bounded stats, targeting, and kill attribution key off that.
1711
-
1712
- ### Object spatial queries, entity patching, and surface sampling
1713
-
1714
- ```ts
1715
- ctx.scene.object.at(x, y, z) // cell lookup, cell size 1, most-recent wins
1716
- ctx.scene.object.inBox(min, max) // inclusive AABB query
1717
- ctx.scene.object.raycast({ origin, direction, maxDistance, halfExtents?, filter? }) // → nearest hit or null
1718
- ctx.scene.object.raycastAll({ origin, direction, maxDistance, halfExtents?, filter? }) // → hits, nearest-first
1719
- ctx.scene.entity.update(id, patch) // name/position/rotations/role/movement/behaviors/meta; false for unknown id
1720
- ```
1721
-
1722
- Placed objects are unit boxes (half-extents `[0.5, 0.5, 0.5]`) centered on position, matching the shell's default render, so `raycast`/`raycastAll` (`scene/objectQuery`) match what a player sees. `entity.update` notifies subscribers and bumps `ctx.version()` the same as `spawn`/`despawn`/`setPose` — it's the general-purpose patch the more specific methods (`setPose`, `form.shapeshift`, `possession.possess`) build on.
1723
-
1724
- `ctx.scene.object.place(catalogId, x, y, z, { instanceId?, parentSpace?, rotation?, visual? })` takes an optional `visual: ObjectVisual` (`@jgengine/core/scene/objectStore`) — `{ scale?: number | [x,y,z], color?, opacity? }` — a per-instance render override independent of the catalog entry; `ctx.scene.object.setVisual(instanceId, visual | undefined)` changes it after placement (`undefined` clears back to the catalog default). Distinct from `objectStyles` on `PlayableGame` (styles a catalog id for every instance); `visual`/`setVisual` targets one placed instance (a damaged crate, a dyed banner, a resized prop).
1725
-
1726
- `pointerService.worldHitCenter()` (shell) casts from the viewport center regardless of cursor presence (pointer-lock aim) — combine with `pointer.worldHit()` (cursor-driven) to support both mouse-look and free-cursor games from the same probe. `PointerHit` also carries an optional `uv?: { u, v }` on UV-mapped mesh hits (absent for the ground fallback), `material?: { color, metalness?, roughness? } | null` sampled off the hit mesh's `MeshStandardMaterial` (`null`/unset for non-standard materials, e.g. the ground plane) — combine `uv` + `material` for paint tools, decals, and material-aware interaction — and `instanceId?: number`, the hit index when the intersected mesh is a `THREE.InstancedMesh` (grid-world cells, `InstancedBodies` debris, any instanced render), absent otherwise.
1727
-
1728
- **Runtime paint layer** (`ctx.scene.entity.paint`, backed by `scene/paintLayer`) — a `PaintLayer` keyed by instance id (entity or object): `paint(instanceId, { u, v, radius, color })`, `strokes(instanceId)`, `clear(instanceId?)`, `version(instanceId)` (bumps per paint/clear), `subscribe(listener)`. The shell auto-renders painted instances through a lazily-created 512×512 canvas texture kept in sync — no per-game render wiring. Clearing refills with the material's base color; the original texture pixels are not restored.
1729
-
1730
- ### Audio — positional emitters, listener falloff, buses
1731
- Catalog-first, no per-game audio glue. The `audio` field of `defineGame({...})` — `{ sounds: Record<string, SoundDef>, buses?: Record<string, AudioBusDef> }` — declares the sound catalog (`SoundDef = { id, url, bus, gain?, loop?, positional?, falloff? }`) and mix buses (`music`/`sfx`/`ambient`/…, `AudioBusDef = { id, gain? }`) — both types from `@jgengine/core/audio/audioFalloff`. `entitySounds?: Record<string, string>` maps an entity **kind name** (same convention as `entitySprites`/`entityModels`) to a sound id: while a matching entity exists, the shell keeps a looping positional emitter on it, repositioned every frame. `objectSounds?: Record<string, string>` does the same keyed by placed-object catalog id. The pure distance→gain math (`computeFalloffGain(distance, config)`, curves `"linear" | "inverse" | "none"`) lives in core so it is unit-tested without a browser; `@jgengine/shell` (`shell/audio/audioEngine`, `shell/audio/AudioComponents`) is the only package that touches Web Audio — it owns an `AudioContext`, mounts `AudioListener` on the camera every frame, and `EntityAudioEmitters`/`ObjectAudioEmitters` drive per-instance emitter gain from the core falloff function. `GamePlayerShell` wires all of this automatically from `playable.audio`/`entitySounds`/`objectSounds` — a game never touches `AudioContext` directly.
1732
- ### Camera rigs (`camera` field of `defineGame({...})`)
1733
- The shell ships a **rig library**; a game picks and tunes one through `camera` config, never by writing camera positions from `onTick`. Select with `camera.rig` (or the `perspective: "third" | "first"` shorthand) — or by config block alone (#207.8): supplying `camera.<rig>` selects that rig with no redundant `rig` field, checked in the table's order; an explicit `rig` wins when several blocks are present:
1734
- | `rig` | For | Key config (`camera.<rig>`) |
1735
- |-------|-----|------------------------------|
1736
- | `orbit` (default) | Third-person chase | Top-level fields on `camera` itself — `initialDistance`, `minDistance`/`maxDistance`, `targetHeight`, `min/maxPolarAngle`, drag/zoom. There is **no `camera.orbit` block**; orbit is the one rig tuned at the top level |
1737
- | `first` | FPS mouse-look | `firstPerson: { eyeHeight, sensitivity, maxPitch, reticle, viewmodel }` |
1738
- | `topDown` | ARPG iso / top-down (Diablo IV, Hades II) | `topDown: { height, pitch, yaw, followSmoothing, zoom }` — decoupled follow; `pitch` is camera elevation (PI/2 = straight down, near 0 = grazing and boom-distance blows up past `frustum.far`) |
1739
- | `rts` | Free-pan / edge-scroll (The Sims, Manor Lords) | `rts: { panSpeed, edgeScroll, rotateSpeed, bounds, start, pan }` — `pan: false` turns it into a static backdrop camera: no WASD/arrow pan, no edge-scroll, no Q/E rotate, no wheel zoom, still re-centers on `followEntityId` if one resolves |
1740
- | `shoulder` | Over-the-shoulder (Helldivers 2, Remnant II) | `shoulder: { shoulderOffset, distance, ads, side }` — ADS + shoulder-swap (V) |
1741
- | `lockOn` | Souls-like strafe (Elden Ring) | `lockOn: { targetEntityId?, distance, framingBias, yawSmoothing }` — yaw binds to player→target; WASD becomes strafe |
1742
- | `chase` | Vehicle chase (Forza, Rocket League) | `chase: { distance, springDamping, fov: { base, max, speedForMax }, shakePerSpeed, view: "chase"|"cockpit"|"hood"|"rear" }` |
1743
- | `sideScroll` | Fixed lateral follow — 2.5D platformer/beat-'em-up | `sideScroll: { distance, height, lookHeight, axis: "x"\|"z", followSmoothing, fov }` — reads no player input, follows like the other follow rigs (defaults to the local player) |
1744
- | `observer` | Detached spectator/photo/kill-cam (#120) | `observer: { bind: { kind: "entity", entityId } \| { kind: "point", position }, distance, height, orbitSpeed }` — reads no player input, auto-orbits the bound subject |
1745
- | `inspection` | Model-viewer / data-viz orbit (#207.7) | `inspection: { anchor: "target"\|"cursor"\|"center", target, initialDistance, initialPosition, min/maxDistance, min/maxPolarAngle, pan, rotateSpeed, zoomSpeed, dampingFactor }` — left-drag orbit, middle/right-drag pan (pan defaults on for this rig only), scroll zoom toward the anchor (`cursor` = zoom-to-cursor); orbits a fixed `target`, never reads player/entity state |
1746
- | `none` | No camera rig mounted | HUD-only presentations or a game that manages its own camera; see `presentation: "hud"` below |
1747
- **Frustum:** `camera.frustum: { fov?, near?, far? }` overrides the canvas camera; `far` defaults to 300, so any world whose content spans more than a few hundred units must raise it or distant settlements/terrain silently clip out of view. **Every rig accepts `followEntityId: null`** so avatar-less games (city-builders, card games, auto-battlers) still mount a camera. Leave `followEntityId` unset and the shell defaults it to `ctx.player.possession.active(userId)` every frame, so a possession swap (party control-swap, BG3-style) or a form's mesh/camera-relevant change re-targets the camera automatically — set it explicitly only to override that default. **Shake / trauma (#28):** every rig reads a shake channel; feed it from anywhere with `import { cameraShake } from "@jgengine/shell/camera"` — `cameraShake(amplitude, decayPerSecond?)` (amplitude 0..1) — or from React via `useCameraShake()`. Tune with `camera.shake: { maxOffset, maxRoll, decayPerSecond, exponent, frequency }`. **Cinematic (#29):** set `camera.cinematic: { keyframes: [{ position, lookAt, fov?, duration?, ease? }], loop? }` to play a scripted path over the active rig, and `camera.transitionSeconds` cross-fades the camera when the rig changes so mode swaps don't hard-cut. The pure rig math (shake decay, spring-arm, speed→FOV, offset/strafe, keyframe lerp) is exported from `@jgengine/shell/camera` for testing.
1748
-
1749
- ## `GameContext` — the ctx surface
1750
-
1751
- `createGameContext` (in `@jgengine/core/runtime/gameContext`) wires every system:
1752
-
1753
- ```
1754
- ctx.scene.object place, remove, move, rotate, get, list, subscribe,
1755
- at, inBox, raycast, raycastAll, catalog
1756
- ctx.scene.entity spawn, despawn, setPose, update, get, list,
1757
- stats.{get,set,delta}, setTarget, getTarget, cycleTarget,
1758
- canReceive, preview, effect, paint,
1759
- willHitProjectile, fireProjectile, settleProjectile,
1760
- distance, inRadius, hasLineOfSight, queryArc, moveToward,
1761
- spawnPoseOf, resetToSpawn, resetAllToSpawn,
1762
- form.{register,get,active,abilities,shapeshift,revert}
1763
- ctx.game commands, events, feed, loot, trade, quest, social, chat,
1764
- unlocks, economy, leaderboard, roster, store, cards, turn
1765
- ctx.game.social friends, party, presence, emotes.play, worldInvites
1766
- ctx.game.store set, delete, get, has, subscribe, mapSnapshot, arraySnapshot — game-defined
1767
- keyed reactive store slot (any value type); mutations bump ctx.version()
1768
- ctx.game.cards pile(id, config?) — lazily creates (config required on first call) or returns
1769
- the existing notify-wrapped CardPile for id
1770
- ctx.game.turn loop(id, config?) — lazily creates (config required on first call) or returns
1771
- the existing notify-wrapped TurnLoop for id
1772
- ctx.player userId, isNew, inventory, stats (modifiers), loadout,
1773
- applyLoadout, movement (pose/aim), motion (impulse/setVerticalVelocity/setY/takePending),
1774
- possession, cosmetics
1775
- ctx.player.motion impulse(vy), setVerticalVelocity(vy), setY(y), takePending() — game-code
1776
- seam into the shell's vertical-motion integrator; drained once per frame
1777
- before gravity, so a jump pad or grapple release calls this from
1778
- onTick/commands instead of touching y directly
1779
- ctx.item use, weapon
1780
- ctx.input publish(held), isDown(action), held() — per-frame held-action snapshot, polled from onTick
1781
- ctx.world ground (TerrainField), groundHeightAt(x, z) — the canonical
1782
- sampler for the game's declared world; environment worlds
1783
- resolve their terrain field, every other world kind is 0.
1784
- Use it for every spawn/placement/waypoint y — never
1785
- hand-roll a noise sampler or hardcode y = 0 on relief
1786
- ctx.camera follow(entityId | null), followedEntityId(), setCinematic(config), cinematic(),
1787
- subscribe — runtime camera-follow/cinematic override; the shell reads
1788
- followedEntityId() each frame, falling back to the static
1789
- playable.camera.followEntityId when it returns undefined
1790
- ctx.time advance, now, calendar, snapshot; pause, play, toggle,
1791
- setSpeed, cycleSpeed; after, every, at (game-time timers)
1792
- ctx.subscribe / ctx.version change signal — UI layers bind via useSyncExternalStore
1793
- ```
1794
-
1795
- `content.itemById(id)` supplies `{ use?, weapon?, trade? }` — exact shapes: `use` is the handler **name string** (not an object), `weapon` is a flat `Record<string, number | Record<string, number>>` built from your catalog stats (`damage`, `projectile.{...}`, `explosion.{...}`), and every lookup returns **`null`** (not `undefined`) for an unknown id; `content.entityById(id)` supplies `{ stats?, receive?, onDeath?, movement?, role? }`; `content.objectById(id)` supplies `GameContextObjectEntry` `{ proximityPrompt?, breakable?, slotInventory? }`. Build all three from your catalogs in `content.ts`. Call-shape gotchas that cost typecheck loops: `ctx.item.use.use(input)` takes **one** argument on the ctx surface (the two-arg `use(state, input)` is the raw factory shape); `ctx.scene.entity.moveToward(id, target, { speed, dt, stopDistance? })` — the third argument is an options object, never a bare `dt`; `nav/pathFollow`'s `createPathFollow(config)` returns the initial `PathFollowState` directly and `advancePathFollow(config, state, dt)` returns the **next state** (with `position: [x,y,z]`, `heading`, `done`) — there is no wrapper object, and `Waypoint` is a `[x, y, z]` tuple. A placed object resolves its catalog entry via `ctx.scene.object.catalog(instanceId)`; `ctx.scene.object.at(x, y, z, tolerance?)` finds placed objects near a point (grid interaction, click resolution beyond the pointer service). `ctx.scene.entity.update(id, patch)` writes a shallow patch onto a spawned entity's mutable fields (e.g. `movement.walkSpeed`) without a full respawn — `scene/movementSpeed`'s `applyStatDrivenSpeed(deps, id, { baseSpeed, multiplierStat?, flatBonusStat? })` is the catalog-driven helper that recomputes and writes `movement.walkSpeed` from a stat-modifier pair each time a buff changes.
1796
-
1797
- ### Two tiers: `ctx` runtime vs pure factories
1798
-
1799
- The `ctx` surface above is the **stateful runtime** — it's what game code uses. Every subsystem it wires is *also* exported as a **pure factory** that `createGameContext` composes internally: `createTradeSystem`, `createDeathSystem`, `createEffectSystem`, `createProjectileSystem`, `createSpatialApi`, `createEntityStatsApi`, `createEntityStore`, `createObjectStore`, `createStats`, `createLoadouts`, `createLootRegistry`, `createQuestJournal`, `createSocial`, `createSlots`, `createInteriors` (plus stateless helpers beside each — `canAffordCosts`/`resolveBuy` in `game/trade`, `getStatValue`/`applyPoolDelta` in `scene/entityStats`, and so on). **Build a game through `ctx`, not these** — reach for the factories only for unit tests of pure game math, headless servers, or a custom runtime. Import the domain deep path (`@jgengine/core/combat/death`, `@jgengine/core/game/trade`, `@jgengine/core/stats/statModifiers`, …) and read the `.d.ts`; each is a real export in the published package.
1800
-
1801
- `createSpatialApi`'s optional `grid: { cellSize }` opts `inRadius`/`queryArc` into a lazily-built x/z broadphase index over `candidates()` instead of a linear scan — worth it once candidate counts run into the hundreds+. The index is reused across calls until `invalidate()` is called, so call it after any position change (move, spawn, despawn); a candidate outside the index at query time still resolves exactly (never silently skipped), only a *moved* one can be missed until invalidated.
1802
-
1803
- ## `loop` — lifecycle
1804
-
1805
- ```ts
1806
- export function onInit(ctx: GameContext) {
1807
- ctx.item.use.register(itemUseHandlers);
1808
- ctx.player.loadout.register(loadouts);
1809
- for (const table of lootTables) ctx.game.loot.register(table);
1810
- ctx.game.quest.register(quests);
1811
- ctx.game.quest.bind("entity.died");
1812
- ctx.game.feed.bind("entity.died");
1813
- ctx.game.events.on("entity.died", (evt) => onEntityDied(ctx, evt));
1814
- setupWorld(ctx);
1815
- }
1816
-
1817
- export function onNewPlayer(ctx: GameContext) {
1818
- ctx.scene.entity.spawn("player_default", { id: ctx.player.userId, position: spawnPoint });
1819
- if (ctx.player.isNew) ctx.player.applyLoadout(ctx.player.userId, "starterKit");
1820
- }
1821
-
1822
- export function onTick(ctx: GameContext, dt: number) {
1823
- // AI, regen, respawn timers — dt is GAME time (see ctx.time). Never death detection (see entity.died)
1824
- }
1825
- ```
1826
-
1827
- `onInit` runs once per boot; register everything there. Loot tables register through `ctx.game.loot.register` — `lootTable()` is a pure validating factory, there is no global side-effect registry.
1828
-
1829
- ## `ctx.time` — the simulation clock
1830
-
1831
- `onTick`'s `dt` is **game time, not real time**: the shell scales each frame's real delta by `definition.time.scale` (real→game seconds at 1×) and the live speed multiplier, so writing decay/regen/AI as `rate * dt` makes it obey pause and fast-forward for free — never read wall-clock in a tick. Configure via `defineGame({ time: { scale?, speeds?, dayLength?, start?, startPaused?, daysPerYear?, seasons? } })` (all optional; default is real-time 1:1 with speeds `[1,2,3,4]`, 365-day years).
1832
-
1833
- - **Continuous** work scales through `dt`. **Scheduled** work uses game-time timers: `ctx.time.after(sec, cb)`, `ctx.time.every(sec, cb)`, `ctx.time.at(gameSec, cb)` — measured in game-seconds, so 4× fires them 4× sooner and pause freezes them. Each returns a cancel handle.
1834
- - **Controls** (drive from a HUD or a command): `pause()`, `play()`, `toggle()`, `setSpeed(mult)` (0 pauses), `cycleSpeed()`. Read state with `ctx.time.snapshot()` / `ctx.time.calendar()` (`{ day, hour, minute, second, dayFraction, year, dayOfYear, yearFraction, season? }`), or in React with `useGameClock()` → snapshot + `controls`. Speeding to 4× or pausing affects **everything** on the tick — no per-system wiring.
1835
- - **Calendar year/season** rides the same day counter, no separate clock: `year`/`dayOfYear` fall out of `day` divided by `TimeConfig.daysPerYear` (default 365), `yearFraction` is progress through the current year (0..1). Setting `TimeConfig.seasons: string[]` (e.g. `["spring","summer","fall","winter"]`) slices the year into equal named segments and populates `calendar().season`; omit `seasons` and the field is absent — a living-world sim names its own season boundaries this way instead of a hand-rolled `dayOfYear % ...` module.
1836
-
1837
- ### Beat clock — BPM signal + input quantization
1838
-
1839
- `@jgengine/core/time/beatClock` is a separate, purpose-built signal from `simClock` — a BPM tick generator for rhythm games (Hi-Fi Rush–style quantized combat), not a day/pause clock. `createBeatClock({ bpm, beatsPerBar? }, onBeat?)` returns a `BeatClock`: call `advance(gameDt)` from `onTick` with the same **game-time** `dt` (never wall-clock) — it fires `onBeat(beatIndex)` once per newly crossed integer beat and returns a `BeatSnapshot` (`beat`, `beatIndex`, `bar`, `beatInBar`, `phase`). `createBeatInputBuffer<T>(beatDurationSec)` is the auto-correct input buffer: `buffer(action, nowSec)` quantizes an off-beat press to fire on the next beat tick (or immediately if pressed exactly on one); `advance(nowSec)` drains and returns every action whose beat has arrived. `nextBeatTime(nowSec, beatDurationSec)` is the underlying pure quantization function. Feed a music track's actual BPM in; the buffer is what makes an early/late input still land on-beat.
1840
-
1841
- ## Content catalogs
1842
- ## `ctx.game.store` — reactive game state
1843
-
1844
- ```ts
1845
- ctx.game.store.set("health", 100) // any key, any value type
1846
- ctx.game.store.get("health") // T | undefined
1847
- ctx.game.store.has("health")
1848
- ctx.game.store.delete("health")
1849
- ctx.game.store.subscribe(listener) // change-signal fires on set/delete
1850
- ctx.game.store.mapSnapshot() / arraySnapshot()
1851
- ```
1852
-
1853
- A reactive per-game keyed store (`ObservableKeyedStore<unknown>`) attached to `GameContext` — reach for it instead of a module-level singleton store for ad-hoc reactive game state (turn trackers, deck UIs, anything that doesn't already have a `ctx` surface). `set`/`delete` bump `ctx.version()` and notify `ctx.subscribe` listeners; `get`/`has` are plain reads. Unlike a per-slot handle, there is no `define`/seed step — a key simply doesn't exist until the first `set`.
1854
-
1855
- ## `ctx.game.cards` / `ctx.game.turn` — lazily-created piles and turn loops
1856
-
1857
- `ctx.game.cards.pile(id, config?)` and `ctx.game.turn.loop(id, config?)` lazily create (config required on first call) or return the existing notify-wrapped `CardPile`/`TurnLoop` for `id` — call with just the id after the first `onInit` seed to fetch the same instance; every mutating method is wrapped so it bumps `ctx.version()`/notifies `ctx.subscribe` automatically, same as every other `ctx` surface. This replaces manually constructing `createCardPile`/`createTurnLoop` and wiring notification yourself.
1858
-
1859
- ## Movement, pose, input
1860
- ## External data — `data/dataSource` and the dev proxy
1861
-
1862
- Renderer-free async-state primitives (`@jgengine/core/data`) for a game that reads a live external source (a leaderboard API, a session browser, remote config) — distinct from `ctx.game.store`/multiplayer, which are for the game's own authoritative state.
1863
-
1864
- - **`createDataSource(load, options?)`** (`data/dataSource`) → `DataSource<T>` wraps one `load(signal)` async call as `{ status: "idle"|"loading"|"ready"|"error", data, error }`. `getState()` reads the current snapshot, `subscribe(listener)` fires on every change, `refresh({ force? })` re-runs `load` (de-duplicates a call already in flight unless `force`; aborts the prior call first when forced), `startPolling(intervalMs?)`/`stopPolling()` run `refresh` on an interval (`intervalMs` falls back to the one passed at construction; throws if neither is given), `dispose()` tears down polling and in-flight requests for good. Pass `options.clock` (`{ setInterval, clearInterval }`) to swap the timer source in tests.
1865
- - **`fetchJson<T>(url, options?)`** (`data/fetchJson`) — `fetch` + JSON-parse in one call; throws `HttpStatusError` (`status`, `statusText`, `url`) on a non-OK response and `JsonParseError` (`url`, `cause`) on unparsable JSON, so a `DataSource`'s `error` is always one of these two typed shapes, never a bare `Error`. `options.fetchImpl` swaps the fetch implementation for tests/SSR.
1866
- - **`createJsonDataSource<T>(url, options?)`** (`data/jsonDataSource`) — sugar combining the two above: a `DataSource<T>` whose `load` calls `fetchJson(url, options)`.
1867
- - **Dev proxy (`data/devProxy`)** — same-origin routing for external APIs during `bun dev` so browser CORS never blocks a game's `fetchJson` call against a third-party host. `parseDevProxyTable(raw)` parses a `VITE_JGENGINE_DEV_PROXY` env value (a JSON object of `{ routeName: "https://api.example.com" }`) into a `DevProxyTable`; `proxiedUrl(target, { dev?, table?, prefix? })` rewrites a `target` URL whose prefix matches a table entry into `/proxy/<routeName>/<rest>` (default prefix `/proxy`) when `dev` is true (defaults to `import.meta.env.DEV`) — else returns `target` unchanged, so the same call hits the real host in production. `apps/dev`'s `vite.config.ts` reads the same env var and wires a matching Vite server `proxy` entry per route (`changeOrigin: true`, strips the `/proxy/<routeName>` prefix) — set `VITE_JGENGINE_DEV_PROXY` once and both sides (the URL rewrite and the actual proxy route) agree.
1868
-
1869
- ## Multiplayer and the backend seam
1870
- ## Genre cheat sheet
1871
-
1872
- - **Voxel/crafting**: objects for blocks/machines, `voxel()`, `object.break`/`object.placeFromInventory`.
1873
- - **Tycoon/lab**: objects + `slotInventory`, `plots()`, configure via prompt → command.
1874
- - **Shooter**: `fireProjectile`/`settleProjectile`; grenades settle → `effect({ at, radius })`; `movement.poses`/`aim` + zoom modifier; `servers({ … })` + game-owned `server.mode`; loadout classes from commands.
1875
- - **MMO/RPG**: bounded stats + `leveling()` over a game XP curve; `tabTarget` → `cycleTarget`; handlers read `getTarget`; quests bound to `entity.died`/`inventory.added`; social party + `partyShare`; `server: "persistent"`.
1876
- - **All combat games**: react to `entity.died` (feed/leaderboard/score) — never poll HP.
1877
-
1878
- ## Anti-patterns
1879
-
1880
- | Wrong | Right |
1881
- |-------|-------|
1882
- | Player tuning in `defineGame` | Entity catalog `movement` + stats |
1883
- | `behaviors: […]` on place/spawn | Catalog entry |
1884
- | Engine `weapon.fire` / `consumable.use` / `combat.*` | `item.use` + catalog `use` → game handler |
1885
- | `ItemUseInput.to` for targets | `getTarget(from)` in handlers |
1886
- | `effect({ to })` for gunshots | `fireProjectile` + `settleProjectile` |
1887
- | Polling HP in `onTick` for kills | `entity.died` event |
1888
- | `combat.lootTable` / `loot.enemy` | `onDeath` on the entity that died |
1889
- | Hand-rolled `Math.random()` loot in commands | `lootTable()` + `ctx.game.loot.roll` |
1890
- | Hand-rolled `xpForLevel`/`levelFromXp` | `game/progression` `curve()` + `leveling()` |
1891
- | Hardcoded shop arrays | `item.trade.shops` + `tradableAt` |
1892
- | Kit seeding via scattered `put`/`grant` | `applyLoadout` |
1893
- | Per-user quest state hand-rolled | `game.quest.register` + binds |
1894
- | `useKillFeed` / per-domain feed hooks | `useFeed({ action })` |
1895
- | Raw keys in game logic | `defineGame` input actions |
1896
- | Positioning inside `ui/components/` or on primitives (`CurrencyPill className="absolute …"`) | Screen wrappers in `GameUI.tsx` only |
1897
- | Game UI classes without `@source` in host CSS | `@source` entries for your game dirs + `node_modules/@jgengine/{shell,react}` |
1898
- | One file per catalog entry / per brand | Dense `<domain>/catalog.ts` |
1899
- | Convex mutations called from game code | `commands.run` through the `GameBackend` transport |
1900
- | Half a system: quest without tracker, cooldown without sweep, keybind never shown, stub "coming soon" modal | Finish the system end to end — or cut it whole (see `jgengine`) |
1901
- | Game-side workaround for a missing engine primitive | File the gap at github.com/Noisemaker111/jgengine/issues (or PR the primitive) and cut or scope the dependent system honestly |
1902
- | Game nouns in this skill | Engine primitives + placeholder ids only |
1903
-
1904
- ## New-game definition of done
1905
-
1906
- This is a gate, not a suggestion — every box, in one pass (workflow: **`jgengine`** skill). "Compiles and the hooks are wired" is not done; a declared system with no UI, no feedback, or no way to exercise it is not done — finish the system or cut it whole.
1907
-
1908
- - [ ] `game.config.ts` (`defineGame` from `@jgengine/shell/defineGame`) + `index.tsx` (barrel) + `main.tsx` (standalone host) + `loop.ts` + `game/content.ts`
1909
- - [ ] Catalogs: `game/entities/<role>/catalog.ts`, `game/items/<domain>/catalog.ts`, `game/objects/catalog.ts`; loot tables beside their domain
1910
- - [ ] Entity `stats` + `receive` orders aligned on the same stat ids; `role` set (drives targeting + camera)
1911
- - [ ] `game/items/use-handlers.ts` registered in `onInit`; handlers read `getTarget`/`aim`, never a target input
1912
- - [ ] `game/loadouts.ts` + `applyLoadout` in `onNewPlayer` (gated on `isNew`)
1913
- - [ ] `game/quests/catalog.ts` + binds; if using xp/level, a game-owned curve fed to `game/progression` (`curve`/`leveling`) — **with their HUD/tracker, or cut**
1914
- - [ ] `onInit`: register handlers/loadouts/loot/quests, event listeners, feed binds, leaderboard tracks; `setupWorld`
1915
- - [ ] Player spawns with `id === ctx.player.userId`
1916
- - [ ] `game/ui/GameUI.tsx` owns layout; components use `@jgengine/react` hooks
1917
- - [ ] UI passes the **quality bar** above (contrast, scale, framing, genre fit) — not just hook wiring
1918
- - [ ] Camera tuned via `camera` in `defineGame({...})` — defaults untouched means the feel was never checked
1919
- - [ ] For an `environment()` world: a `<game>.world.test.ts` asserts `summarizeEnvironment(world)` (`@jgengine/core/world/environmentSummary`) is non-empty with the expected counts — the browserless scene-correctness gate
1920
- - [ ] HUD screenshotted over a staged `GameUiPreview` scenario and **judged by looking at the image** against the UI quality bar in [`../jgengine-ui/reference.md`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-ui/reference.md) — the final human glance, not the verification loop
1921
- - [ ] Co-located bun tests for pure game math (curves, cooldowns, spawn logic)
1922
- - [ ] Multiplayer via adapter config only; no direct backend calls
1923
-
1924
- ## Quick reference
1925
-
1926
- ```
1927
- defineGame (shell) engine fields (assets, world, physics, inventories, input, server, save, time, feed, multiplayer)
1928
- + presentation fields (content, loop, GameUI, camera, environment, shadows, movement, devtools, …) in one call — smart defaults fill the rest
1929
- defineGame (core) the underlying engine-only primitive: assets, world, physics, inventories, input, server, save, time, feed, multiplayer, loop
1930
- PlayableGame { game, content, loop, GameUI, camera, … } — the runner contract `defineGame` (shell) returns
1931
- GameContext ctx.scene / ctx.game / ctx.player / ctx.item / ctx.camera / ctx.input + subscribe/version
1932
- scene.object place, remove, move, rotate, at, setVisual (per-instance ObjectVisual: scale/color/opacity override)
1933
- scene.entity spawn (anchor/offset), despawn, setPose, update; stats; targeting; effects;
1934
-
1935
- # jgengine-ui
1936
-
1937
- Use this skill for the **visual and interaction design of the game interface**: title screens, HUDs, menus, prompts, maps, inventories, dialogue, touch controls, transitions, pause/results states, accessibility, and screenshot critique.
1938
-
1939
- Do not use this skill as a React, routing, state-management, or hooks reference. The main `jgengine` skill owns routing and points to the engine APIs. When implementation needs `@jgengine/react` hooks or shell APIs, follow the links in the main skill and the compact API appendix in [reference.md](reference.md); keep this skill focused on what the player sees and feels.
1940
-
1941
- ## Required outcome
1942
-
1943
- A JGengine game must read as a self-contained game, not a responsive website with a canvas inside it.
1944
-
1945
- Before shipping UI:
1946
-
1947
- 1. Give the game a concise UI art direction.
1948
- 2. Compose explicit desktop/mobile game layouts instead of document flow.
1949
- 3. Keep persistent HUD information sparse and hierarchical.
1950
- 4. Adapt touch controls to the genre and reserve their screen zones.
1951
- 5. Implement authored focus, pressed, selected, disabled, success, failure, and warning states.
1952
- 6. Add purposeful motion and feedback.
1953
- 7. Capture screenshots and revise what actually renders.
1954
-
1955
- ## Ownership boundary
1956
-
1957
- The main `jgengine` skill owns intake, engine architecture, API routing, hooks, commands, state, and verification routing. This skill owns presentation quality.
1958
-
1959
- Read [reference.md](reference.md) when building or reviewing a game interface. It contains the implementation quality bar, layout rules, art-direction template, touch-control requirements, acceptance criteria, and the compact existing React API surface.
1960
-
1961
- ## Non-negotiable defaults
1962
-
1963
- - Active play owns the viewport; no marketing header, page title bar, document scrolling, or website container.
1964
- - Screen placement belongs in the game's `ui/GameUI.tsx` composition layer.
1965
- - Persistent gameplay information is frameless unless a physical/diegetic frame is part of the game's art direction.
1966
- - Instructions are contextual and temporary, not permanent keyboard grids.
1967
- - Mobile controls share input mechanics but not one universal visual skin.
1968
- - Themes change geometry, composition, typography roles, icons, motion, materials, sound, and density—not only colors.
1969
- - Ordinary rounded cards, pill buttons, generic dark modals, and dashboard grids are fallback failures, not defaults.
1970
-
1971
- ## Preview states ship with the UI
1972
-
1973
- Every game ships `src/preview.tsx`: a static default frame (default export, used by the website card) plus a `states` named export (`GamePreviewStates` from `@jgengine/react/preview`) keying named UI states — `stage_1`, `game_over`, `boss_intro` — to components. Build state entries from the game's **real UI components** with fixture snapshots (canned props/state), not redrawn lookalikes; that turns every key into a capturable render test. Capture any state instantly with `bun run shoot <game> --preview <stateKey>` — no sim, no three.js, no hang risk — and use it as the screenshot-critique loop for HUD/menu/overlay work before any full-shell `--mode ui`/`play` glance.
1974
-
1975
- ## Rejection test
1976
-
1977
- Reject and revise the UI when it could be mistaken for a SaaS dashboard, landing page, admin panel, documentation page, or generic emulator overlay.
1978
-
1979
- # JGengine UI — game presentation reference
1980
-
1981
- This reference defines the required visual and interaction quality for JGengine games. The main `jgengine` skill owns engine architecture, hooks, input commands, and routing. This document owns what the interface looks like, how it is composed, how it responds, and how it is verified.
1982
-
1983
- ## The rule
1984
-
1985
- A game must visually own its viewport. It must not resemble a dashboard, landing page, documentation page, or ordinary responsive web app.
1986
-
1987
- HTML and React are valid implementation tools. Website visual grammar is not the default.
1988
-
1989
- ## 1. Start with a concise UI art direction
1990
-
1991
- Before implementing screens, write this short block:
1992
-
1993
- ```md
1994
- UI ART DIRECTION
1995
-
1996
- Player fantasy:
1997
- Emotional tone:
1998
- Shape language:
1999
- Material language:
2000
- Typography roles: display / body / numerical / labels
2001
- Motion language:
2002
- Icon language:
2003
- Sound language:
2004
- Information hierarchy:
2005
- Forbidden patterns:
2006
- ```
2007
-
2008
- Keep it practical. It should directly influence layout, silhouettes, controls, timing, and materials.
2009
-
2010
- Example forbidden patterns:
2011
-
2012
- - generic rounded dashboard cards
2013
- - pill buttons
2014
- - long centered paragraphs during play
2015
- - ordinary two-column form layouts
2016
- - persistent keyboard-instruction grids
2017
- - multiple equally weighted bordered panels
2018
- - generic translucent mobile circles
2019
- - large website-style modals
2020
- - document-flow wrapping used as HUD layout
2021
-
2022
- A theme is not complete when only colors and fonts change. It must also affect composition, geometry, spacing rhythm, borders, icons, animation, sound, information density, terminology, button construction, and touch controls.
2023
-
2024
- ## 2. Screen inventory and hierarchy
2025
-
2026
- Identify the screens the game actually needs:
2027
-
2028
- - boot/loading
2029
- - title or attract screen
2030
- - mode selection
2031
- - onboarding/tutorial
2032
- - gameplay HUD
2033
- - pause
2034
- - settings
2035
- - map/inventory/dialogue where relevant
2036
- - victory/results
2037
- - failure/retry
2038
-
2039
- For each screen, define:
2040
-
2041
- - the player’s primary question
2042
- - the primary action
2043
- - the most important information
2044
- - what can be hidden
2045
- - what belongs in-world instead of in the HUD
2046
-
2047
- ### HUD tiers
2048
-
2049
- **Tier 1 — immediate action and survival**
2050
- Health, timer, current target, ammo, danger, capture state.
2051
-
2052
- **Tier 2 — short-term decisions**
2053
- Objective progress, route progress, cooldowns, combo, pursuit distance.
2054
-
2055
- **Tier 3 — reference information**
2056
- Full map, inventory, controls, schedule, mission details, lore.
2057
-
2058
- Tier 1 is immediately readable. Tier 2 is quieter. Tier 3 is usually hidden until requested.
2059
-
2060
- Do not style every datum as an equally important bordered box.
2061
-
2062
- ## 3. Full-viewport game composition
2063
-
2064
- The active game should behave like an application mode:
2065
-
2066
- - own the full viewport
2067
- - avoid document scrolling
2068
- - avoid site navigation and marketing chrome during play
2069
- - respect safe-area insets
2070
- - keep exit/settings/fullscreen controls minimal
2071
- - separate world, HUD, controls, screens, and system overlays
2072
-
2073
- Recommended layer contract:
2074
-
2075
- ```tsx
2076
- <GamePlayer>
2077
- <WorldLayer />
2078
- <HudLayer />
2079
- <ControlLayer />
2080
- <ScreenLayer />
2081
- <SystemLayer />
2082
- </GamePlayer>
2083
- ```
2084
-
2085
- - `WorldLayer`: game renderer
2086
- - `HudLayer`: non-blocking gameplay information
2087
- - `ControlLayer`: touch/input surfaces
2088
- - `ScreenLayer`: title, pause, settings, tutorial, victory, failure, transitions
2089
- - `SystemLayer`: exit, fullscreen, engine settings, devtools
2090
-
2091
- Do not place unrelated interface pieces into one ordinary DOM flow.
2092
-
2093
- ## 4. Explicit game layout modes
2094
-
2095
- Do not rely on generic responsive wrapping. Compose explicit modes such as:
2096
-
2097
- - desktop-wide
2098
- - desktop-compact
2099
- - mobile-landscape
2100
- - mobile-portrait
2101
-
2102
- A mobile layout is not a shrunken desktop HUD.
2103
-
2104
- On mobile:
2105
-
2106
- - reserve thumb-control zones
2107
- - keep critical HUD out of those zones
2108
- - hide keyboard legends
2109
- - reduce persistent information
2110
- - move Tier 3 information behind contextual panels
2111
- - respect browser and device safe areas
2112
- - support portrait only when intentionally designed
2113
- - otherwise show a polished rotate-device state
2114
-
2115
- All viewport anchoring should live in the game’s top-level UI composition file. Child components own their internal layout, not their screen position.
2116
-
2117
- ### Design-resolution fit (`platforms` + `hudFit`)
2118
-
2119
- Design-resolution fit is on by default for every game: each `HudCanvas` auto-scales from `hudFit.designSize` (default 1600×900) down to the live viewport, clamped by `hudFit.minScale`/`maxScale` (default 0.4–1), so the authored layout shrinks instead of overflowing a phone. No declaration needed. `hudFit.mobile` overrides the fit on compact displays only — tune the phone presentation there instead of hand-rolling media queries. The player's Graphics → UI scale setting multiplies the computed scale on every platform. Declaring `platforms: ["web"]` (without `"mobile"`) opts a desktop-only game out; its compact displays keep the legacy fixed 0.85 zoom.
2120
-
2121
- **Overflow is an error, not a style note.** `HudCanvas` measures every `HudPanel` against the viewport at runtime; offenders land in a `data-hud-overflow` attribute (and a console warning), and `bun run shoot <game> --device mobile` (or `both`) exits non-zero naming the escaping panels. A game is not mobile-done while shoot reports HUD OVERFLOW.
2122
-
2123
- ### Phase-gated HUD visibility (`showDuring`)
2124
-
2125
- `HudCanvas` and `HudPanel` take an opt-in `showDuring?: GamePhase[]` — the element renders only while `gamePhase` is one of the listed phases (`"menu" | "playing" | "paused" | "ended"`), so a non-cartridge game hides its HUD under menu/end overlays without hand-rolling a phase check. Omit it for the default always-visible behavior. Gate the whole HUD with `<HudCanvas showDuring={["playing"]}>`, or keep a single results panel up with a per-`HudPanel` value. The read degrades to `"playing"` when the component renders outside a `GameProvider` (component showcases, previews), so it never throws there.
2126
-
2127
- ### Shared viewport allocation (`GameViewportProvider`, region collision)
2128
-
2129
- The shell allocates the live viewport once — visual viewport, safe-area insets, orientation, and layout mode — and hosts a **layout registry** every UI subsystem publishes its occupied rectangle to. This replaces "every subsystem independently claims an edge" (the mobile-overlap smell). It is wired automatically for every game; author against it, don't rebuild it.
2130
-
2131
- - **The mode** is one of `desktop-wide | desktop-compact | mobile-landscape | mobile-portrait`, resolved from the live `visualViewport` + coarse-pointer + `platforms`. Read it with `useGameLayoutMode()` (or `useGameViewportLayout()` for the full geometry: `mode`, `orientation`, `safeArea`, `controlZones`, `gameplayRect`). Both degrade to a sane desktop default outside the provider, so previews never throw.
2132
- - **Live CSS variables** are published on the provider root: `--jg-viewport-*`, `--jg-visual-viewport-*`, `--jg-safe-{top,right,bottom,left}`. Use them (with `100dvh` fallbacks) instead of assuming `100vh` equals the visible area on mobile Safari.
2133
- - **Touch controls reserve real rectangles.** The engine measures the joystick / action-cluster / utility zones at runtime (ResizeObserver, not guessed percentages) and registers them as `control` regions. `HudCanvas` already lifts bottom-anchored panels above the dock via `--jg-hud-dock-clearance`; the registry additionally makes any residual overlap a hard error.
2134
- - **Collision is detected, not hoped for.** A `HudPanel` inside a `HudCanvas` registers as a `hud` region automatically. `bun run shoot <game> --device mobile` / `mobile-landscape` reads a `data-jg-layout-collision` attribute and exits non-zero naming both colliding regions (e.g. `throttle ∩ radio (4270px²)`) — the same failure discipline as HUD overflow. In dev the colliding elements also carry `data-jg-collision` for outlining. Opt an intentional overlap out with `allowOverlapWith` / `collisionGroup`, or a soft `mobileBehavior="transient"`.
2135
-
2136
- ### HUD priority + mobile behavior (`HudPanel`)
2137
-
2138
- Declare intent, not just CSS. `HudPanel` accepts:
2139
-
2140
- - `priority?: "critical" | "secondary" | "tertiary"` — the Tier from §2, surfaced to tooling. Critical stays visible; tertiary folds away first.
2141
- - `mobileBehavior?: "persistent" | "compact" | "icon" | "transient" | "hidden" | "sheet" | "modal"` — `"hidden"` unmounts the panel on phones (move that Tier-3 readout behind a contextual action instead); `"transient"` softens its collision policy for a fleeting line; the rest tag the element (`data-hud-mobile-behavior`) for the game's own responsive CSS. Keep these game-authored and lightly styled — this is a placement contract, not a website design system.
2142
-
2143
- The game still owns the genre-appropriate composition; the engine owns the geometry and the failure gate.
2144
-
2145
- ### Mandatory orientation (`orientation`)
2146
-
2147
- A game declares its phone-orientation contract on `defineGame({ orientation })`:
2148
-
2149
- - Legacy `"landscape"` / `"portrait"` stays **advisory** — a dismissible rotate hint, never a gate.
2150
- - The object form `{ mobile: <rule> }` is the strict contract, where `<rule>` is `any` (both) · `portrait` / `landscape` (advisory preference) · `portrait-required` / `landscape-required` (hard gate) · `unsupported` (no phone support).
2151
-
2152
- For a driving/landscape game: `orientation: { mobile: "landscape-required" }`. When the device is held the wrong way the shell shows an **engine-owned `RotateDeviceScreen`** (polished, safe-area-aware, `visualViewport`-sized, reduced-motion-respecting, themeable via `--jg-*`) above every layer, **suppresses game input, freezes the simulation, and unmounts the HUD and touch controls** — gameplay never runs behind the gate. The gate is derived live from orientation, so rotating back to a valid orientation resumes automatically with no stuck-paused state. Never re-implement a "rotate for best experience" toast; declare the requirement and the engine owns the rest.
2153
-
2154
- ## 5. Change the visual grammar
2155
-
2156
- Avoid making every element the same rounded translucent rectangle.
2157
-
2158
- Use genre-appropriate structures:
2159
-
2160
- - clipped corners
2161
- - irregular silhouettes
2162
- - image-backed frames
2163
- - mechanical plates
2164
- - radial interfaces
2165
- - ribbons and tabs
2166
- - gauges and meters
2167
- - emblems and decorative corners
2168
- - notches and edge anchors
2169
- - diegetic objects
2170
- - world-space prompts
2171
- - asymmetrical compositions
2172
- - masks, textures, layered borders, and strong focal elements
2173
-
2174
- Practical rule: no more than roughly 20% of a normal gameplay screen should resemble an ordinary web card or modal.
2175
-
2176
- Every persistent panel must justify why it exists, remains visible, has that shape, and occupies that position.
2177
-
2178
- ## 6. Game UI primitives
2179
-
2180
- Prefer small headless or lightly styled primitives over a giant universal design system. Useful concepts include:
2181
-
2182
- - `HudAnchor`
2183
- - `StatReadout`
2184
- - `Meter`
2185
- - `ObjectiveTracker`
2186
- - `ActionPrompt`
2187
- - `Reticle`
2188
- - `MinimapFrame`
2189
- - `DialoguePlate`
2190
- - `Countdown`
2191
- - `BossBar`
2192
- - `ItemPickup`
2193
- - `DamageIndicator`
2194
- - `PauseScreen`
2195
- - `ResultsScreen`
2196
- - `VirtualControlZone`
2197
- - `ScreenTransition`
2198
-
2199
- A primitive should expose game-oriented choices such as shape, material, urgency, placement, hierarchy, entry motion, icon treatment, compactness, and diegetic-versus-overlay presentation.
2200
-
2201
- **Minimap** is already shipped, not hand-rolled: `Minimap` / `WorldMap` / `Compass` from `@jgengine/react/map` render a framed SVG minimap over a `MarkerSet` (`createMarkerSet`, `@jgengine/core/world/markers`) and optional `FogField`, projecting via `@jgengine/core/world/minimap` (`projectToMinimap`, `headingToBearing`, edge-clamp). A game feeds flat props (`markers`, `center: [x,z]`, `worldRadius`, `size`, `facingYaw`, `rotate`) and repopulates the marker set each HUD tick from live entities — no custom canvas painter. **Swing timer**: `swingTimerState(player, target, prevPeriod, prevTimer)` (`@jgengine/core/ui/swingTimer`) is the pure, parameter-in/next-state-out core for a melee swing bar (recovers period on the reset edge; hidden unless auto-attacking a live non-object target) — thread the returned `nextPeriod`/`nextTimer` back via refs, render a thin `Meter`.
2202
-
2203
- Do not create a primitive whose only value is wrapping a `div` with border radius.
2204
-
2205
- ## 7. Complete interaction states
2206
-
2207
- Every interactive element needs intentional states:
2208
-
2209
- - rest
2210
- - hover where applicable
2211
- - keyboard/controller focus
2212
- - pressed
2213
- - selected
2214
- - disabled
2215
- - success
2216
- - failure
2217
- - warning
2218
-
2219
- Do not communicate all states with background-color changes alone. Use appropriate combinations of:
2220
-
2221
- - scale compression
2222
- - position shift
2223
- - edge or glow response
2224
- - mask movement
2225
- - icon movement
2226
- - text response
2227
- - brief particles
2228
- - sound
2229
- - haptics when supported
2230
- - controlled shake only when appropriate
2231
-
2232
- Focus must look authored while remaining accessible. Menus should support keyboard/controller-style focus navigation when practical.
2233
-
2234
- ## Rendering — post-processing, lighting, shadows
2235
-
2236
- A cinematic look is opt-in engine config, never hand-wired render passes. Set `defineGame({ postProcessing })` (`PostProcessingConfig` from `@jgengine/core/render/postProcessing`) and the shell mounts an `EffectComposer` and owns the render: RenderPass → AO → Bloom → tone-map output → Grade. Absent means the renderer draws directly (unchanged), so it never imposes a look on games that don't ask. Each stage is a config object, `false` to skip, or omitted for its tuned default:
2237
-
2238
- - `toneMapping: "aces" | "agx" | "reinhard" | "cineon" | "linear" | "none"` (default `aces`) + `exposure`.
2239
- - `bloom: { strength, radius, threshold }` — HDR glow around bright pixels (defaults 0.32 / 0.55 / 0.85).
2240
- - `grade: { lift, gain, gamma, saturation, vignette, grain }` — display-space colour grade: cool-shadow/warm-highlight split, vignette, animated film grain.
2241
- - `ao: { radius, intensity, distanceFalloff, blend }` — ground-truth ambient occlusion; heavier than the rest, omit or `false` on low-end targets.
2242
-
2243
- **Orbit camera occlusion:** the third-person orbit rig takes `camera: { collision: { enabled, padding?, minTargetDistance? } }` — a spring-arm that raycasts target→camera each frame and pulls the boom in past walls/terrain so the camera never clips inside geometry. Off by default (unchanged chase feel); enable it for any world with interiors or dense structures.
2244
-
2245
- Lighting is `defineGame({ lighting })` (`LightingConfig`): ambient / hemisphere / directional, replacing the shell's default lights when set. A `DirectionalLightingConfig` with `castShadow` takes `shadowMapSize`, `shadowCameraSize`, `shadowBias`, `shadowNormalBias` for crisp contact shadows. Sky-lit worlds (a `sky()` world feature) get a high-res sun whose shadow camera follows the view each frame, so grounded shadows stay sharp under the player anywhere in a large world.
2246
-
2247
- ## Settings menu
2248
-
2249
- **Settings menu (themed, four layouts, no forced chrome).** The engine builds the whole menu for free — Sound (master + per-bus volume), Graphics (quality/dpr + shadows), Gameplay (FOV slider, default 40–120), Controls (per-action key rebinding, inline click-to-rebind, persisted) — from the game's `audio.buses` and `input` map. What it does **not** do is bolt a fixed gear onto every game: **there is no auto trigger.** You place the entry yourself so it lives *inline with your game's own UI*, never a stray corner overlay. Drop `<SettingsTrigger className=…>` (from `@jgengine/react`) anywhere in your HUD or menu — headless button, `className` for skin/placement, optional `children` to replace the default gear glyph, renders nothing when there's nothing to show. Or call `useSettings().open()` from your own control. Tune the menu via `defineGame({ settings })` (`GameSettingsConfig` from `@jgengine/core/settings/settingsModel`):
2250
-
2251
- - `variant: "panel" | "sheet" | "sidebar" | "fullscreen"` — the layout + skin (default `panel`; `sheet` is the mobile bottom-sheet). All four are fixed-size (no shrink-to-content jitter) and read the game's `--jg-*` theme tokens, falling back to a neutral dark skin.
2252
- - `actions: SettingsActionDef[]` — game-state actions (Restart, Quit to menu, …). They become the **first "Game" tab, shown before anything else** — the home for buttons that used to float over the HUD. Each: `{ id, label, kind?: "default"|"danger", description?, run(ctx) }`; the menu closes right after `run`.
2253
- - `hideBindings: string[]` — input actions to drop from the rebindable Controls list. A game-state key like `restart` belongs in `actions`, not the rebind grid — hide it here so it stops showing up as a "rebindable" control.
2254
- - `surface: "quick"` — additionally mount compact on-screen volume/graphics buttons. Omit for none. `settings: false` — off entirely.
2255
- - `extra: GameSettingDef[]` — append rows to any category, built-in *or a brand-new one* named by `category` (any string). Each row: `{ id, label, category, kind: "slider"|"toggle"|"select", default, min?, max?, step?, options?, onChange?(value, ctx) }`.
2256
- - `categories: SettingCategoryDef[]` — declare custom category tabs, or relabel/reorder built-ins (`{ id, label, order? }`).
2257
- - `hide: SettingCategory[]` — drop built-in categories.
2258
-
2259
- **Game-state controls go in `actions`, never a floating button.** Restart/quit/new-game buttons stapled to the bottom of the HUD are the anti-pattern — declare them as `actions` (first Game tab) and place a `<SettingsTrigger>` inline. A contextual button on a win/lose *results* card is fine; a persistent game-state button pinned over live play is not.
2260
-
2261
- **Present it any way you want.** `useSettings()` (`@jgengine/react`) returns the live controller — `{ categories, actions, variant, surface, isOpen, open, close, setOpen }` — so a game can drive its own pause-menu button, or render `categories`/`actions` (rows carry `value`/`set`/bounds, keybinds carry `rebind`/`reset`) entirely inside its own HUD. `useHasSettings()` gates a custom entry; `useSetting(id, fallback)` reads/writes one value. Set a slider's `min`/`max` explicitly — an omitted range collapses the thumb to 0/1.
2262
-
2263
- ## 8. Motion and game feel
2264
-
2265
- Add purposeful motion for:
2266
-
2267
- - screen entry and exit
2268
- - confirm and cancel
2269
- - warnings
2270
- - score increases
2271
- - objective updates
2272
- - damage
2273
- - victory and failure
2274
- - countdowns
2275
- - pause
2276
- - item pickup
2277
-
2278
- Motion should be brief, readable, interruptible when necessary, coordinated, consistent with the game’s art direction, and respectful of reduced-motion settings.
2279
-
2280
- Do not animate everything constantly. Motion communicates hierarchy, cause and effect, urgency, and state changes.
2281
-
2282
- ## 9. Mobile controls are genre-authored
2283
-
2284
- Shared input mechanics may remain shared. Their visual treatment and arrangement must match the game.
2285
-
2286
- Examples:
2287
-
2288
- **Driving**
2289
- Steering region or wheel, accelerator, brake, handbrake, optional camera/map control.
2290
-
2291
- **Stealth**
2292
- Movement zone, sneak/crouch hold, contextual interaction, temporary map/schedule control.
2293
-
2294
- **Shooter**
2295
- Movement zone, aim region, fire/action cluster, weapon or ability controls.
2296
-
2297
- **Puzzle/arcade**
2298
- Direct drag, tap, swipe, paddle region, or discrete directions. Do not add a joystick without a gameplay reason.
2299
-
2300
- Requirements:
2301
-
2302
- - never cover critical HUD information
2303
- - use the game’s shape and material language
2304
- - fade training labels after learning
2305
- - consider thumb reach
2306
- - preserve accessible target sizes
2307
- - visually respond to activation
2308
- - support optional scaling where appropriate
2309
-
2310
- Do not use one generic translucent controller across all games.
2311
-
2312
- **`presentation: "hud"` games get 3D parity.** A pure-HUD game (no camera rig) now reaches the same input/audio seams as a 3D game:
2313
- - **Touch gestures** — the shell mounts a headless `TouchPlaySurface` in the hud branch too, so `touch.gestures` (swipe/tap) reach actions without the game hand-wiring pointer events on its own canvas. The visible dock stays game-authored per the rule above.
2314
- - **No phantom reservations** — camera action names (`turnLeft`/`turnRight`/`interact`/…) are reserved *only* when a camera rig is active, so a hud game may bind them directly instead of renaming to `steer*`.
2315
- - **Audio actually plays** — audio resumes on the first pointer gesture in hud games (not just 3D), and `playOneShot` self-resumes the suspended context. Trigger sound from anywhere holding `ctx` via `ctx.game.audio.play(soundId, at?)` / `ctx.game.audio.resume()` — the reachable seam over the shell's audio engine.
2316
-
2317
- ## 10. Progressive instruction
2318
-
2319
- Do not leave large control grids visible during gameplay.
2320
-
2321
- Prefer:
2322
-
2323
- - contextual prompts
2324
- - brief onboarding
2325
- - first-use hints
2326
- - a controls screen
2327
- - pause-menu reference
2328
- - icons attached to actions
2329
- - progressive disclosure
2330
-
2331
- Desktop keyboard legends must not appear on touch devices. Prompts should appear near the relevant action, object, or HUD region and clear when no longer useful.
2332
-
2333
- ## 11. Reference directions for flagship games
2334
-
2335
- ### Clockwork Heist
2336
-
2337
- Use gentleman-thief mechanical field-kit language: watch geometry, midnight enamel, aged brass, ivory paper, engraved labels, mechanical shutters, and an authored schedule timeline. The timer should feel like a clock. The schedule should be an on-demand pocket-watch or dossier panel. Touch controls should use brass/enamel construction. Restart belongs in pause, not permanently over the world.
2338
-
2339
- ### Canyon Chase
2340
-
2341
- Use desert pursuit language: battered dashboard, analog instruments, radio display, route strip, warning lamps, and road-sign typography. Target gap should read as a pursuit gauge. Border progress should resemble an odometer, route strip, or mile marker. Driving controls should feel like steering, throttle, brake, and handbrake—not generic circles.
2342
-
2343
- ### Brick Breaker
2344
-
2345
- Use arcade-cabinet language: bezel framing, CRT/vector treatment, arcade numerical readouts, attract mode, launch feedback, and brief level overlays that clear before play. Pause and results should feel like cabinet states, not web dialogs.
2346
-
2347
- These games must remain structurally distinct, not recolors of one component set.
2348
-
2349
- ## 12. Accessibility and performance
2350
-
2351
- Maintain:
2352
-
2353
- - sufficient contrast
2354
- - readable text size
2355
- - keyboard navigation
2356
- - controller navigation where available
2357
- - reduced-motion support
2358
- - visible authored focus
2359
- - touch target sizing
2360
- - semantic labels where practical
2361
- - responsive scaling
2362
- - reasonable DOM and animation performance
2363
-
2364
- Use blur, masks, textures, filters, and full-screen effects carefully, especially on mobile.
2365
-
2366
- ## 13. Screenshot verification is mandatory
2367
-
2368
- Capture and inspect meaningful states:
2369
-
2370
- - desktop title screen
2371
- - desktop gameplay
2372
- - mobile landscape
2373
- - mobile portrait where supported
2374
- - pause
2375
- - victory or failure
2376
- - an interaction prompt
2377
- - touch controls in active use
2378
-
2379
- Inspect for:
2380
-
2381
- - overlap and clipping
2382
- - weak contrast
2383
- - unreadable scale
2384
- - excessive cards
2385
- - website-like composition
2386
- - broken safe areas
2387
- - conflicting hierarchy
2388
- - browser chrome interference
2389
- - poor thumb reach
2390
- - keyboard instructions on touch devices
2391
- - inconsistent art direction
2392
-
2393
- Revise after inspection. Typechecking is not visual proof.
2394
-
2395
- ## 14. Rejection criteria
2396
-
2397
- Require revision when any of these are true:
2398
-
2399
- - normal site navigation remains visible during active gameplay
2400
- - the player must scroll the page to use the game
2401
- - the game is presented inside a normal content card
2402
- - essential HUD is covered by touch controls
2403
- - controls overlap each other
2404
- - keyboard instructions appear on touch devices
2405
- - large instruction panels remain visible during gameplay
2406
- - more than three ordinary card-like panels are persistently visible
2407
- - the main action looks like a standard website button
2408
- - pause resembles a generic website modal
2409
- - victory/failure is only text plus restart
2410
- - restart is permanently visible without a gameplay reason
2411
- - menu elements lack pressed, focused, selected, or disabled states
2412
- - UI changes have no transition or feedback
2413
- - generic virtual controls are used without genre adaptation
2414
- - the theme only changes colors and fonts
2415
- - unrelated UI elements have equal visual weight
2416
- - mobile portrait technically fits but is not intentionally composed
2417
- - important UI sits beneath safe areas
2418
- - ordinary document flow determines the HUD layout
2419
- - generic default styling is used because no art direction was written
2420
-
2421
- ## 15. Compact implementation API appendix
2422
-
2423
- Use the main `jgengine` skill for the authoritative engine API routing. The React package exposes `GameProvider`, hooks, and headless primitives from `@jgengine/react` and its documented subpaths. Common hooks include player/game state, entities, stats, inventory, quests, prompts, clocks, markers, fog, and engine stores. The shell provides `GamePlayerShell`, input integration, devtools, and `GameUiPreview`.
2424
-
2425
- Use these APIs to bind state; do not let API wiring dictate visual composition. Keybind labels should derive from the game’s binding table, and UI actions should dispatch through game commands rather than existing only as click handlers.
2426
-
2427
- Headless components are not finished design. They are behavior and accessibility seams that the game must art-direct.
2428
-
2429
- ## Definition of done
2430
-
2431
- UI work is complete only when:
2432
-
2433
- - the game owns the viewport
2434
- - site chrome is absent during active play
2435
- - no document scrolling is required
2436
- - HUD and control layers have clear responsibilities
2437
- - mobile controls do not cover critical content
2438
- - touch controls match the genre and game identity
2439
- - title, pause, and results screens feel authored
2440
- - interaction states and transitions are present
2441
- - screenshots have been reviewed and revised
2442
- - the implementation remains accessible and performant
2443
- - future generated UI is explicitly prevented from falling back to generic website-card styling
2444
-
2445
- ---
2446
- name: jgengine-world
2447
- description: World API: movement, cameras, physics, maps, sensors, spawn placement.
2448
- ---
2449
-
2450
- # jgengine-world
2451
-
2452
- ## Movement, pose, input
2453
-
2454
- ```ts
2455
- ctx.player.movement.getPose(id) / setPose(id, "crouch") // validates catalog movement.poses
2456
- ctx.player.movement.getAim(id) / setAim(id, "ads") // ADS = aim state + zoom modifier, not a pose
2457
- ```
2458
-
2459
- Poses (`standing/crouch/prone/running`) change the collision capsule (`POSE_HITBOX`); aim pairs with a `player.stats` zoom modifier on `"reticle"`. Game code reads action names only (`isDown("aim")`, `wasPressed("interact")`) — hold vs toggle is resolved by the binding config, never by raw key branches.
2460
-
2461
- ### `ctx.input` — polling the raw controls
2462
-
2463
- `ctx.input` (`@jgengine/core/runtime/inputSnapshot`) is a per-frame held-action snapshot for `onTick` to poll, distinct from the command-dispatch path (bound actions still run commands the normal way): `publish(held: readonly string[])` (the shell calls this once per frame before `onTick`), `isDown(action)`, `held()` for the full list. Publishing never bumps `ctx.version()` — it's a poll surface, not reactive state.
2464
-
2465
- **`repeatMs`** — bind an action as `{ hold: [...], repeatMs: 150 }` (`input/actionBindings`) and the shell fires its command on the down edge, then again every `repeatMs` while held, resetting on release (hotbar-style repeat-fire without a per-game timer).
2466
-
2467
- **Aim on generic commands** — every command resolved from a bound action now runs with `{ yaw, pitch, aim: { yaw, pitch } }` in its payload, so a handler can read the camera-relative aim without going through `pointer.worldHit()`.
2468
-
2469
- ### Controller kinematics — movement config, physics tuning, respawn
2470
-
2471
- `PlayableGame.movement` (`PlayerMovementConfig`) tunes the shell's built-in walk controller (never touch `PhysicsWorld` for ordinary player movement):
2472
-
2473
- ```ts
2474
- movement: {
2475
- mode?: "free" | "axis" | "grid"; // "free" (default) camera-relative; "axis" locks travel to one world axis; "grid" snaps each committed position to cell centers
2476
- axis?: "x" | "z"; // world axis for mode "axis". Default "x"
2477
- cellSize?: number; // cell size for mode "grid". Default 1
2478
- collideObjects?: boolean; // collide the walking player against placed scene objects (unit-box AABBs) even without collision.voxel
2479
- beforeCommit?: (frame: MovementCommitFrame) => readonly [number, number, number] | undefined | void; // intercepts each frame's resolved position before the pose commits; return a replacement to constrain/redirect the step
2480
- }
2481
- ```
2482
-
2483
- `nav/navConstrain`'s `constrainToNavGrid(grid, { y? })` is a standalone walkable-pass-through + wall-sliding helper over a `nav/navGrid`; its `(proposed, entity)` shape doesn't match `beforeCommit`'s `(frame) => [x,y,z]` signature directly, so wire it in with a small adapter closure rather than passing it straight through.
2484
-
2485
- `defineGame({ physics: { gravity, jumpVelocity } })` drives the kinematics controller directly: `gravity` (signed, e.g. `-24`) and `jumpVelocity` override the built-in tuning; omit either to keep the defaults. This is the one global exception to "never player tuning in `defineGame`" — it configures the shared controller, not a catalog entry. It is still **distinct** from `physics/physicsWorld`'s standalone rigid-body sim (see below) — `defineGame.physics` never touches that sim.
2486
-
2487
- **Vertical motion intents** — `ctx.player.motion` (`@jgengine/core/runtime/motionIntents`): `impulse(vy)` adds to the vertical velocity the shell's controller is about to integrate, `setVerticalVelocity(vy)` replaces it outright, `setY(y)` wins over physics for that frame. The shell calls `takePending()` once per frame, before integrating gravity, to drain what accumulated; this is not reactive state (jump pads, launch abilities, bounce pads).
2488
-
2489
- **`collision: { voxel: true }` — object lattice as solids.** When set, the shell's local player uses a voxel body whose `isSolid(x,y,z)` is rebuilt from `ctx.scene.object.list()` as exact `` `${x},${y},${z}` `` keys (integer cell queries). Integer-placed objects are walkable/blocking; fractional-coord objects decorate without colliding. Removing an object opens a real trapdoor under gravity — do not fake the fall with `setPose`. `visual.scale` does not shrink the collider (always a unit cell). The voxel body is created once; prefer `motion.setY` / `impulse` for vertical relocation — full XY teleport of the local voxel body is not supported. Solid cache rebuilds when object **count** changes. Recipe: `jgengine` → voxel trapdoor board.
2490
-
2491
- **Respawn** — `ctx.scene.entity.spawnPoseOf(id)` reads the spawn pose, `resetToSpawn(id)` teleports back to it with zero velocity, `resetAllToSpawn(filter?)` does it for every entity matching an optional filter and returns the count (round resets, out-of-bounds recovery).
2492
-
2493
- ## Touch & mobile
2494
-
2495
- Every game is touch-playable with zero per-game input code. On a coarse-pointer device the shell derives a `TouchScheme` from the game's `input` bindings (`deriveTouchScheme`, `@jgengine/core/input/touchScheme`): a virtual joystick binds whichever of `moveForward`/`moveBack`/`moveLeft`/`moveRight` (or `turnLeft`/`turnRight`) are bound, on-screen buttons cover the remaining actions, and drag-to-look mounts automatically for `first`-person camera rigs. Touch controls feed synthetic `touch:<action>` codes into the same `ActionStateTracker` the keyboard uses — game code reads `isDown`/`wasPressed` and never branches on input source.
2496
-
2497
- Refine the derived scheme with the `touch` field of `defineGame({...})` (`TouchControlsConfig`, all optional):
2498
-
2499
- ```ts
2500
- touch: {
2501
- gestures: {
2502
- tap: "rotateCw",
2503
- swipeUp: "hold",
2504
- swipeDown: "hardDrop",
2505
- drag: { left: "shiftLeft", right: "shiftRight" },
2506
- },
2507
- buttons: [
2508
- { action: "rotateCcw", label: "CCW" },
2509
- { action: "softDrop", label: "Soft" },
2510
- ],
2511
- },
2512
- ```
2513
-
2514
- - **`gestures`** — bind `tap` / `swipeUp` / `swipeDown` / `swipeLeft` / `swipeRight` / `drag` (`{ left?, right?, up?, down?, stepPx? }`, repeats its action every `stepPx` of travel) on the play surface. An action consumed by a gesture is removed from the derived button set.
2515
- - **`buttons`** — curate the on-screen cluster (order preserved; bare string or `{ action, label?, icon? }`); omit to auto-derive one button per remaining bound action. Buttons render a glyph, not text: `iconForAction` (`@jgengine/react/gameIcons`) resolves the action name to a `GameIconName` (`jump`, `sprint`, `rotateCw`, `hardDrop`, `swap`, `hand`, `restart`, arrows, …), the `label` becomes the `aria-label`; set `icon: "<GameIconName>"` to pick one explicitly or `icon: false` to force the text label.
2516
- - **`hidden`** — actions to drop from the derived buttons without gesture-binding them.
2517
- - **`movement: false`** — suppress the virtual joystick even when movement actions are bound.
2518
- - **`look` / `lookSensitivity`** — drag-to-look on the play surface; defaults to `true` for `first`-person camera rigs, `0.005` radians/px.
2519
- - **`touch: false`** — opt out entirely when the game's own DOM UI is already touch-native.
2520
-
2521
- `useDisplayProfile()` (`@jgengine/react/display`) reports `{ coarsePointer, compact, portrait }` — live media-query state, SSR-safe — for adaptive HUD layout; see the mobile/touch rules in [`../jgengine-ui/reference.md`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-ui/reference.md).
2522
-
2523
- ## Interaction — `proximityPrompt`
2524
-
2525
- One primitive for all float UI: `{ radius, display, invoke }` where `display` is `{ kind: "keybind", actionId }` | `{ kind: "gauge", gaugeId }` | `{ kind: "label", text }` and `invoke` is `{ command, args? }` or null (display-only). `talkable: "dialogue_id"` on an entity expands to a talk prompt. Engine picks the nearest prompt in radius (priority tie-break). Never build per-game hint resolver chains.
2526
-
2527
- ## Pointer-driven input and navigation
2528
- The **pointer is a service, not per-game glue**. Opt in with `camera` plus a `pointer` config in `defineGame({...})`; the shell casts the cursor into the world and dispatches commands you define — verbs stay commands, catalogs stay data.
2529
- - **`pointer.worldHit()` (shell service).** The shell raycasts the cursor to `{ point, normal, entity, object }` (a renderer-free `PointerHit` from `@jgengine/core/input/pointer`) — entity/object are the topmost instance ids under the cursor, else `null`, with a ground-plane fallback for open terrain. Consume it renderer-free: `aimToPoint(origin, point)` builds an `Aim` for `item.use`/projectiles (ground-target skillshots, twin-stick), `groundOf(hit)` drops to `[x, z]` for routing. `pointer.worldHitCenter()` is the same raycast pinned to the viewport center instead of the live cursor — the reticle-aim query a locked/hidden-cursor rig (first-person, gamepad) needs when there is no cursor position to read.
2530
- - **The `pointer` field of `defineGame({...})`** (all optional): `moveCommand` (left-click ground → `run(cmd, { point, entity, object })`, click-to-move), `select` (left-drag marquee + single-click box-select of entities), `orderCommand` (right-click ground → `run(cmd, { selection, point })`, issue a command to the selection), `contextMenu` (right-click an entity/object → its catalog `verbs` menu), `secondaryCommand` (right-click ground/entity/object → `run(cmd, { point, entity, object, aim })` when neither `orderCommand` nor `contextMenu` claims the click — a generic right-click verb for games with no selection/RTS model), `aim` (route the primary ability's aim to the cursor), `grabWorldItems` (left-click a `worldItem` within pickup radius → engine-owned `ctx.scene.worldItem.pickup`, no game command). Enabling `select`/`moveCommand` frees the left button for verbs; orbit moves to middle-drag.
2531
- - **`createDragCapture({ maxPull?, grabRadius? })`** (`@jgengine/core/input/pointer`) — a renderer-agnostic slingshot/drawback state machine: `begin(origin, at)` starts a pull (rejected outside `grabRadius`), `update(at)` tracks the cursor, `release()` returns the final `DragState { origin, current, pull, magnitude, fraction }` (pull clamped to `maxPull`), `cancel()` aborts. Angry Birds-style slingshots, bow drawback, throwable wind-up — pair with `aimToPoint` to fire.
2532
- - **Selection math** (`scene/selection`) is pure and testable: `createSelectionSet()`, `screenRect`/`selectWithinRect`/`isMarquee` over projected screen points.
2533
- - **Context menu** (`interaction/contextMenu`): a catalog entity/object carries `verbs: contextVerb(label, command, args?)[]`; the shell builds the menu with `buildContextMenu` and dispatches the chosen command via `contextVerbInput` (verb args + `target`/`point`, so one handler can walk-then-act).
2534
- - **Navmesh + A\*** (`nav/navGrid`): `createNavGrid({ bounds, cellSize, diagonal? })` → mark obstacles with `blockAabb`/`setWalkable`, or `populateNavGridFromEnvironment(grid, world)` to block every generated building's footprint on an `environment()` world's `structures` in one call (returns the count blocked) instead of hand-walking the district. `findPath(grid, from, to, { clearance?, smooth?, stepCost? })` returns a string-pulled `[x, z]` polyline (blocked start/goal snap to the nearest walkable cell) feeding **both click-to-move and AI routing**; `stepCost?(from, to)` multiplies the base cost of a grid step — `slopeStepCost(terrainField, weight?)` is the ready-made factory that penalizes steep terrain (routes around cliffs instead of over them). Renderer-free — AI and gameplay consume it without the shell.
2535
- - **`pathFollow`** (`nav/pathFollow`): the lighter authored-polyline mover for tower-defense creeps that needs no navmesh — `createPathFollow({ waypoints, speed, loop? })` + pure `advancePathFollow(config, state, dt)` (crosses multiple waypoints per tick, reports `done`/`heading`/`distanceTravelled`). Feed it a navmesh route with `pathFromNav(route, elevation, offset?)` and the same follower drives click-to-move — `elevation` is either a fixed `y` or a `{ sampleHeight(x, z) }` field (any `TerrainField` qualifies), so a route across relief rides the ground instead of a flat plane.
2536
- - **`constrainToNavGrid(grid, { y? })`** (`nav/navConstrain`) is a standalone walkable-pass-through + wall-slide helper: it passes through walkable moves, slides along walls at the navmesh boundary instead of stopping dead, and optionally remaps `y` to the grid. Its `(proposed, entity)` shape doesn't match `PlayerMovementConfig.beforeCommit`'s `(frame) => [x,y,z]` signature, so wire it in with a small adapter closure (see "Controller kinematics" above) to wall a player/AI to the same navmesh `findPath` already routes against.
2537
- ## AI — director, threat, jobs, crowds (`ai/*`)
2538
- Renderer-free AI over the same navmesh (`findPath`/`pathFollow`) gameplay already uses. Everything ticks on **game-time `dt`** (the `ctx.time` simClock delta), so it obeys pause and fast-forward for free. Manifests, patrol routes, job definitions, threat weights, and POIs are **game data** — the primitives own the loop, the catalog owns the content.
2539
- - **Spawn director** (`ai/spawnDirector`) — budgets and escalates spawns for wave shooters and difficulty directors (Brotato, Bloons TD 6, Risk of Rain 2, Helldivers 2, Deep Rock Galactic). `createSpawnDirectorState(config)` then pure `advanceSpawnDirector(config, state, dt, { alive, players? })` → `{ state, spawns: SpawnRequest[] }`. Each `WaveManifest` grants a `budget` spent on affordable weighted `SpawnEntry`s (`cost`/`weight`/`minWave`), capped by `maxAlive`; `duration` auto-advances waves (or call `advanceWave` on "wave cleared"). Budget also trickles via `budgetPerSecond`, ramps a difficulty curve with `escalationPerSecond` (grows with sim-time), scales with `playerBudgetPerSecond`, and surges on `raiseAlert(state, amount)` decaying over time (bug-breach/dropship escalation). Seeded (`seed`) so ticks are deterministic. `pickSpawnPoint(points, players, { roll, bias })` biases placement toward (or away from) players. `config.spawnPoints?: NavPoint[]` lets the director pick a point itself: each `SpawnRequest` then also carries `point` (the chosen `[x, z]`, biased by `config.spawnPointBias`) and `laneId` (the point's index into `spawnPoints`) — feed multiple named lanes/portals and read `laneId` back to route the spawned entity down its lane instead of correlating positions by hand.
2540
- - **Threat table** (`ai/threat`) — MMO/extraction aggro (Escape from Tarkov, WoW-style tanking). `createThreatTable({ decayPerSecond?, max?, forgetBelow? })`: `add(source, amount)` accumulates, `decay(dt)` bleeds off per game-second and forgets emptied sources, `highest({ current?, stickiness? })` returns the top-threat source to feed `scene/targeting` — `stickiness` (e.g. 1.1) keeps the current target until another exceeds it by that factor, so aggro doesn't jitter. `taunt(source, durationSeconds)` forces the mob onto a tank for that window (overriding `highest`) and lifts the taunter's threat to the current top so aggro stays after the window; `forcedTarget()` reports the active taunt, `decay(dt)` counts it down. `ranked()` for a threat meter.
2541
- - **Patrol** (`scene/behaviors`) — `patrol({ waypoints, speed, loop? })` is a `BehaviorDescriptor` (a route is data) that layers a fixed beat on top of `wander`; drive it with `createPathFollow`/`advancePathFollow` (lane creeps, scav patrols in Deadlock/Tarkov). Route waypoints between guard posts with `findPath`.
2542
- - **Job board** (`ai/jobBoard`) — colony/companion task assignment (Palworld stations, Schedule I employees, Sons of the Forest directives). `createJobBoard()`: `post(job)` a `JobDef` (`station`, `work` seconds, `priority`, `arriveRadius`, `repeat`), `claim(worker)` auto-pulls the highest-priority queued job or `assign(worker, jobId)` for a player order (steals it from its holder), `release` requeues. Per tick `advance(worker, dt, { distanceToStation })` runs the state machine `travelling → working → done` (path to `station(worker)` via `findPath`, occupy, run the loop), returning a `JobReport` on completion; `repeat` jobs re-run as a production loop and report each cycle.
2543
- - **Crowd flow** (`ai/crowd`) — many agents routing to their own points of interest with congestion (Two Point Museum corridors, Dave the Diver seating). `computeFlowField(grid, goals, { clearance?, congestion? })` runs Dijkstra from the goals over the walkable grid → `direction(point)`/`next(point)` steer any agent toward the nearest goal (no per-agent A*). `createCrowdField(grid)` tracks per-cell occupancy (`enter`/`leave`/`count`); pass `crowd.penalty(weight)` as the field's `congestion` to reroute flow around crowded cells each tick. `selectPoi(pois, from, { roll, occupancy?, distanceBias?, distance? })` weights a POI by appeal and proximity, skips ones at `capacity`, and accepts a `distance` override (e.g. `findPath` length) to choose over the navmesh, not line-of-sight.
2544
- - **Factions & reputation** (`faction/factions`, `faction/reputation`) — allegiance-based hostility for RPGs/MMOs/strategy (WoW-style Horde-vs-Alliance, at-war reputation grinds, guards-vs-thieves). `createFactionGraph({ factions, symmetric?, unaligned? })` models a faction-vs-faction relation matrix — each `FactionDef` lists `relations` toward others (`"hostile" | "neutral" | "friendly"`) with `towardSelf`/`towardOthers` fallbacks; `relationBetween(a, b)` resolves it (mirroring undeclared directions when `symmetric`, defaulting `unaligned` for unknowns). `createFactionRoster(graph)` maps entities to factions (`assign`/`factionOf`/`members`), then `relationBetweenEntities`/`isHostile`/`hostilesOf(observer, candidates)` answer "who is my enemy" as a data lookup — feed it into `scene/targeting`'s `classify` and `ai/threat` eligibility instead of a per-game role-string check. `createReputationLedger({ tiers?, initial?, min?, max? })` is the per-actor standing ledger: `gain`/`set`/`standing` track reputation, `tier`/`relation` map it through `DEFAULT_REPUTATION_TIERS` (the classic Hated→Exalted ladder, or your own), `standings(actor)` snapshots all. `effectiveRelation({ base, ledger, actorId, factionId })` overlays a player's earned standing on the base faction relation, so a reputation grind flips a normally-hostile faction to neutral/friendly.
2545
- ## Map, fog of war & ping
2546
- Minimap/world-map/fog/compass state is renderer-free core (`world/*`), the top-down terrain image bakes in the shell, and the minimap/compass/world-map are react components. Ping rides the existing party + feed — it is not a new channel.
2547
- - **Markers** (`world/markers`): `createMarkerSet()` is a reactive keyed set of `MapMarker { id, kind, position, label?, owner?, expiresAt?, meta? }` — `add`/`remove`/`get`/`list`/`query({ kind, owner, near, radius })`/`prune(now)`/`subscribe`. `kind` is a game-owned catalog string; `DEFAULT_MARKER_KINDS` (objective/enemy/loot/location/danger/ping/player/ally) supplies colors + glyphs the react map reads (override with your own `MarkerKindStyle` palette). Objective/entity/loot markers all live here.
2548
- - **Fog of war** (`world/fog`): `createFogField({ bounds, cellSize })` is reveal-on-event — `reveal(x, z, radius?)` (a dig/act), `revealAlong(from, to, radius?)` (a walked trail); once a cell is revealed it stays revealed. `isRevealed`/`fraction`/`cells()` (stable snapshot for rendering)/`reset`/`subscribe`.
2549
- - **Minimap math** (`world/minimap`): pure projection + bearings — `projectToMinimap(worldPoint, { center, worldRadius, size, rotate? })` → pixel `{ x, y, inside, distance }` (north = −Z maps up), `clampToMinimapEdge` for off-map markers, `compassBearing(from, to)`/`headingToBearing(yaw)`/`bearingToCardinal`/`relativeBearing` for the compass strip.
2550
- - **Ping** (`game/ping`): `classifyPing(hit, { roleOf, categoryOf }, options?)` turns a G1 `pointer.worldHit()` `PointerHit` into a category (hostile entity → `enemy`, tagged object → its catalog category, open ground/ally → `location`). `createPingSystem({ markers, feed, party?, ttlMs?, classify, classifyOptions? })` composes classify + broadcast: `ping(from, hit, category?)` classifies, drops a categorized marker, and pushes the `PingPayload` to the party feed under `PING_FEED_ACTION` (`"party.ping"`) — the shell's feed bridge fans it to the squad. `DEFAULT_PING_CATEGORIES` is the enemy/loot/location/danger wheel. Enable the verb with the `pointer.pingCommand` field of `defineGame({...})`: the shell binds the `ping` input action → `worldHit()` → runs your command with `{ point, entity, object, normal }`.
2551
- - **Shell render** (`@jgengine/shell/map`): `bakeTerrainMap(field, bounds, { resolution? })` renders a `TerrainField`/`RegionField` to a top-down PNG data-URL for the map background; `MapMarkerBeacons({ markers })` renders world-space beacons (the visible side of a ping) — wire via the `WorldOverlay` field of `defineGame({...})`. See the `extraction-map` demo game.
2552
- ## Sensors, vision & observer tools (`sensor/`)
2553
- Pure `@jgengine/core/sensor/*` primitives for querying and surfacing world state the player can't normally see or reach through the standard occlusion/proximity rules — reveal vision, hidden-state sensors, photo-mode framing, and session replay. Shell renderers/HUD pieces live in `@jgengine/shell/vision` and `@jgengine/shell/replay`.
2554
- | Primitive | Answers |
2555
- |-----------|---------|
2556
- | `createRevealQuery({ resolvePosition, resolveTags, candidates })` → `RevealQuery` | `inRadius(center, radius, tags)` — occlusion-ignoring tagged-entity radius query (Dark Sight / detective-vision reveal, #115). `inRadius` already never checks occlusion (only combat's AoE `effect()` layers a LoS filter on top of it) — this is that same query shaped for a vision readout: scoped to catalog-declared tags, sorted nearest-first |
2557
- | `probeHiddenState(origin, sources, { range, variableId, falloff? })` / `probeHiddenStateAll(...)` → `SensorReading \| null` | A sensor verb: reads a hidden zone/entity state variable (EMF/thermometer/geiger, #116) in range, strongest reading first; `strength` falls off linearly with distance by default |
2558
- | `projectToView(camera, point)` → `FrustumProjection` | Pure camera-frustum projection (no three.js) — `inView`, `screenX/screenY` (-1..1), `distance` |
2559
- | `framingScore(projection, config?)` → `number` | 0..1 framing quality from screen-center placement + distance-to-ideal (photo-mode "is this subject framed", #117) |
2560
- | `createFrustumSensor(config?)` → `FrustumSensor` | `tick(camera, targets, dt)` — per-target in-view + framing + `dwellSeconds` (resets the instant a target leaves frame); a view-frustum sensor on a held camera object (Content Warning-style monster-filming scoring) |
2561
- | `createRecordingBuffer(options?)` → `RecordingBuffer<T>` | `append(t, data)` / `seek(t)` / `range(fromT, toT)` — a session-recording buffer for replay/photo mode/kill-cam (#120), keyed on game-time so pause/fast-forward scrub consistently |
2562
- | `colorDistance(a, b)` / `concealmentScore(entityColors, backgroundColors)` / `createConcealmentSensor(config?)` → `ConcealmentSensor` | Camouflage/blend-in scoring — how well an entity's palette matches its surroundings (hide-and-seek, stealth camo checks) against a `threshold` |
2563
- | `createFreezeMonitor(config?)` → `FreezeMonitor` | Detects a tracked subject moving past a tolerance speed during a "freeze" window (red-light-green-light, statue games) and reports `FreezeViolation`s |
2564
- Shell wiring: `@jgengine/shell/vision/RevealVision` (`RevealHighlights` — depth-test-disabled 3D highlight meshes for tagged entities in radius, meant for `WorldOverlay`; `RevealScreenTint` — full-screen CSS tint for "vision mode is on", meant for `GameUI`), `@jgengine/shell/vision/HiddenStateProbeHud` (`SensorReadoutMeter` — needle-strength HUD readout), `@jgengine/shell/vision/FrustumSensorHud` (`FrustumSensorReadout` — drives the sensor off the live render camera via `useThree`/`useFrame`, portals its HUD through drei's `Html fullscreen`), `@jgengine/shell/replay/useSessionRecorder` (records an entity's pose into a `RecordingBuffer` every frame; drive an observer-cam ghost, scrubber, or kill-cam export from it). The detached spectator/photo cam itself is the `observer` camera rig (see Camera rigs above) — bind it to any entity or fixed point.
2565
-
2566
- ## World features
2567
-
2568
- Renderer-free world surface — query primitives, environment fields + weather + realm composition, survival meters/moodles, interactive building & terraform, the optional headless physics world, vehicles/mounts/racing, and spawn placement. Full surface: **[reference.md](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-world/reference.md)**.
2569
-
2570
- ## Level design — places, not noise
2571
-
2572
- Procedural terrain is a canvas, never the level. A world with only `terrain()` + spawn clusters reads as an empty sandbox no matter how big its bounds. Every open-world game composes **places** on top of the canvas, and the checklist below is the floor, not the ceiling:
2573
-
2574
- - **Every site is a set-piece.** A camp is a wall ring with a deliberate gate opening facing the approach, cover inside, a tower or banner as its silhouette — never a bare radius of spawns. Compose from placed objects (`ctx.scene.object.place` with stable instance ids) driven by pure data functions (ring/scatter/route generators) so bun tests can assert the composition without rendering.
2575
- - **Roads make the space legible.** Physically connect sites: trace waypoint routes between them and feed the points into the terrain descriptor's `flatten` masks so the route is genuinely walkable, then dress it — markers, wrecks, signposts — every ~60 units so the player can read the path at a glance. A test should walk the route and assert the step height stays small.
2576
- - **One landmark per region.** A water tower, crashed vehicle, gate, or monument visible from the approach gives orientation without a map. Distinct silhouette + distinct color.
2577
- - **Anchor → approach → arena → reward.** Each combat site needs a visible anchor drawing the player in, a readable approach (the road), an arena with cover the AI and player both use, and a visible reward (chest, vendor, quest turn-in) at the back so clearing it feels earned.
2578
- - **People, not just spawns.** Hubs hold named NPCs (talkable entities with prompts), vendors, and light props (lamps, crates, stalls). A hub with only vending-machine objects is a menu, not a town.
2579
- - **Density budget.** Inside a site's flatten radius aim for roughly one placed object per 6–10 units of radius; along roads one prop per ~60 units; open wilderness stays sparse so sites contrast. Frustum/distance culling is automatic — err toward more dressing, not less.
2580
- - **Guided openness, never invisible walls.** Total freedom reads as emptiness: herd the player physically. Raise terrain amplitude so off-road relief is genuinely unclimbable, gate slope in `movement.beforeCommit` (block a step whose ground rises past a climb limit, with per-axis slide so it feels like a wall of rock, not a script), and carve the intended route as the one low path. Then buy the openness back deliberately: side pockets (a den, a cache, a wreck field) hang off the main road on short spur routes, each with its own reward, so exploration branches from the path instead of dissolving it. Test the herding the same way you test the road: assert off-road samples rise above the climb limit while every route and spur stays under it.
2581
-
2582
- ## Turn-based & tactics (renderer-free)
2583
-
2584
- # jgengine domain API — World features
2585
-
2586
- Reference module for the [`jgengine-world` API](SKILL.md) skill. Load this when you need the renderer-free world surface.
2587
-
2588
- ## World features
2589
-
2590
- Descriptors from `@jgengine/core/world/features` — config data the runner/world layer interprets:
2591
-
2592
- | Feature | Use |
2593
- |---------|-----|
2594
- | `biomes({ map, zones, bounds? })` | Region atmosphere/rules layering; zones reference biome ids |
2595
- | `voxel({ seed, generate?, streaming? })` | Block worlds |
2596
- | `plots(config)` | Shared city + instanced interiors |
2597
- | `tilemap({ map })` | 2D/2.5D levels |
2598
- | `flat()` | Plain arena |
2599
- | `environment({ terrain, sky, weather, vegetation, water, structures, pads })` | Composable outdoor scene — terrain + sky/time-of-day + rain/snow + grass + ocean + buildings + ground pads. Each field takes the matching descriptor: `terrain()`, `sky()`, `rain()`/`snow()`, `grass()`, `ocean()`, `building()`, `pad()`. `building()`, `ocean()`, `rain()`/`snow()`, and `grass()` take `position: [x, z]` to site a cluster/water body/weather band/vegetation patch away from the origin (several settlements, an offset lake, per-biome rain, a distant meadow) — the weather/grass `position` is sugar for `area.position`, so a biome-banded world places each band by zone; building clusters ground-snap to the terrain field per building; each `pad()` (a flat platform/paved patch — `{ center, size: [w,d] | { radius }, height?, color?, rotationY? }`) implicitly flattens the terrain beneath it via a `TerrainFlattenMask`, so a building pad or spawn circle never fights the noise field underneath |
2600
-
2601
- `biomes`/`voxel`/`plots`/`tilemap` share a `WorldGridConfig` (`cells?: WorldGridCell[]`, `cellSize?`, `baseHeight?`, `defaultColor?`) — a `WorldGridCell` is `{ x, z, height?, color? }`, one extruded box per cell. `resolveGridInstances(config)` (`@jgengine/core/world/gridInstances`) is the pure cell→instance math (position, scale, color per cell); the shell renders the result as a single `THREE.InstancedMesh` **automatically whenever `PlayableGame.environment` is unset and `game.world` is one of these four grid kinds** — no manual render wiring for a cell-based world, same auto-render convention as `environment()` worlds.
2602
-
2603
- `terrain()`'s `material` (a named palette — `"grass" | "sand" | "snow" | "rock" | "ash"`, resolved via `resolveTerrainPalette`/`TERRAIN_MATERIAL_PALETTES` in `world/terrain`) sets the default low/high/waterline colors; `colors: { low?, high?, waterline? }` overrides any of them field-by-field, and `segments` tunes the render mesh's subdivision. `biomeBands: BiomeBand[]` (`{ z, fade?, material?, colors? }`) cross-fades the **ground palette along the world's z axis** — ordered zones (vale → marsh → peaks) that blend across a `fade`-wide window (default 64) centered on each boundary; it's the linear counterpart to the radial `materialRegions` (which paint on top; each region is a `TerrainCircleRegion` (default), `TerrainPolylineRegion` (roads/rivers), or `TerrainRectRegion` (rotatable districts), sharing a `TerrainRegionStyle`). Pure/testable via `createTerrainPaletteSampler`/`createBiomeBandSampler` in `world/terrain`; the shell renders it through the same per-vertex `paletteAt` seam as regions, no extra wiring. (Per-zone **fog/sky** cross-fade isn't wired yet — three.js fog is scene-global — so bands drive ground color today.) `flatten: TerrainFlattenMask[]` (`{ center, radius, height?, falloff? }`) carves explicit flat circles into the noise field independent of pads — building foundations, spawn circles, roads — blending back to the noise height over `falloff` (default `radius * 0.5`). `detail: TerrainDetailConfig` (`{ rockColor?, sandColor?, snowColor?, rockSlopeStart?, snowHeight?, waterLevel?, detailScale?, macroScale?, roughness?, strength? }`) swaps the flat vertex-colour ground for a procedural noise shader (`@jgengine/shell`'s `createTerrainDetailMaterial`, defaults via `resolveTerrainDetail`): it keeps the biome-tinted base and blends noise-broken **rock by slope**, **sand by waterline**, and **snow by height** over it — textured-reading terrain with no image assets, full PBR (lit/shadowed/fogged), composing with the post-processing chain. Omit for the flat look. `sky({ preset?, timeOfDay?, horizonColor?, zenithColor?, sunIntensity?, ambientIntensity?, fog? })` — `preset: "day" | "dusk" | "night"` (default `"day"`) is the static look; `timeOfDay: true` instead drives sun position, sky colors, and fog from the world clock's `calendar().dayFraction` every frame (`@jgengine/shell`'s `TimeOfDayDaylight` mounts this automatically for an `environment()` world with `sky` set — no per-game render wiring). The sky dome renders a bright HDR sun disc + warm glow (aligned to the sun light, so it blooms through a `postProcessing` chain), a mid-sky procedural cloud band, and a horizon haze — no HDRI assets; richer than a flat gradient with zero config. **Gotcha:** `sunIntensity` / `ambientIntensity` are honored only on the **day** keyframe (`daylightCycle` builds dusk/night/dawn from fixed constants). Raising intensities under `preset: "dusk"` or `"night"` does nothing — use `preset: "day"` plus warm `horizonColor`/`zenithColor` when the first screenshot must be bright and readable (see `jgengine`'s first-shot art recipe).
2604
-
2605
- **Flatten-mask composition semantics** (`withFlattenMasks` — easy to fight if guessed): masks apply **sequentially and the last matching mask wins outright**; there is no mask-to-mask blending. Inside `radius` the height becomes that mask's `target` exactly; in the `radius..radius+falloff` annulus it lerps from `target` back to the **raw noise height**, never to another mask's output. `target` defaults to the raw noise height at the mask's own center (`height` overrides). Consequences to know before composing roads or multi-site layouts: (1) a chain of default-height circles stair-steps, because each snaps to its own center's noise — give road masks explicit `height` values ramped between the endpoint site targets; (2) a later mask's falloff annulus punches raw-noise bumps through an earlier flat area — order masks so the surface that must win comes last, keep road `falloff` small (≤ radius), and skip road circles inside an already-flat site radius; (3) raw noise rarely herds — to guarantee canyon walls, emit masks with `height` *above* the surroundings flanking the corridor. A working road-ramp recipe (overlapping circles every ~12 units, height ramped between site targets, ramp clamped flat inside each site radius, wall masks alongside) lives in `Games/borderlands2/src/game/world/level.ts`.
2606
-
2607
- `parentSpace` positions are local to that space — convert at seams only.
2608
-
2609
- ### Query primitives (renderer-free, for gameplay)
2610
-
2611
- Pure `@jgengine/core` functions so gameplay reads the same world the shell renders — no three.js needed:
2612
-
2613
- | Primitive | Answers |
2614
- |-----------|---------|
2615
- | `resolveTerrainField(terrain(...))` / `noiseField(cfg)` → `TerrainField` | `sampleHeight(x,z)`, `sampleNormal(x,z)`, `waterLevel` — ground-snap, collision, camera. `resolveGroundStep` slope-limits movement |
2616
- | `snapToGround(field, position, offset?)` → `[x,y,z]` | Replaces a position's `y` with the field's sampled ground height (+ `offset`) at its `x`/`z` — the pure version of a spawn/placement ground-snap |
2617
- | `snapEntityToGround(entities, id, field, offset?)` → `boolean` | Ground-snaps an already-spawned entity in place via `entities.setPose` — false when `id` is unknown; the imperative sibling of `snapToGround` for "drop this entity onto the terrain right now" (mount dismount, teleport, respawn) |
2618
- | `windField(cfg)` → `WindField` | `at(t)`, `atPoint(x,z,t)`, `strengthAt` — one wind source for weather sway, grass, sailing, fire spread |
2619
- | `waterSurface(cfg)` / `waterSurfaceFromDescriptor(ocean(...))` → `WaterSurface` | `height(x,z,t)`, `normal`, `displace` — buoyancy, floating, shoreline (CPU Gerstner matching the ocean shader) |
2620
- | `scatter(cfg)` → `ScatterPoint[]` | Seeded, overlap-aware point distribution — vegetation, props, lots, spawn points (`minDistance`, `avoid` rects) |
2621
- | `createRegionField({ regions })` → `RegionField` | `sampleRegion(x,z)` blends content-agnostic biomes by nearest selector — height + `tint`/`water`/`fog`/`speedMultiplier` + opaque `data`. Extends `TerrainField`, so it ground-snaps too |
2622
- | `scatterItems(field, area, layersFor)` → `ScatterInstance[]` | Region-driven content scatter — density per region, grounded, above-water/slope-aware. `pickWeighted` for weighted rolls. (vs `scatter`'s pure geometric points) |
2623
- | `buildingIndex(district)` → `BuildingIndex` | `at`/`within`/`nearest`/`isInside`/`blockers` over a generated district — placement avoidance, pathfinding |
2624
-
2625
- **Voxel field (`world/voxelField`).** `createVoxelField<T extends string>({ chunkSize? })` (default 16) is a logical block lattice for voxel games and instanced renderers — distinct from the `voxel()` `WorldFeature` descriptor above (that's the runner-level world kind; this is the block data structure a voxel game's gameplay reads and writes). `set`/`remove`/`get`/`has`/`fill`/`clear`/`count`/`cells`/`bounds` are the block CRUD (`set` returns `false` only when the identical type is already there — a no-op write). `neighbors(x, y, z)` returns the 6-adjacent occupied cells; `exposedFaces(x, y, z)` returns the `VoxelFace`s (`"px"|"nx"|"py"|"ny"|"pz"|"nz"`) not touching another voxel — feed that straight into greedy-meshing/face-culling. `raycast(origin, direction, maxDistance)` runs a 3D DDA and returns `{ x, y, z, type, face, adjacent, distance }`, where `adjacent` is the empty cell just in front of the hit — the placement target for block-place tools. Renderers dirty-track via `chunkOf(x, y, z)` + `chunkVersion(chunk)` and `subscribe(listener)`, so an instanced mesh only rebuilds the chunks that changed. For a non-`environment()` voxel world, assert on `field.summary()` (`{ blocks, types, bounds }`) the same way an `environment()` world asserts on `summarizeEnvironment` (see `jgengine-verify`).
2626
-
2627
- **Destructible terrain (`world/carve`).** Two runtime-editable primitives for dig/carve worlds. `VoxelVolume` is a dense grid of material ids (0 = empty) — `carve({ center, radius, toolStrength })` clears a sphere of solid cells the tool is strong enough to break and returns the count removed (feed a loot roll), `deposit({ center, radius, material })` fills one (Deep Rock tunnels, Astroneer terrain add); `solidAtWorld` reads it back for collision. `CarvableField` (via `carvableTerrain(base)`) wraps any `TerrainField` and writes craters/mounds into its height — `carve({ x, z, radius, depth })`/`deposit({ x, z, radius, height })` — so ground-snap, collision, and the shell mesh all read the deformed surface (Helldivers 2 explosion craters). Cell strengths come from a `VoxelMaterial` table (DATA). Renders through `@jgengine/shell/terrain/CarvedTerrain`.
2628
-
2629
- Renderers for these descriptors live in `@jgengine/shell` (`shell/terrain`, `shell/water`, `shell/weather`, `shell/structures`).
2630
-
2631
- ### Environment fields, weather hooks & realm composition
2632
- Renderer-free survival/environment primitives that extend the world query layer — meters, spawn gating, and damage-in-sunlight read the same world the shell renders, all ticking on game-time `dt`.
2633
- - **Environment field** (`world/envField`): `createEnvironmentField({ dayLength, baseTemperature, nightDrop, altitudeLapse, terrain, rain, occluders, heatSources, ambientFloor, temperatureAt })` → `EnvironmentField`. Sample **temperature**, **wetness**, **lightExposure** (direct sun/sky), and **ambientLight** (spawn gating) at any `(x, z, time)` — `sample(x, z, time, y?)` returns all four plus `sheltered`. Occluders (roofs/canopy) shade sun and shelter from rain; heat sources (campfires) warm nearby positions; `sunElevation(time)` drives the day cycle. Sun damages a vampire, cold forces campfires, low ambient light spawns mobs — the field answers "am I in sun vs. shade / cold vs. warm / dark vs. lit". Pure and instantaneous; stateful build-up belongs to a decay meter reading the field.
2634
- - **Weather → gameplay** (`world/weather`): `resolveWeather(state, table)` turns a `WeatherState { kind, intensity }` into concrete `ResolvedWeather` (`grip`, `visibility`, `structureDamage`, `chill`, `ignition`, `spread`) via a game-owned `WeatherModifierTable` — multipliers interpolate from neutral by intensity, rate effects scale linearly. Read `grip`/`visibility` in movement and AI, `structureDamage` on a building tick.
2635
- - **Fire spread** (`world/weather`): `createFireGrid({ cols, rows, cellSize, origin, fuelAt, spreadRate, burnRate, wind, windBias })` → `FireGrid` is a **coarse cellular** propagation (not a fluid solver): `ignite(x, z)` / `igniteCell(col, row)`, then `step(dt, { spread, wetnessAt })` transfers heat to neighbours biased by wind, consumes fuel (`unburnt → burning → burnt`), and honours firebreaks (zero-fuel cells) and rain/wetness suppression. `resolveWeather(...).spread` feeds the step; `@jgengine/shell/weather` `FireSpreadLayer` renders the burning/scorched cells.
2636
- - **Realm composition** (`world/realm`): `composeRealm(base, cards)` assembles a played instance at runtime from a deck of modifier **cards** (Nightingale realm cards) — a `major` card is the biome base, `minor` cards layer environment param overrides, a `WeatherState`, and spawn-table edits (`set`/`add`/`scale`/`remove`). The result recomposes both the environment (into a sampleable field via `composed.environmentField(extra?)`) and the `spawnTable`, and depends on the weather hooks above to turn its `weather` into gameplay modifiers.
2637
- ### Survival meters, moodles & multi-region health
2638
- The `survival/` domain — decay-over-time meters and per-part health, both feeding one stacking **moodle** status display distinct from numeric bars.
2639
- - **Decay meters** (`survival/decayMeter`): `createDecayMeterSet([{ id, max, min?, start?, rate, thresholds }])` → `DecayMeterSet`. Each named meter (hunger, thirst, oxygen, sanity, warmth, stamina) drains/recovers on `tick(dt)` at `rate`, refills from consumables/actions via `refill(id, amount)`, and raises threshold moodles (`below`/`above`). `setRateModifier(id, mult)` lets the environment drive them — read an env field, then speed warmth loss when cold or oxygen loss in a toxic biome.
2640
- - **Moodles** (`survival/moodle`): the shared status stack, distinct from raw bars. `stackMoodles(...groups)` folds meter, ailment, and buff `Moodle[]` into one worst-first display (same-id stacks add, worst severity wins). `createMoodleStack()` holds timed buffs (`add({ id, label, duration })` — Valheim's concurrent food buffs) and expires them on `tick(dt)`.
2641
- - **Multi-region health** (`survival/regionHealth`): `createMultiRegionHealth({ regions, ailments })` → `MultiRegionHealth` gives per-part pools (head/thorax/arms/legs, Tarkov/DayZ style) — `damage(regionId, amount)` scales by `vulnerability` and kills when a `vital` part empties; a stacking **ailment queue** (`applyAilment`, `tick(dt)` drains like bleed) carries per-injury treatment (`treat(itemId)` clears wounds via bandage/tourniquet/splint). `ailmentMoodles()` shares the moodle display with the meters (#78 + #90).
2642
- ### Interactive building & terraform (renderer-free tools)
2643
- Turn data-only placement into the build tooling of Valheim/Enshrouded/The Sims/Fortnite/Dinkum. All pure `@jgengine/core/world`; the shell renders the ghost/tint/brush (`shell/structures/PlacementGhost`, `shell/terrain/EditableGround`, `shell/terrain/TerraformBrushCursor`) driven by `pointer.worldHit()`.
2644
- | Primitive | Answers |
2645
- |-----------|---------|
2646
- | `createPlacementController({ footprint, rules, snapMode, grid })` | Owns the ghost: `hover(hit)` → `PlacementPreview` (`valid` tint wraps `validatePlacement`), `rotate()`, `setSnapMode`/`cycleSnapMode` (`"grid"`/`"free"`/`"surface"`), `commit()` → `PlacementCommit` (`rotationY` via `quarterTurnsToRotationY`). Feed it `pointer.worldHit()`. |
2647
- | `snapToNearest(registry, placed, movingDef, cursor, { snapDistance })` | Typed connector sockets — snaps a piece's socket onto the nearest **compatible** placed socket (`socketsCompatible` = both sides `accept` the other type). `worldSockets`/`socketWorldPosition` expand a piece's sockets to world space. |
2648
- | `solveSupport(pieces, links, { maxDistance })` → `SupportResult` | Walks the connector graph to any `grounded` piece: `supported` stays, `unsupported` collapses, `distance` (hops-to-ground) drives the white→red decay tint. `toDebrisBodies(pieces, unsupported)` → `AddBodyOptions[]` for the `PhysicsWorld` debris sink. |
2649
- | `createWallDrawTool({ snap, closeTolerance })` | Drag wall points → auto-encloses when the path returns to the start (`isEnclosed`), `footprint()` derives the room `EnclosedFootprint`, `roof()` auto-fits a hip/gable/flat `RoofPlan`. `createSurfacePaint()` stores per-tile floor/wall surfaces. |
2650
- | `createPlacedStructureStore()` | Save/load a built layout: `add`/`move`/`rotate`/`remove`/`select`, `snapshot()`↔`load()` round-trip (survives reload), `subscribe` for the renderer. |
2651
- | `createEditableTerrain({ bounds, base, cellSize })` → `EditableTerrain` | A `TerrainField` you can **write back to**: `apply(edit: TerraformEdit)` raises/lowers/flattens/paints under a cursor and re-samples `sampleHeight`; `surfaceAt`, `snapshot`/`restore`, `reset`. `createTerraformBrush(field)` is the cursor tool (`raise`/`lower`/`flatten`/`paint`, radius/strength). This write-back grid is the shared terrain-edit pattern. |
2652
- | `createPlotPermissions({ plotId, ownerId, guildId? })` + `createContributionPool(goal)` | Per-plot/guild edit authority (`canEdit`/`canView`, `grant`/`revoke` `BuildRole`, guild inheritance) for co-op building, plus a pooled-resource contribution model (`contribute` caps at the goal, reports overflow, `isComplete`, per-contributor totals). |
2653
-
2654
- ### Physics world (optional, headless)
2655
-
2656
- `physics/physicsWorld` `PhysicsWorld` is a standalone fixed-capacity rigid-body sim (SoA buffers, spatial-hash broadphase, sleeping) — **not** the `defineGame` `physics: { gravity, jumpVelocity }` field, which the built-in walk controller reads directly every frame (see "Controller kinematics" above; both values are real and honored, not dead config). Reach for `PhysicsWorld` when a game needs many colliding dynamic bodies (piles, debris, stress scenes): `new PhysicsWorld({ capacity, bounds, … })`, `addBody({ position, mass?, ...shape })`, then `step(dt)` per tick → `PhysicsStats`. Core owns the sim; `@jgengine/shell/world/InstancedBodies` renders its bodies. Most games never need it — the character controller covers ordinary movement. The broadphase grid (`nx*ny*nz` cells from `bounds`/`cellSize`) throws at construction if it would exceed a sane cell cap — shrink `bounds` or raise `cellSize` (same guard on `physics/spatialGrid`'s `SpatialGrid`).
2657
-
2658
- **Body shape: box or sphere.** `AddBodyOptions` is a discriminated union — `{ shape?: "box", halfExtents }` (box is the default, `shape` omittable) or `{ shape: "sphere", radius }` (the radius fills all three half-extent columns, so broadphase/bounds see the sphere's enclosing AABB). `world.shape[i]` (`SHAPE_BOX` / `SHAPE_SPHERE`) reports a live body's shape for a consumer walking the raw SoA arrays. Sphere-sphere and sphere-box pairs resolve with a proper radial normal (not the axis-aligned box/box path) — balls, projectile bodies, and rolling debris collide correctly against both boxes and each other.
2659
-
2660
- **Collision shapes are box/sphere/voxel only.** Every collider in the engine — `PhysicsWorld` bodies (box `halfExtents` or sphere `radius`), object/entity picking (`scene/objectQuery` raycasts against unit boxes), and `world/voxelField`/`world/carve` blocks — is an axis-aligned box, a sphere, or a voxel cell. Arbitrary authored level-mesh collision (a sculpted GLB as a collider) is not supported. The seams for custom collision are `movement.beforeCommit` (steer or replace the walk controller's resolved step) and object raycasts (query the scene yourself and react) — not a mesh collider.
2661
-
2662
- **Ballistic collision sweep (`physics/ballisticSweep`).** `createBallisticSweep(world, { step?, radius? })` → `BallisticSweep`, a `(origin, velocity, gravity, maxTime) => BallisticSweepHit | null` function that marches the closed-form arc (constant gravity, straight lateral) through a `PhysicsWorld` and reports the first sample inside any live body's AABB (sleeping bodies included), refined by one bisection step; `null` means the whole arc is clear. `step` (default 1/60) is the march interval in seconds, `radius` (default 0) inflates every body's AABB before the point test — pass the projectile's own radius. Wire it into `combat/projectiles` via `ProjectileSystemDeps.sweepBallistic`: when set, a ballistic shot settles at the swept impact point instead of the closed-form landing; omitted or `null` falls back to that closed-form arc.
2663
-
2664
- **Removing and moving bodies.** `removeBody(id)` tombstones a body — it drops out of integration/broadphase and its slot is queued for the next `addBody` — without moving or invalidating any other body's `id` (ids are raw SoA slots, stored as-is in joints and game state, so nothing ever gets swapped). It conservatively wakes any sleeping body whose AABB touched the removed one's (no persistent contact set to consult, so this errs toward waking too much, never too little). `setVelocity(id, x, y, z)` and `setPosition(id, x, y, z)` write a body's velocity/position directly (instead of poking the public `velX`/`posX` SoA arrays) and wake it if asleep; `teleport(id, x, y, z)` is `setPosition` plus a hard velocity reset (respawn/teleporter, vs. sliding). `isAlive(id)`/`highWater` (one past the highest slot ever handed out) let a consumer that iterates the raw SoA arrays skip tombstoned holes correctly instead of assuming `count` is a dense `0..count` range.
2665
-
2666
- **Joints & constraints.** `hingeJoint`/`fixedJoint`/`distanceJoint`/`springJoint(opts)` connect two bodies, or a body to a fixed world point (omit `bodyB`). The sim is translational (no angular DOF), so `hinge`/`fixed` pin the shared anchor (the `axis` is retained metadata), `distance` holds a fixed separation, and `spring` drives toward `restLength` with `stiffness`/`damping` (suspension, follow-point carry). `removeJoint(id)`, `setJointAnchor(id, x, y, z)` (move anchor B — a world anchor's follow point, or body B's local offset), `setJointAnchorA(id, x, y, z)` (move anchor A's local offset — e.g. re-rotating a suspension mount each frame as the chassis turns), `setJointRest`, and `readJointSegments(out)` for `@jgengine/shell/world/InstancedJoints` (debug line render). This is the foundation under vehicles, ragdolls, grapples, and carry.
2667
-
2668
- **Collision → gameplay events.** `world.onCollision(listener, minApproachSpeed?)` delivers every impacting contact — `CollisionEvent { a, b, nx, ny, nz, approachSpeed, impulse }` — to game code during `step` (the object is reused; read/copy it, never retain). This is the seam crash-damage and destruction read; pass `null` to detach.
2669
-
2670
- **Actors on top of the sim:** `physics/ragdoll` (`createRagdoll(world, { bones, links, balance? })` — jointed bones, floppy or active-ragdoll via a balance motor), `physics/carryable` (`Carryable` — grab a body to a follow point, shared multi-owner carry, `carrySpeedMultiplier` encumbrance, drop/throw; the raycast pick is the caller's job, core owns the constraint), `physics/forceVolume` (`ForceVolume` — impulse/velocity/accelerate trigger region, `once` for boost pads; `PlatformCarry` — carry bodies standing on a moving platform by its per-`step` delta). Separately, `physics/spatialGrid` `SpatialGrid` is a broad-phase grid over the x/z plane, **distinct** from the rigid-body sim, for cheap same-tick proximity across hundreds–thousands of simple movers — `rebuild(count, xs, zs)` then `queryCircle` (swarm enemies hitting a player/AoE) or `forEachPair` (mutual separation).
2671
-
2672
- **Swarm-scale presentation.** `@jgengine/shell/world/SpriteBatch` renders up to `capacity` sprite-sheet quads as one `InstancedMesh` (per-instance atlas `frame`, `plane: "xy" | "xz"` or `billboard`, `pixelated` nearest-filtering) — the batched path for bullet-heaven swarms, item streams, and tile-grid presentation instead of one `<sprite>` per entity. Pair it with `world/lod`'s `createLodScheduler` (see the concept table) to band render detail by distance and throttle far entities' update work.
2673
-
2674
- **Traversal (`physics/traversal`).** `Grapple` fires a rope from a body to a fixed world point on the joint API — `fire(x,y,z)` attaches a `distance` (rigid) or `elastic` (spring) joint, `reel(dt)`/`payOut(dt)` shorten/lengthen the rope to pull the traveller in, `moveAnchor` re-points it (ziplines, grapple-to-moving-target). Grapple/zipline/swing (Sekiro, Deep Rock, Just Cause) are all the same primitive; the raycast that finds the anchor is the caller's. `Glide` is a reduced-gravity, forward-thrust wingsuit/glider over a body — call `apply(dt, steerX, steerZ)` each frame before `step` to feed back most of gravity (`gravityScale`), thrust along the steer vector, and clamp descent; stop calling it to fall normally, no attach/detach state.
2675
- **Structural destruction (`physics/structure`).** `StructureGraph` models a building as nodes (pieces) + load-bearing edges with some nodes `anchor`ed (foundations). `damage(id, n)`/`damageEdge(a,b,n)`/`severEdge(a,b)` wear pieces and connections; when one breaks, the graph recomputes reachability to an anchor and returns a single `CollapseEvent { fell }` — every piece the loss disconnected. `toDebris(world, event)` sinks the fallen pieces into a `PhysicsWorld` as rigid bodies (The Finals, Rainbow Six). It is coarse by design: **replicate the collapse event (the `fell` id list), not each fragment's physics** — game clients re-derive the debris locally. Piece integrity and edge strength default from a `StructureMaterial` table (DATA).
2676
- ### Vehicles, mounts, crash damage & racing
2677
- Five primitives layer a driving/racing game over the physics sim and `world/water`. All are **data-first** (spec the chassis/wheels/grip curve, damage thresholds, and checkpoint layout as catalog data) and pure `@jgengine/core`; renderers live in the game/shell. Each `update(dt, …)` runs **before** the shared `world.step(dt)`.
2678
- - **Analog input — `input/axisInput`.** `AxisInput { throttle, brake, steer, handbrake }` is a continuous channel, **distinct from the digital action bindings**. `new AxisChannel({ bindings, smoothing })` ramps held keys into pedal-like analog values (`sample(dt, isDown)`), or `setAnalog(axis, value)` drives it straight from a gamepad axis. `DRIVE_AXIS_BINDINGS` is a ready WASD/arrow map. `sampleAxisBindings` is the instantaneous, unsmoothed read the channel ramps toward each frame — exposed headlessly as `ctx.input.axis(bindings, ranges?)`, bound to **action names** rather than raw key codes (#533.7).
2679
- - **`physics/vehicleBody`.** `createVehicleBody(world, config)` is an arcade car: a chassis box body with per-wheel suspension held by G3's `springJoint` against the sampled `groundHeight`, drive/brake along the heading, and a `GripCurve` (`sampleGripCurve`) that bleeds lateral velocity for cornering — and, under `handbrake`, drift. `update(dt, axisInput)` then `world.step`. Because the chassis is a real body it still collides, which feeds crash damage. Rocket League, Trackmania, Wreckfest.
2680
- - **`physics/buoyancy`.** `createBuoyantBody(world, { body, water, … })` floats a body on a CPU `WaterSurface` (Archimedes per hull point + water drag) so it settles at the waterline and rides the Gerstner waves; pass an `AxisInput` to `update(dt, time, input?)` and it drives as a boat (thrust + yaw + keel). Sea of Thieves, BOTW rafts.
2681
- - **`scene/mount`.** `createMountController()` transfers control to a driven entity: `register({ id, kit, seats })`, `mount(riderId, mountId, seatId?)`, `dismount`. Read `cameraTarget(riderId)` to point the follow camera and `driveTarget(riderId)` to route that rider's `AxisInput` at the mount — the control seat drives, passenger seats ride (multi-seat shared vehicles), and an un-mounted rider drives themselves. `driver(mountId)`/`occupants(mountId)`/`kitOf`. Palworld mounts, V Rising horse, a crewed ship.
2682
- - **`scene/stationClaim`.** `createStationClaim(controller?)` layers **facet stations** on `scene/mount` for a vehicle several players crew at once: `register({ id, kit, stations })` where each `Station` tags a seat with a `facet` (`"steer"`/`"sails"`/`"cannon"`). `claim(playerId, vehicleId, facetOrStationId)`, `release`, `controllerOf(vehicleId, facet)` (who mans it), `facetOf(playerId)`, `openFacets`, `crew`. Only a `control` station operates the hull (`driver`/`driveTarget`); the rest ride but command their own facet. Sea of Thieves helm + sails + cannons.
2683
- - **`physics/damageZones`.** `createDamageModel({ zones, disableAt })` maps accumulated contact impulse (from `onCollision`) to **coarse discrete stages** (not soft-body): `absorb(zoneId, impulse)` / `routeCollision(event, resolveZone)` bump a zone's stage (caller swaps the visual/collider), an optional `detachStage` ejects a part as debris once, and crossing `disableAt` flips a whole-vehicle `disabled` state. Wreckfest crumple/derby.
2684
- - **`game/race`.** `raceTrack({ checkpoints, laps })` is an ordered ring of AABB checkpoint volumes (the final one is the finish line); `createRaceState({ track, win })` — driven each tick by `update(now, positions)` on game time — emits `checkpoint.hit` / `lap.completed` / `position.changed` / `race.finished`, keeps split times, resolves a pluggable `RaceWinCondition` (`firstPastPost`, `topK` round-cut, `everyoneFinishes`, `lastStanding` derby), and `resetToCheckpoint(id)` hands back a respawn pose. `removeRacer(id)` drops a racer mid-race and renumbers the remaining standings; `reset()` clears all racer progress/finish state back to construction time so the same instance replays without rebuilding it. Trackmania, Mario Kart, Fall Guys.
2685
-
2686
- ### Spawn placement
2687
-
2688
- `spawn(catalogId, { id?, position | anchor, offset?, parentSpace?, group? })` — anchor `{ kind: "entity" | "zone", id }` with offset `{ radius, pattern }` or `{ xyz }`. Catalog supplies movement/model; no behaviors on spawn.
2689
-
2690
- **Named spawn/respawn points** (`game/spawnPoints`) — `createSpawnPoints()`: `record(id, { x, y, z, rotationY? })` names a point (level bounds, team spawns, checkpoints), `get(id)`/`list()` read them back, `respawn(entities, entityId, spawnId)` teleports an existing entity to a recorded point via `setPose` in one call — the id-keyed alternative to threading raw coordinates through respawn logic by hand.
2691
-
2692
- **Level sequence** (`game/levelSequence`) — `createLevelSequence({ levels: [{ id, config }], retriesPerLevel? })` is a pure, deterministic campaign machine: `start()` enters level 0, `clear()` marks the current level cleared, `advance()` moves to the next (or `"complete"` after the last), `fail()` consumes an attempt and returns `"retry"` while `retriesPerLevel` remain else `"failed"`, `retry()` restarts after a retry-eligible failure. `current()` → `{ id, index, config, attempt } | null`; `progress()` → `{ index, total, cleared }`; `reset()` rewinds to idle. Mirrors the reducer style of `game/race` and `ai/spawnDirector` — a level-select/roguelike-run campaign shell without hand-rolling the state machine per game.
2693
-
2694
- # jgengine-api — Cartridge
2695
-
2696
- Reference module for the [`jgengine`](./SKILL.md) skill. Load this when building a game as a **cartridge** — one declarative config instead of hand-wired loop/state/UI files. A cartridge game is ~75% smaller than the classic shape and nearly all of it is data; reach for `defineGame` directly only when the game's simulation doesn't fit the cartridge archetypes even through the escape hatches.
2697
-
2698
- ## Why
2699
-
2700
- Across the classic games, 78–91% of each game's LOC was generic wiring restated per game: a run-state store with subscribe/notify, chase-and-contact enemy loops, auto-fire weapon routines, magnet pickups, draft plumbing, phase-gated HUD trees, and tests for all of it. The cartridge layer owns every one of those; the game ships only its **data** (catalogs, tuning, layout) and any genuinely bespoke rules through typed escape hatches.
2701
-
2702
- ## Shape
2703
-
2704
- `game.config.ts` is the whole game — `cartridge({...})` from `@jgengine/shell/cartridge` compiles the config into a `PlayableGame` (validating it first — a bad reference throws at import with a list of problems). `loop.ts` and `world.ts` disappear; the spec carries the world feature and the loop is engine-owned. `main.tsx` is 5 lines via `mountGame` (`@/components/ui/mount`, registry). Sprites/SVG art stay in `src/game/assets.ts`; the game keeps one test file under `src/game/`.
2705
-
2706
- ```ts
2707
- import { cartridge, type CartridgeConfig } from "@jgengine/shell/cartridge";
2708
- import { standardCartridgePanels } from "@/components/ui/cartridge-panels";
2709
-
2710
- export const config: CartridgeConfig = {
2711
- name, seed, panels: standardCartridgePanels, assets, entitySprites,
2712
- flow: { start: "gate", countdownSeconds: 3, restart: true }, // press-to-start → 3-2-1 → playing; "restart" command
2713
- player: { kind, health, walkSpeed }, // compiled into content + spawned per player
2714
- enemies: { id: { label, health, walkSpeed, xp, contact: { damage, intervalSeconds }, behavior: "chase" | "none" } },
2715
- combat: { contactRadius },
2716
- spawning: { director: SpawnDirectorConfig, placement: { kind: "ring", radius } },
2717
- weapons: { id: { kind: "projectile" | "orbit" | "pulse" | "custom", damage, cooldownMs, maxLevel, ... } },
2718
- progression: { xp: Curve, maxLevel, draft: { choices, upgrades } },
2719
- fields: { magnetRadius, damageMultiplier }, // named run-scalars upgrades mutate
2720
- xpGems: { collectRadius, pullSpeed, rarityThresholds, defaultRarity },
2721
- rules: { win: { kind: "survive", seconds }, lose: { kind: "playerDeath" } | { kind: "custom", check }, killLeaderboardStat },
2722
- world, physics, camera, worldItem, theme, hud, screens, // screens: start/win/lose
2723
- };
2724
- export const game = cartridge(config);
2725
- ```
2726
-
2727
- The run is a phase machine every game gets for free: `start → countdown → playing → won | lost`. `flow.start: "gate"` renders `screens.start` (TitleScreen binding) until begin; `flow.countdownSeconds` renders the big-number countdown; `flow.restart: true` registers a `restart` command that resets the run in place, clears cartridge entities, and restores player stats — no hand-rolled session store, phase union, or reset function. `run.playingSeconds` is the run clock (drives the survive rule and the timer panel), so pauses and pre-game phases never skew timing.
2728
-
2729
- ## Core surface (`@jgengine/core/cartridge/`)
2730
-
2731
- - `@jgengine/core/cartridge/spec` — the `CartridgeSpec` types, `Leveled` values (`number | { base, perLevel, min?, max? } | { table }` resolved by `leveled(value, level)`), `WASD_KEYBINDS` (the default when `input` is omitted).
2732
- - `@jgengine/core/cartridge/runtime` — `createCartridge(spec)` → `{ content, loop, run(ctx), weaponKit(ctx), chooseUpgrade(ctx, offerId) }`. Owns the run store (outcome/kills/fields/weapon levels, subscribe/notify), spawn director advance + ring placement, chase + contact-damage enemies (terrain-grounded), the three weapon archetypes with auto-targeting, magnet xp-gem pickups feeding `leveling()`, pause-and-draft level-ups, kill → gem drop + leaderboard, and win/lose rules.
2733
- - `@jgengine/core/cartridge/validate` — `validateCartridge(spec)` → problem list: spawn waves must reference declared enemies, upgrades must reference declared weapons/fields, stacks can't exceed weapon `maxLevel`, tuning must be positive, rarity thresholds descending. The game's test asserts it returns `[]`.
2734
-
2735
- Weapon archetypes: `projectile` (auto-target nearest in `range`, travel-time bolt fx), `orbit` (leveled blade count/radius sweeping `hitRadius`), `pulse` (radial AoE with linear falloff and an expanding-ring fx). Upgrade effects: `weaponLevel` (+1 level per stack), `statBonus` (+max and +current on pick), `fieldAdd` / `fieldMultiply` (recomputed from stacks). Weapon damage is multiplied by the `damageMultiplier` field when declared.
2736
-
2737
- ## Presentation (shell + registry)
2738
-
2739
- `hud.panels` is a schema — items `vital | xp | timer | score | abilityBar | component`, anchored via the movable HUD layout; `screens.win/lose` render the results/death screens; the upgrade-draft modal appears whenever a draft is pending. The shell renders the frame and injects concrete components through the `panels` seam — `standardCartridgePanels` (registry `cartridge-panels`) binds the jgengine UI kit; swap any binding for a custom component without touching the engine. Weapon fx render engine-side from the run store's bolt/pulse feeds (`fxColor`/`fxEmissive` per weapon). `theme` is the `--jg-*` CSS var block — hand-pick it or derive from a few seed colors with `deriveJgTheme` (registry `jg-theme`).
2740
-
2741
- ## Escape hatches — bespoke logic without leaving the cartridge
2742
-
2743
- - `weapons.<id> = { kind: "custom", fire(ctx, run, args) }` — cooldown/level/damage handled for you; the fire shape is yours.
2744
- - `spawning.placement = { kind: "custom", position(ctx, run) }`.
2745
- - `rules.win = { kind: "custom", check(ctx, run) }`.
2746
- - `progression.draft.upgrades[].effect = { kind: "custom", apply(ctx, run, stacks) }`.
2747
- - `systems: [(ctx, run, dt) => ...]` — extra per-tick simulation after the built-ins, only while playing.
2748
- - `hud` items `{ kind: "component", Component }` — arbitrary React panels alongside the schema ones.
2749
-
2750
- A game that is *mostly* bespoke simulation (custom physics, session machines) should keep `defineGame` and write its systems — the cartridge is for games whose shape the archetypes already cover.
2751
-
2752
- ## Testing
2753
-
2754
- Cartridge behaviors are engine-tested once (`packages/core/src/cartridge/runtime.test.ts`); the game test is one call plus any game-specific assertions:
2755
-
2756
- ```ts
2757
- import { bootCartridge, cartridgeSmokeTest, tickCartridge } from "@jgengine/core/cartridge/testkit";
2758
- cartridgeSmokeTest(config); // validate + world summary + headless run/spawn/kill/gem smoke
2759
- ```
2760
-
2761
- `bootCartridge`/`tickCartridge` build a headless `GameContext` and drive the loop (auto-choosing drafts) for custom assertions — see `@jgengine/core/cartridge/testkit`. The testkit imports `bun:test`; import it from test files only.