threedog 1.1.0 → 1.2.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 (363) hide show
  1. package/CHANGELOG.md +879 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +23 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +6 -1
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +74 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +9 -8
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +70 -79
  180. package/docs/recipes/63-third-person-start.md +47 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/GAMEMAP.md +2 -3
  185. package/examples/action/main.js +3 -3
  186. package/examples/action/picture/lights.js +3 -1
  187. package/examples/perf-island/GAMEMAP.md +3 -3
  188. package/examples/perf-island/picture/lights.js +2 -1
  189. package/examples/plain-picture/GAMEMAP.md +1 -1
  190. package/examples/rc2d/GAMEMAP.md +1 -1
  191. package/examples/styletest/GAMEMAP.md +2 -2
  192. package/examples/styletest/main.js +1 -1
  193. package/examples/techniques/interior-light/README.md +3 -3
  194. package/examples/techniques/interior-light/interiorLight.js +2 -4
  195. package/examples/techniques/interior-light/picture/lights.js +2 -1
  196. package/examples/techniques/modular-building/picture/lights.js +3 -1
  197. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  198. package/examples/techniques/procedural-animation/README.md +1 -1
  199. package/examples/techniques/procedural-animation/main.js +1 -1
  200. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  201. package/examples/world/GAMEMAP.md +2 -3
  202. package/examples/world/art/humanoid.js +1 -1
  203. package/examples/world/main.js +6 -3
  204. package/index.d.ts +2 -2
  205. package/llms.txt +101 -0
  206. package/modules/ambience/Ambience.js +21 -5
  207. package/modules/calendar/index.js +9 -5
  208. package/modules/calendar/schedule.js +23 -8
  209. package/modules/camera/FirstPersonCamera.js +3 -1
  210. package/modules/camera/FollowCamera.js +10 -5
  211. package/modules/camera/RtsCamera.js +4 -3
  212. package/modules/camera/common.js +70 -8
  213. package/modules/camera/contract.js +1 -1
  214. package/modules/characters/Character.js +16 -10
  215. package/modules/characters/NPC.js +31 -19
  216. package/modules/characters/assetModel.js +14 -9
  217. package/modules/characters/astar.js +6 -1
  218. package/modules/characters/contract.js +2 -2
  219. package/modules/characters/index.js +34 -22
  220. package/modules/characters/movers/manual.js +1 -1
  221. package/modules/characters/movers/rapier.js +17 -2
  222. package/modules/characters/movers/simple.js +1 -1
  223. package/modules/characters/movers/support.js +16 -7
  224. package/modules/characters/npcAvoid.js +2 -2
  225. package/modules/characters/npcSim.js +3 -2
  226. package/modules/characters/pathAsync.js +24 -8
  227. package/modules/characters/pathJob.js +1 -1
  228. package/modules/characters/player.js +10 -9
  229. package/modules/characters/playerStrings.js +5 -5
  230. package/modules/characters/proceduralRig.js +5 -5
  231. package/modules/characters/useModel.js +6 -0
  232. package/modules/characters/walkTo.js +1 -1
  233. package/modules/collision/Collision.js +29 -18
  234. package/modules/collision/grid.js +22 -4
  235. package/modules/content/index.js +3 -1
  236. package/modules/content/loader.js +1 -1
  237. package/modules/content/models.js +82 -33
  238. package/modules/content/props.js +2 -1
  239. package/modules/content/rules.js +11 -5
  240. package/modules/content/templates.js +3 -3
  241. package/modules/content/words.js +2 -2
  242. package/modules/debug/DebugPanel.js +9 -9
  243. package/modules/flow/index.js +9 -6
  244. package/modules/gameplay/Dialogue.js +34 -20
  245. package/modules/gameplay/Interactions.js +19 -15
  246. package/modules/gameplay/Inventory.js +9 -4
  247. package/modules/gameplay/Quests.js +12 -10
  248. package/modules/gameplay/pickups.js +23 -11
  249. package/modules/grid/index.js +1 -1
  250. package/modules/grid/preview.js +2 -2
  251. package/modules/grid/tiles.js +1 -1
  252. package/modules/hlod/index.js +4 -1
  253. package/modules/hud/index.js +47 -10
  254. package/modules/hud/parts.js +28 -9
  255. package/modules/level/geometry.js +8 -3
  256. package/modules/level/index.js +10 -5
  257. package/modules/level/load.js +4 -2
  258. package/modules/lights/sources.js +1 -1
  259. package/modules/music/Music.js +22 -4
  260. package/modules/nav/index.js +20 -10
  261. package/modules/particles/Particles.js +31 -14
  262. package/modules/particles/effect.js +20 -5
  263. package/modules/particles/lit.js +72 -0
  264. package/modules/photo/Photo.js +72 -28
  265. package/modules/photo/pathTrace.js +106 -0
  266. package/modules/rigid/RigidBodies.js +23 -14
  267. package/modules/rigid/Vehicles.js +3 -13
  268. package/modules/rigid/sync.js +2 -1
  269. package/modules/settings/Settings.js +52 -20
  270. package/modules/settings/apply.js +23 -9
  271. package/modules/settings/sections.js +39 -6
  272. package/modules/settings/strings.js +2 -0
  273. package/modules/settings/view.js +19 -3
  274. package/modules/sky/dome.js +15 -3
  275. package/modules/sky/environment.js +28 -12
  276. package/modules/sky/fog.js +1 -1
  277. package/modules/sky/frame.js +6 -1
  278. package/modules/sky/shader.js +4 -3
  279. package/modules/sky/skyModule.js +8 -4
  280. package/modules/swarm/Swarm.js +1 -1
  281. package/modules/terrain/ChunkManager.js +61 -15
  282. package/modules/terrain/chunkJob.js +2 -2
  283. package/modules/terrain/index.js +20 -5
  284. package/modules/terrain/terrainEdit.js +8 -4
  285. package/modules/terrain/terrainTexture.js +4 -2
  286. package/modules/timeline/Timeline.js +4 -3
  287. package/modules/timeline/Tween.js +3 -0
  288. package/modules/timeline/letterbox.js +1 -0
  289. package/modules/triggers/index.js +36 -17
  290. package/modules/vegetation/Vegetation.js +81 -19
  291. package/modules/vegetation/densityMap.js +13 -8
  292. package/modules/vegetation/draw.js +147 -24
  293. package/modules/vegetation/groundChunks.js +20 -5
  294. package/modules/vegetation/index.js +3 -3
  295. package/modules/vegetation/modelGeometry.js +9 -4
  296. package/modules/water/Water.js +11 -8
  297. package/modules/weather/Weather.js +7 -2
  298. package/modules/weather/shaders.js +25 -5
  299. package/modules/weather/weatherDraw.js +20 -6
  300. package/modules/world/World.js +2 -1
  301. package/modules/world/index.js +2 -2
  302. package/modules/world/persist.js +6 -2
  303. package/modules/world/views.js +15 -2
  304. package/package.json +4 -1
  305. package/presets.js +5 -5
  306. package/render/PostFX.js +84 -41
  307. package/render/backend.js +137 -16
  308. package/render/cascades.js +3 -1
  309. package/render/cascades.tsl.js +2 -0
  310. package/render/daylight.js +7 -1
  311. package/render/detail.js +7 -4
  312. package/render/effects.js +27 -8
  313. package/render/fogLook.js +24 -0
  314. package/render/fuse.js +5 -2
  315. package/render/fx/detail.tsl.js +9 -7
  316. package/render/fx/index.js +7 -2
  317. package/render/fx/library.tsl.js +1 -0
  318. package/render/fx/lightShaft.tsl.js +114 -0
  319. package/render/fx/noise.tsl.js +25 -8
  320. package/render/fx/objectOrigin.tsl.js +39 -10
  321. package/render/fx/particles.tsl.js +23 -6
  322. package/render/fx/patchNodes.tsl.js +17 -12
  323. package/render/fx/pcss.tsl.js +51 -0
  324. package/render/fx/postWebGPU.tsl.js +89 -29
  325. package/render/fx/sky.tsl.js +3 -9
  326. package/render/fxNumbers.js +10 -4
  327. package/render/impostor.tsl.js +107 -0
  328. package/render/lighting.js +33 -1
  329. package/render/lightmap.js +42 -28
  330. package/render/lights.js +19 -3
  331. package/render/materials.js +6 -4
  332. package/render/mergeCommon.js +4 -1
  333. package/render/occlusion.js +14 -4
  334. package/render/patches.js +79 -41
  335. package/render/postRuns.js +32 -0
  336. package/render/postWebGL.js +97 -10
  337. package/render/probes.js +10 -14
  338. package/render/shaderErrors.js +2 -1
  339. package/render/shadowCache.tsl.js +33 -5
  340. package/render/shadows.js +42 -16
  341. package/render/slots.js +8 -5
  342. package/render/vertexInputs.js +52 -0
  343. package/types/core.d.ts +114 -46
  344. package/types/gameplay.d.ts +56 -23
  345. package/types/generated/core/audio/Audio.d.ts +27 -1
  346. package/types/generated/core/base/Random.d.ts +1 -1
  347. package/types/generated/core/input/Input.d.ts +6 -8
  348. package/types/generated/core/input/inputSeat.d.ts +1 -1
  349. package/types/generated/core/inspect/Budget.d.ts +26 -0
  350. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  351. package/types/generated/core/saves/Saves.d.ts +10 -7
  352. package/types/generated/core/saves/session.d.ts +8 -2
  353. package/types/generated/core/scene/Rays.d.ts +1 -3
  354. package/types/generated/modules/particles/Particles.d.ts +1 -1
  355. package/types/generated/modules/world/World.d.ts +2 -1
  356. package/types/generated/render/PostFX.d.ts +35 -9
  357. package/types/physics.d.ts +796 -764
  358. package/types/pixel.d.ts +1 -1
  359. package/types/tsl.d.ts +62 -1
  360. package/types/world.d.ts +12 -3
  361. package/ui/Focus.js +7 -5
  362. package/ui/Parts.js +1 -1
  363. package/ui/touchPart.js +6 -3
@@ -17,9 +17,40 @@ import { acceleratedRaycast, computeBoundsTree } from 'three-mesh-bvh';
17
17
  import { thingOf } from '../inspect/Inspect.js';
18
18
  import { RESERVED_LAYERS } from '../../render/layers.js';
19
19
  import { DEV, warnOnce } from '../base/validate.js';
20
+ import { notePatch, patchOn } from './threePatches.js';
20
21
 
21
22
  // No three.js prototype is changed: a registered static mesh gets its own BVH and its own raycast (an own property on that mesh), so the engine's
22
23
  // rays are fast and the game's own Raycaster stays plain three.js. A game that wants BVH page-wide writes three-mesh-bvh's three documented lines.
24
+ // Those two writes on the game's objects are a change to three like any other, so they are listed (threePatches 'ray-bvh') and undone:
25
+ // the last registration of a mesh going (remove, forget, geometry dispose, engine.dispose) gives it back the raycast it had, and a
26
+ // boundsTree Rays built is dropped once no registered mesh uses that geometry. A boundsTree the game (or another library) built stays theirs.
27
+ // Module-level, not per engine: two engines may register one mesh, and only the last one leaving may put it back.
28
+ const PATCH = 'ray-bvh';
29
+ /** mesh -> { users, own, prev }: own / prev is the raycast as it was (an own property or the class's) @type {Map<THREE.Object3D, any>} */
30
+ const fast = new Map();
31
+ /** geometry -> { users, tree }: only the trees Rays built @type {Map<THREE.BufferGeometry, any>} */
32
+ const built = new Map();
33
+ function accelerate(m) {
34
+ const f = fast.get(m); if (f) { f.users++; return; }
35
+ if (!patchOn(PATCH)) return;
36
+ const g = m.geometry;
37
+ if (!g.boundsTree && triangles(g) >= BVH_MIN) { computeBoundsTree.call(g); built.set(g, { users: 0, tree: g.boundsTree }); }
38
+ const b = built.get(g); if (b) b.users++;
39
+ // a game's own raycast override wins: only the class's own method is replaced
40
+ if (g.boundsTree && m.raycast === THREE.Mesh.prototype.raycast) { fast.set(m, { users: 1, own: Object.hasOwn(m, 'raycast'), prev: m.raycast, geometry: g }); m.raycast = acceleratedRaycast; }
41
+ else if (b) fast.set(m, { users: 1, own: null, prev: null, geometry: g }); // holds the tree it uses, no raycast to give back
42
+ }
43
+ function decelerate(m, g, all = false) {
44
+ const f = fast.get(m); if (!f || (--f.users > 0 && !all)) return;
45
+ fast.delete(m);
46
+ // a raycast the game wrote since is the game's: left alone
47
+ if (f.prev && m.raycast === acceleratedRaycast) { if (f.own) m.raycast = f.prev; else delete m.raycast; }
48
+ const b = built.get(g);
49
+ if (b && --b.users <= 0) { built.delete(g); if (g.boundsTree === b.tree) g.boundsTree = null; }
50
+ }
51
+ notePatch(PATCH, 'geometry.boundsTree (three-mesh-bvh) and an own mesh.raycast = acceleratedRaycast on each mesh of 256+ triangles registered with engine.rays.addStatic; its last registration going gives the raycast back and drops a boundsTree Rays built (core/scene/Rays.js)',
52
+ () => { for (const [m, f] of [...fast]) decelerate(m, f.geometry, true); },
53
+ { scope: 'objects in the scene', lost: 'engine.raycast tests every triangle of a large static mesh: the same hits, slower' });
23
54
 
24
55
  // Meshes under this many triangles get no BVH (blocky buildings etc.: the per-triangle check is faster)
25
56
  const BVH_MIN = 256;
@@ -43,7 +74,7 @@ export class Rays {
43
74
  constructor(engine) {
44
75
  /** @internal */ this.engine = engine;
45
76
  /** @internal */ this.providers = [];
46
- /** @internal the tick the statics' world matrices were last brought up to date */ this.fresh = -1;
77
+ /** @internal the tick the statics' world matrices were last brought up to date; -1 = refresh at the next ray (a registration, a new frame) */ this.fresh = -1;
47
78
  /** Registered mesh -> { refs: registration count, occ: camera-blocker registration count } @type {Map<THREE.Object3D, { refs: number, occ: number }>} @experimental */
48
79
  this.statics = new Map();
49
80
  /** The three.js Raycaster (firstHitOnly is on) @type {any} @experimental */
@@ -52,7 +83,7 @@ export class Rays {
52
83
  this.ray.layers.enable(RESERVED_LAYERS.batched); // originals drawn through engine.batching sit here and must still be hit
53
84
  }
54
85
  /**
55
- * Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }.
86
+ * Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }. Matrices are read once per tick and frame: a registered mesh moved between two rays of one step needs updateMatrixWorld() first.
56
87
  * Only visible objects are hit. Something that is merely not drawn is still hit: batched originals, far hlod originals and the full model of a far assets.lod sit on a reserved layer, with their visible true.
57
88
  * Unregisters automatically on geometry dispose or engine.remove.
58
89
  * @param {THREE.Object3D | THREE.Object3D[]} obj
@@ -67,31 +98,40 @@ export class Rays {
67
98
  for (const o of [].concat(obj)) o.traverse(m => {
68
99
  if (DEV && (m.isInstancedMesh || m.isSkinnedMesh)) warnOnce(`engine.rays.addStatic: skipped ${m.isInstancedMesh ? 'an InstancedMesh' : 'a SkinnedMesh'} ("${m.name}"): rays do not hit these and they do not block the camera. Use a collider, or register a plain stand-in mesh.`, 'rays-skip-' + m.type);
69
100
  if (!m.isMesh || m.isInstancedMesh || m.isSkinnedMesh || m.userData.lodLevel || !m.geometry?.attributes.position) return; // a low level stands in on screen only: rays use the full model
70
- if (!m.geometry.boundsTree && triangles(m.geometry) >= BVH_MIN) computeBoundsTree.call(m.geometry);
71
- if (m.geometry.boundsTree && m.raycast === THREE.Mesh.prototype.raycast) m.raycast = acceleratedRaycast; // a game's own raycast override wins
72
101
  let s = this.statics.get(m);
73
102
  if (!s) {
74
- s = { refs: 0, occ: 0, geometry: m.geometry, onDispose: () => this._drop(m) };
103
+ s = { refs: 0, occ: 0, geometry: m.geometry, onDispose: () => m.geometry === s.geometry ? this._drop(m) : this._rebind(m, s) };
75
104
  m.geometry.addEventListener('dispose', s.onDispose);
105
+ accelerate(m);
76
106
  }
77
107
  s.refs++; if (occluder) s.occ++;
78
- this.statics.set(m, s); added.push(m);
108
+ this.statics.set(m, s); added.push([m, s]);
79
109
  });
80
110
  return { remove: () => {
81
- for (const m of added.splice(0)) {
82
- const s = this.statics.get(m); if (!s) continue;
111
+ for (const [m, mine] of added.splice(0)) {
112
+ const s = this.statics.get(m); if (s !== mine) continue; // forgotten, or registered again since: that count is not this handle's
83
113
  s.refs--; if (occluder) s.occ--;
84
114
  if (s.refs <= 0) this._drop(m);
85
115
  }
86
116
  } };
87
117
  }
88
- /** Unregister every mesh under the object (engine.remove calls this automatically) @param {THREE.Object3D} obj @experimental */
118
+ /** Unregister every mesh under the object (engine.remove calls this) @param {THREE.Object3D} obj @internal */
89
119
  forget(obj) { obj.traverse(m => this._drop(m)); }
120
+ /** @internal The mesh got another geometry (mesh.geometry = ...) and the old one was disposed: the mesh stays registered, and now follows the new one (listener and BVH) */
121
+ _rebind(m, s) {
122
+ s.geometry.removeEventListener('dispose', s.onDispose);
123
+ decelerate(m, s.geometry);
124
+ s.geometry = m.geometry;
125
+ if (!s.geometry?.attributes.position) return this._drop(m); // nothing to hit any more
126
+ s.geometry.addEventListener('dispose', s.onDispose);
127
+ accelerate(m);
128
+ }
90
129
  /** @internal */
91
130
  _drop(m) {
92
131
  const s = this.statics.get(m); if (!s) return;
93
132
  s.geometry.removeEventListener('dispose', s.onDispose);
94
133
  this.statics.delete(m);
134
+ decelerate(m, s.geometry);
95
135
  }
96
136
  /** @internal Clear all registrations (called by engine.dispose) */
97
137
  dispose() { for (const m of [...this.statics.keys()]) this._drop(m); this.providers = []; }
@@ -141,8 +181,9 @@ export class Rays {
141
181
  } else {
142
182
  const ray = this.ray.ray, tick = this.engine.time.tick;
143
183
  // matrices are refreshed by the render, and a fixed step runs before it: what moved or was added since would answer from where it was.
144
- // shortcut: once per tick and not per ray (a walk up the parents of 5000 statics costs more than the rays): something moved between two rays of one step answers from the next tick
184
+ // Once per tick and per frame, not per ray (5000 statics x 4 rays a frame measured 12 ms against 3-5 ms): a static moved between two rays of one step needs updateMatrixWorld() on it first (docs/api/rays.md)
145
185
  if (this.fresh !== tick) { this.fresh = tick; for (const m of this.statics.keys()) m.updateWorldMatrix(true, false); }
186
+ this.ray.firstHitOnly = !filter; // BVH keeps one hit per mesh: a filter running after that would lose the hit it accepts behind the one it refuses
146
187
  for (const [m, s] of this.statics) {
147
188
  if (occluders && !s.occ) continue; // first: a camera ray then pays one flag check for every mesh that is no blocker
148
189
  if (!mayHit(ray, m, far)) continue; // most statics are nowhere near the ray: skip them before walking parents
@@ -150,6 +191,7 @@ export class Rays {
150
191
  hits.length = 0; m.raycast(this.ray, hits);
151
192
  for (const h of hits) take(toHit(h));
152
193
  }
194
+ this.ray.firstHitOnly = true;
153
195
  if (targets === 'all') for (const p of this.providers) take(p(o.clone(), d.clone(), far));
154
196
  }
155
197
  if (best) { const e = this.engine, h = best; Object.defineProperty(h, 'thing', { get: () => thingOf(e, h.object, h), configurable: true }); } // computed only when read
@@ -6,7 +6,7 @@
6
6
  import { warnMissing } from '../base/validate.js';
7
7
  import { readParams, keysSchema } from '../base/params.js';
8
8
  import { codedError } from '../base/errorHints.js';
9
- import { holdFov } from './view.js';
9
+ import { holdFov, baseFov } from './view.js';
10
10
 
11
11
  const vec3 = a => Array.isArray(a) && a.length === 3 && a.every(Number.isFinite);
12
12
 
@@ -41,18 +41,24 @@ export class Views {
41
41
  show(name) {
42
42
  const v = this.map.get(name);
43
43
  if (!v) { warnMissing('view', name, this.list()); return null; }
44
- const e = this.engine, c = e.camera;
44
+ const e = this.engine;
45
45
  // focus: the world loads around what the view looks at, not around a player far away (the view was an empty sheet of ground without it)
46
- const focus = c.position.clone().fromArray(v.target);
47
- this._cam = e.takeCamera('views', { focus });
46
+ const focus = e.camera.position.clone().fromArray(v.target);
47
+ // onTop: a newer claim (a timeline shot) that moved the camera has released, and this one is in charge again: the view is put back, not just the claim (stack hook in core/ops/holds.js)
48
+ this._cam = e.takeCamera('views', { focus, onTop: () => this._put(name, v, focus) });
49
+ this._put(name, v, focus);
50
+ const cam = this._cam; // this showing, not the name: a handle kept from an earlier one must not end a later one
51
+ return { remove: () => { if (this._cam === cam) this.release(); } };
52
+ }
53
+ /** The view's pose and lens, on show and again each time the claim comes back on top */
54
+ _put(name, v, focus) {
55
+ const e = this.engine, c = e.camera;
48
56
  e.focus.copy(focus);
49
57
  c.position.fromArray(v.position); c.lookAt(...v.target);
50
- if (v.fov != null) holdFov(e, v.fov);
58
+ holdFov(e, v.fov ?? baseFov(e)); // a view without a fov shows the base lens: a shot that stood in front of it may have left its own
51
59
  c.updateMatrixWorld(true);
52
60
  this.current = name;
53
61
  e.events.emit('camera:shot', { name }); // a cut: what follows the camera (the light pool) settles at once instead of easing over
54
- const cam = this._cam; // this showing, not the name: a handle kept from an earlier one must not end a later one
55
- return { remove: () => { if (this._cam === cam) this.release(); } };
56
62
  }
57
63
  /** Give the camera back (to the previous holder, e.g. a running cutscene, or to the rig) */
58
64
  release() {
@@ -1,16 +1,19 @@
1
- // Adaptive resolution by frame cost.
2
- // Lowers the render scale when frames cost more than the target allows, raises it back slowly when they are cheap.
1
+ // Adaptive quality by frame cost: one controller, one ladder of steps.
2
+ // When frames cost more than the target allows it lowers one step, when they are cheap it raises the last lowered step back, slowly.
3
3
  // It judges frame COST (main-thread cpuMs, plus GPU time from EXT_disjoint_timer_query_webgl2 when the browser has it), not fps, because a low fps
4
4
  // alone is ambiguous: a display or power mode that refreshes at 30 Hz (laptop battery saver, phone low-power mode) gives 33.3 ms frames with
5
- // almost no work, and lowering the resolution there only blurs the picture for nothing. The fps path stays only as the fallback without GPU time
5
+ // almost no work, and lowering the picture there only blurs it for nothing. The fps path stays only as the fallback without GPU time
6
6
  // (a GPU-bound game shows a low cpuMs), and even then a frame interval locked to the display's own refresh does not count as overload.
7
7
  // Frames that compiled shaders (ApplyCost.rendered reports them) and the first GRACE seconds after ready are not judged: startup hitches are
8
- // one-off costs that resolution cannot fix.
8
+ // one-off costs that lowering cannot fix, and a step that rebuilds the post chain must not judge its own compile.
9
9
  //
10
- // shortcut: only the resolution is adjusted. A tier ladder (resolution -> shadows -> view distance -> vegetation) would hang off decide() below as
11
- // further steps once a game needs it; until then the other knobs stay the game's (settings / engine.autoView).
10
+ // The ladder (engine.adaptive.steps; docs/plans/2026-11-09-quality-ladder.md): the game says what may be lowered and in which order. Default, cheapest
11
+ // to see first (Unity's Adaptive Performance lowers low-visual-impact scalers first): each post effect's own `cheaper` params (live uniforms: no
12
+ // recompile), then the resolution, then the effects that declare skipOnLowTier held off (a chain rebuild and a compile: last, and never back and forth,
13
+ // see FLAP). No list of expensive effects lives here: an effect declares cheaper / skipOnLowTier itself, the engine follows. Only downward: nothing is
14
+ // set above what the game wrote, an effect the player or game has off is not a step, and a hold sits on the 'effect' layer: above the game's own writes, under a cutscene or menu (system) and the player's settings, so their later sets never clash with it.
12
15
  import { DEV, warnOnce } from '../base/validate.js';
13
- import { coded } from '../base/errorHints.js';
16
+ import { coded, codedError } from '../base/errorHints.js';
14
17
  import { writeRatio } from './pixelRatio.js';
15
18
 
16
19
  const GRACE = 3; // s after ready that are not judged (warm-up compiles, first uploads, stream fill)
@@ -19,36 +22,149 @@ const HEAVY = 0.85; // cost above this share of the frame budget = overloa
19
22
  const LIGHT = 0.6; // cost under this share = headroom (raise after RAISE_AFTER windows in a row)
20
23
  const RAISE_AFTER = 4;
21
24
  const LOCK_TOL = 0.08; // intervals within 8 % of the window median count as "clustered"
25
+ // a step other than the resolution that comes down again within FLAP s of going up was not affordable: its next raise waits WAIT s, doubled each time.
26
+ // Why: the cost with an effect off says nothing about its cost on, so "cheap now" can raise it into the same overload; without this it toggles, and each toggle compiles
27
+ const FLAP = 20, WAIT = 15;
28
+ const OWNER = 'adaptive';
22
29
  const HELD = coded('pixel-conflict', 'engine.adaptive.on = true does nothing while pixelSize is on; it comes back with engine.setPixelSize(null)');
30
+ const STEP_FORMS = "'resolution', 'post.<name>' (the effect's cheaper params), 'post.<name>.off' (the effect held off) or { name, down(), up() } (down returns false when it cannot go lower)";
31
+
32
+ /** Adaptive resolution lowered the render scale and it has not climbed back to its top: describe().render.scale's answer
33
+ * @param {any} e @returns {boolean} */
34
+ export function autoLowered(e) {
35
+ const a = e.adaptive, cur = e.renderer.getPixelRatio();
36
+ return !!a?.lowered && cur < (a.max ?? cur) - 0.01;
37
+ }
38
+
39
+ /** What the ladder holds lowered now, in one clause, or null: the one report, read by engine.budget.notice() (shot, verify, describe text print it)
40
+ * @param {any} e @returns {string | null} */
41
+ export function loweredText(e) {
42
+ const a = e.adaptive;
43
+ if (!a) return null;
44
+ const parts = [...(autoLowered(e) ? [`resolution ${a.max} -> ${Math.round(e.renderer.getPixelRatio() * 100) / 100}`] : []), ...[...a.held.values()].map(s => s.text())];
45
+ return parts.length ? `lowered automatically: ${parts.join(', ')} (${a.reason})` : null;
46
+ }
47
+
48
+ /** @param {any} v */
49
+ function checkSteps(v) {
50
+ if (v === null) return v;
51
+ const bad = !Array.isArray(v) ? [v] : v.filter(s => !(s === 'resolution' || (typeof s === 'string' && /^post\.[^.]+(\.off)?$/.test(s))
52
+ || (s && typeof s === 'object' && typeof s.name === 'string' && typeof s.down === 'function' && typeof s.up === 'function')));
53
+ if (bad.length) throw codedError('engine-misuse', `engine.adaptive.steps: a list (first lowered first) of ${STEP_FORMS}; null = the default ladder; got ${JSON.stringify(bad[0]) ?? String(bad[0])}`);
54
+ const keys = v.map(keyOf), twice = keys.find((k, i) => keys.indexOf(k) !== i);
55
+ if (twice) throw codedError('engine-misuse', `engine.adaptive.steps: '${twice}' is listed twice; each step once, in the order it is lowered`);
56
+ return v.slice();
57
+ }
58
+ const keyOf = s => (typeof s === 'string' ? s : `game.${s.name}`);
23
59
 
24
60
  /**
25
- * The engine.adaptive state object: the public fields (on, target, min, max, base, lowered, from; base is what this device or game starts at, the settings presets' base) plus the
61
+ * The engine.adaptive state object: the public fields (on, target, min, max, base, lowered, from, steps; base is what this device or game starts at, the settings presets' base) plus the
26
62
  * controller's own counters. on is an accessor because every reader (the loop's GPU timer, describe, settings) must see false under pixelSize; what was asked for stays and returns with setPixelSize(null).
63
+ * held: what the ladder lowers now besides the resolution, key -> { text, undo }; the resolution needs no entry (renderer ratio against max says it).
27
64
  * @param {{ on: boolean, target: number, max: number, held: () => boolean }} o held: pixelSize decides the ratio now
28
65
  */
29
66
  export function createAdaptive({ on, target, max, held }) {
30
- let wanted = on;
67
+ let wanted = on, steps = null;
31
68
  return { get on() { return wanted && !held(); },
32
69
  set on(v) { wanted = v; if (DEV && v && held()) warnOnce(HELD); },
70
+ get steps() { return steps; }, set steps(v) { steps = checkSteps(v); },
33
71
  target, min: 0.6, max, base: max, t: 0, good: 0, cooldown: 0, lowered: false, from: null,
34
- age: 0, costs: [], gaps: [], refresh: Infinity, reason: null };
72
+ age: 0, costs: [], gaps: [], refresh: Infinity, reason: null, held: new Map(), raisedAt: {}, wait: {}, notBefore: {}, warned: false };
35
73
  }
36
74
 
37
75
  const median = a => { const s = a.slice().sort((x, y) => x - y); return s.length ? s[s.length >> 1] : 0; };
38
76
 
77
+ /** The default ladder: from the effects added now, in chain order @param {any} e */
78
+ function defaultSteps(e) {
79
+ const fx = e.post?._sorted?.() ?? [];
80
+ return [...fx.filter(h => h._def.cheaper).map(h => `post.${h.name}`), 'resolution', ...fx.filter(h => h._def.skipOnLowTier).map(h => `post.${h.name}.off`)];
81
+ }
82
+
83
+ /**
84
+ * One step as { key, down(), lowered(), up() }. down() lowers one notch and says whether it did; up() raises one notch. Every lowered step but the
85
+ * resolution keeps an entry in a.held with its undo, so turning the controller off, a step leaving the list or its effect going away puts it back.
86
+ * @param {any} e @param {any} s
87
+ */
88
+ function stepOf(e, s) {
89
+ const a = e.adaptive, held = a.held, key = keyOf(s), pr = () => e.renderer.getPixelRatio();
90
+ if (s === 'resolution') return { key,
91
+ // a ratio the game wrote with renderer.setPixelRatio is the game's (core/ops/owned.js): this step stands aside, the others still run
92
+ down() {
93
+ const p = pr();
94
+ if (!e._oPixelRatio.on || p <= a.min + 0.01) return false;
95
+ if (!a.lowered) { a.lowered = true; a.from = p; }
96
+ writeRatio(e, Math.max(a.min, +(p - 0.1).toFixed(2)));
97
+ return true;
98
+ },
99
+ lowered: () => e._oPixelRatio.on && pr() < a.max - 0.01,
100
+ up() { writeRatio(e, Math.min(a.max, +(pr() + 0.05).toFixed(2))); } };
101
+ const up = () => held.get(key)?.undo();
102
+ if (typeof s === 'object') return { key, lowered: () => held.has(key), up,
103
+ // the game's own knob (view distance, density): it says when it is at its floor; each notch down is undone by one up()
104
+ down() {
105
+ if (s.down() === false) return false;
106
+ // step: which object holds these notches, so a new step of the same name never raises with this one's up() (ladder)
107
+ const st = held.get(key) ?? { n: 0, step: s, text: () => (st.n > 1 ? `${s.name} x${st.n}` : s.name), undo: () => { s.up(); if (--st.n <= 0) held.delete(key); } };
108
+ st.n++; held.set(key, st);
109
+ return true;
110
+ } };
111
+ const [, name, off] = /^post\.([^.]+)(\.off)?$/.exec(s) ?? [];
112
+ return { key, lowered: () => held.has(key), up,
113
+ down() {
114
+ const h = e.post.get(name);
115
+ if (!h || !h.enabled || held.has(key)) return false; // not added, off by the game or player, held by the tier: nothing to lower
116
+ if (off) {
117
+ const point = e.post.switchPoint(`post.${name}.enabled`);
118
+ // an effect-layer set by another owner throws shared-conflict: then this step is not ours to take
119
+ try { point.take({ owner: OWNER, layer: 'effect', set: false }); } catch { return false; }
120
+ held.set(key, { h, text: () => `${name} off`, undo: () => { held.delete(key); point.release(OWNER); } });
121
+ return true;
122
+ }
123
+ // only downward: a number param goes lower, never higher; any other kind is taken as the effect wrote it
124
+ const to = Object.fromEntries(Object.entries(h._def.cheaper ?? {}).filter(([k, v]) => k in h.params && (typeof v === 'number' ? v < h.params[k] : v !== h.params[k])));
125
+ if (!Object.keys(to).length) return false;
126
+ const was = Object.fromEntries(Object.keys(to).map(k => [k, h.params[k]]));
127
+ h.set(to);
128
+ // back only what still holds the lowered value: a param the game set meanwhile is the game's newer word
129
+ held.set(key, { h, text: () => `${name} cheaper`, undo: () => {
130
+ held.delete(key);
131
+ const back = Object.fromEntries(Object.entries(was).filter(([k]) => h.params[k] === to[k]));
132
+ if (!h._removed && Object.keys(back).length) h.set(back);
133
+ } });
134
+ return true;
135
+ } };
136
+ }
137
+
138
+ /**
139
+ * The steps now, and anything held by a step that left the list, whose effect was removed, or that was replaced by another of that name (an effect or a
140
+ * game step: same key, other object) put back, with the old one's own undo, before the new one lowers anything @param {any} e
141
+ */
142
+ function ladder(e) {
143
+ const a = e.adaptive, given = a.steps ?? defaultSteps(e), list = given.map(s => stepOf(e, s)), now = new Map(given.map(s => [keyOf(s), s]));
144
+ for (const [k, st] of [...a.held]) if (!now.has(k) || (st.h && e.post.get(st.h.name) !== st.h) || (st.step && now.get(k) !== st.step)) drop(a.held, k);
145
+ return list;
146
+ }
147
+
148
+ /** Every notch of one held step undone (a game step lowered three times is raised three times) @param {Map<string, any>} held @param {string} k */
149
+ function drop(held, k) { while (held.has(k)) held.get(k).undo(); }
150
+
151
+ /** Put back everything the ladder holds (the controller turned off, pixelSize on). The resolution stays where it is: settings' 'adaptive' row and setPixelRatio own that write @param {any} e */
152
+ function releaseAll(e) { for (const k of [...e.adaptive.held.keys()]) drop(e.adaptive.held, k); }
153
+
39
154
  /**
40
155
  * One frame's sample. dt in s (the requestAnimationFrame interval), cost in ms (max of cpu and gpu), compiled: this frame compiled shaders.
41
156
  * gpuKnown: cost includes measured GPU time, so a slow interval with a cheap cost is never our overload.
42
157
  */
43
158
  export function adapt(e, dt, cost, compiled, gpuKnown) {
44
159
  const a = e.adaptive;
45
- if (!a.on || !e.ready) return;
160
+ if (!a.on) { if (a.held.size) releaseAll(e); return; }
161
+ if (!e.ready) return;
46
162
  a.age += dt; a.t += dt; a.cooldown -= dt;
47
163
  if (!compiled) { a.costs.push(cost); a.gaps.push(dt * 1000); }
48
164
  if (a.t < WINDOW) return;
49
165
  const costs = a.costs, gaps = a.gaps; a.t = 0; a.costs = []; a.gaps = [];
50
- // the game set renderer.setPixelRatio itself: adaptive resolution stops (core/ops/owned.js); engine.autoView.manual('pixelRatio', false) resumes it
51
- e._oPixelRatio.check(); if (!e._oPixelRatio.on) return;
166
+ // the game set renderer.setPixelRatio itself: the resolution step stands aside (core/ops/owned.js); engine.autoView.manual('pixelRatio', false) resumes it
167
+ e._oPixelRatio.check();
52
168
  if (!gaps.length) return;
53
169
  const gap = median(gaps), clustered = gaps.filter(g => Math.abs(g - gap) <= gap * LOCK_TOL).length >= gaps.length * 0.7;
54
170
  // the fastest steady interval ever seen is the display's refresh (learned during grace too: loading frames are slower, never faster)
@@ -60,15 +176,22 @@ export function adapt(e, dt, cost, compiled, gpuKnown) {
60
176
  // locked: the frames wait on the display (steady at its refresh, work clearly shorter than the interval), not on us
61
177
  const locked = clustered && Math.abs(gap - a.refresh) <= a.refresh * LOCK_TOL && c < gap * 0.8;
62
178
  const overload = heavy || (!gpuKnown && slow && !locked);
63
- const pr = e.renderer.getPixelRatio();
64
- if (overload && pr > a.min + 0.01) {
65
- const to = Math.max(a.min, +(pr - 0.1).toFixed(2));
179
+ const steps = ladder(e);
180
+ if (overload) {
181
+ a.good = 0;
182
+ const s = steps.find(x => x.down());
183
+ if (!s) return;
66
184
  a.reason = heavy ? `frames cost ${c.toFixed(1)} ms of a ${budget.toFixed(1)} ms budget (target ${a.target} fps)` : `fps ${(1000 / gap).toFixed(0)} is under ${a.target}`;
67
- // never silent: the picture gets softer, and the game or an AI should know why (dev warning once; describe().render.scale keeps the facts)
68
- if (!a.lowered) { a.lowered = true; a.from = pr; if (DEV) warnOnce(`render scale ${pr} -> ${to} because ${a.reason}; adaptive resolution lowers it down to ${a.min}. Turn off with createEngine({ adaptiveResolution: false }) or engine.adaptive.on = false; see describe().render.scale`); }
69
- writeRatio(e, to); a.good = 0; a.cooldown = 5;
70
- } else if (!overload && c < budget * LIGHT && pr < a.max - 0.01 && a.cooldown <= 0) {
71
- if (++a.good >= RAISE_AFTER) { writeRatio(e, Math.min(a.max, +(pr + 0.05).toFixed(2))); a.good = 0; }
185
+ a.cooldown = 5;
186
+ // a step that stayed up for 4 x FLAP was affordable after all: its wait starts over
187
+ if (s.key !== 'resolution') { const up = a.age - (a.raisedAt[s.key] ?? -Infinity); if (up < FLAP) { a.wait[s.key] = (a.wait[s.key] ?? WAIT / 2) * 2; a.notBefore[s.key] = a.age + a.wait[s.key]; } else if (up > FLAP * 4) delete a.wait[s.key]; }
188
+ // never silent: the picture changes, and the game or an AI should know why (dev warning once; engine.budget.notice() keeps what is lowered now)
189
+ if (DEV && !a.warned) { a.warned = true; warnOnce(`${loweredText(e)}; adaptive quality lowers engine.adaptive.steps in order (resolution down to ${a.min}). Turn off with createEngine({ adaptiveResolution: false }) or engine.adaptive.on = false; engine.budget.notice() says what is lowered`); }
190
+ } else if (c < budget * LIGHT && a.cooldown <= 0) {
191
+ // last lowered goes up first; a step that flapped waits its turn, and the ones before it with it
192
+ const s = steps.findLast(x => x.lowered());
193
+ if (!s || a.age < (a.notBefore[s.key] ?? 0)) { a.good = 0; return; }
194
+ if (++a.good >= RAISE_AFTER) { s.up(); a.good = 0; if (s.key !== 'resolution') a.raisedAt[s.key] = a.age; }
72
195
  } else a.good = 0;
73
196
  }
74
197
 
@@ -0,0 +1,17 @@
1
+ // Parts the engine draws for something else, not things of their own: a cascade's extra copies of the sun (the material patch adds them up to
2
+ // one sun), far impostor cards placed only in the vertex shader, the sky dome. Whatever copies the scene (the photo path trace, the gallery's
3
+ // 'game' light) leaves every marked object out: one rule here, so no copier keeps its own list and a new such part is covered by marking it.
4
+ // A WeakMap, not userData: three's clone() copies userData, so a game's own clone of a marked object (a cascade light reused as a fill light,
5
+ // a cloned sky mesh) would be hidden too. The tools package reads it through the 'threedog/draw-only' export (the same module instance).
6
+
7
+ /** object -> what a copy lacks without it, in plain words ('' when nothing is: the real sun stays) */
8
+ const MARKED = new WeakMap();
9
+ /**
10
+ * Mark objects as drawn for something else (returns the first, so it fits in the call). For engine module code.
11
+ * @template {import('three').Object3D} T @param {string} what @param {[T, ...import('three').Object3D[]]} objs @returns {T}
12
+ */
13
+ export function drawOnly(what, ...objs) { for (const o of objs) MARKED.set(o, what); return objs[0]; }
14
+ /** True for an object drawOnly marked (never for a clone of one) @param {any} o @returns {boolean} */
15
+ export const isDrawOnly = o => MARKED.has(o);
16
+ /** What a copy lacks without o ('' when nothing), undefined when o is not marked @param {any} o @returns {string | undefined} */
17
+ export const drawOnlyWhat = o => MARKED.get(o);
@@ -12,10 +12,15 @@
12
12
  // What stays the game's: color, intensity, distance, castShadow (turning shadows off is the renderer's switch, render/shadows.js), the shadow map size and bias. The engine never writes them (P1).
13
13
  // lightPool stays the optional helper for "many lamps, few real lights": that trade-off is a game decision the engine cannot guess.
14
14
  // Cost: a scene visitor (no walk per frame); per frame one loop over the shadow-casting game lights, usually zero to three.
15
+ // RectAreaLight: three leaves its LTC tables (314 KB of numbers) to the game, and a game that forgets gets a failed shader build on WebGPU and a black
16
+ // light on WebGL. The first one to enter the scene loads them, once per page (three keeps them in statics too). The import is async and a frame may draw
17
+ // first, so WebGPU gets same-shaped stand-ins at once (an identity matrix: the diffuse part is exact, the shine is missing for that frame) that the real
18
+ // numbers are then copied into. Area lights have no shadows in three, and light only MeshStandard / MeshPhysical materials.
19
+ import { DataTexture, FloatType, HalfFloatType, RGBAFormat, UVMapping, ClampToEdgeWrapping, LinearFilter, NearestFilter } from 'three';
15
20
  import { sceneVisitor } from './sceneDelta.js';
16
21
  import { moduleOwnerOf } from './things.js';
17
22
  import { notePatch, patchOn } from './threePatches.js';
18
- import { shadowMaps } from '../../render/backend.js';
23
+ import { shadowMaps, webgpuPartOrNull } from '../../render/backend.js';
19
24
  import { warnOnce, fmt } from '../base/validate.js';
20
25
  import { MANY } from '../inspect/lightWatch.js';
21
26
  import { isShown } from '../base/util.js';
@@ -31,20 +36,48 @@ const placeholderOn = e => ['sun', 'hemi'].some(k => { const l = e.lights?.[k];
31
36
  /** The engine module that owns o (it or an ancestor carries engineOwned), else null */
32
37
  function engineOwner(o) { for (let p = o; p; p = p.parent) { const m = moduleOwnerOf(p); if (m) return m; } return null; }
33
38
 
39
+ let areaTables = false; // page-wide, as three's own tables are (R29 ALLOW)
40
+ function loadAreaTables() {
41
+ if (areaTables) return;
42
+ areaTables = true;
43
+ const node = webgpuPartOrNull('classes')?.RectAreaLightNode, size = 64 * 64 * 4;
44
+ const standIn = (half, matrix) => {
45
+ const data = half ? new Uint16Array(size) : new Float32Array(size);
46
+ if (matrix) for (let i = 0; i < size; i += 4) data[i] = data[i + 3] = half ? 0x3c00 : 1; // 0x3c00 is 1 as a half float
47
+ const t = new DataTexture(data, 64, 64, RGBAFormat, half ? HalfFloatType : FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1);
48
+ t.needsUpdate = true;
49
+ return t;
50
+ };
51
+ /** @type {Record<string, any> | null} */
52
+ const stand = node ? { LTC_FLOAT_1: standIn(false, true), LTC_FLOAT_2: standIn(false, false), LTC_HALF_1: standIn(true, true), LTC_HALF_2: standIn(true, false) } : null;
53
+ if (stand) node.setLTC(stand);
54
+ Promise.all([import('three/addons/lights/RectAreaLightUniformsLib.js'), import('three/addons/lights/RectAreaLightTexturesLib.js')]).then(([{ RectAreaLightUniformsLib }, { RectAreaLightTexturesLib: lib }]) => {
55
+ RectAreaLightUniformsLib.init(); // WebGLRenderer reads them from UniformsLib, the WebGPU node from the stand-ins
56
+ for (const k in stand) { stand[k].image.data.set(lib[k].image.data); stand[k].needsUpdate = true; }
57
+ }, err => {
58
+ areaTables = false;
59
+ for (const k in stand) stand[k].dispose();
60
+ warnOnce(`RectAreaLight: three's LTC tables did not load (${err?.message ?? err}): on WebGPU the light gives diffuse light only, no shine; on WebGL none. Loading is tried again when a RectAreaLight next enters the scene`);
61
+ });
62
+ }
63
+
34
64
  /** @param {any} e */
35
65
  export function watchGameLights(e) {
36
66
  const all = new Set(), game = new Set(), idled = new WeakSet(), handed = new WeakSet();
67
+ // The one place autoUpdate goes back to the game: only a light the engine idled, and only if the game has not written the value since (then it is the game's)
68
+ const giveBack = l => { if (!idled.delete(l)) return; if (!l.shadow.autoUpdate) { l.shadow.autoUpdate = true; l.shadow.needsUpdate = true; } };
37
69
  const view = sceneVisitor(e.scene, {
38
70
  enter(o) {
39
71
  if (o.isLight && !o.isLightProbe && !o.isLightProbeGrid && o !== e.lights?.sun && o !== e.lights?.hemi && !o.userData.fixedCount && !engineOwner(o) && placeholderOn(e))
40
72
  warnOnce(fmt(ADDED_UP, { what: o.name || o.type }), 'game-light-adds-up');
73
+ if (o.isRectAreaLight) loadAreaTables();
41
74
  if (!o.isPointLight && !o.isSpotLight) return;
42
75
  all.add(o);
43
76
  if (!o.userData.fixedCount && !engineOwner(o)) game.add(o);
44
77
  },
45
78
  leave(o) {
46
79
  all.delete(o); game.delete(o);
47
- if (idled.has(o)) { idled.delete(o); o.shadow.autoUpdate = true; o.shadow.needsUpdate = true; } // leaves as the game left it
80
+ giveBack(o); // leaves as the game left it
48
81
  },
49
82
  });
50
83
  const count = (fn) => { view.sync(); let n = 0; for (const l of all) if (fn(l)) n++; return n; };
@@ -58,6 +91,8 @@ export function watchGameLights(e) {
58
91
  list() { view.sync(); return [...game]; },
59
92
  /** Every point / spot light in the scene, modules' and pools' too; a live set, for reading */
60
93
  all() { view.sync(); return all; },
94
+ /** Catch up with what entered the scene: before a compile or a draw outside the loop, so a RectAreaLight has its tables first */
95
+ sync() { view.sync(); },
61
96
  /** Before each render (loop.js): the idle-shadow rule */
62
97
  frame() {
63
98
  view.sync();
@@ -67,13 +102,19 @@ export function watchGameLights(e) {
67
102
  const opted = !patchOn('light-idle-shadow') || l.userData.idleShadow === false;
68
103
  if (idled.has(l)) {
69
104
  if (s.autoUpdate) { idled.delete(l); handed.add(l); } // the game turned redraws on itself while idled: its light from now on
70
- else if (l.intensity > 0 || !l.castShadow || opted) { idled.delete(l); s.autoUpdate = true; s.needsUpdate = true; } // put back what was taken
105
+ else if (l.intensity > 0 || !l.castShadow || opted) giveBack(l); // put back what was taken
71
106
  } else if (l.castShadow && l.intensity <= 0 && s.autoUpdate && !opted && !handed.has(l)) { s.autoUpdate = false; idled.add(l); }
72
107
  }
73
108
  },
109
+ /** Engine dispose: stop watching the scene and hand every idled light back (a light may outlive the engine in another scene) */
110
+ dispose() { view.remove(); for (const l of game) giveBack(l); },
74
111
  /** Whether the engine holds this light's shadow redraw now (describe) */
75
112
  idled: l => idled.has(l),
76
113
  };
77
114
  }
115
+ /** @internal Every point / spot light in the scene (a live set, for reading; empty before the watch starts): for modules, which do not reach into e._gameLights */
116
+ export function pointSpotLights(e) { return e._gameLights?.all() ?? EMPTY; }
117
+ const EMPTY = new Set();
118
+
78
119
  notePatch('light-idle-shadow', "shadow.autoUpdate of the game's own shadow-casting point / spot lights: off while intensity is 0, back on when lit (core/scene/gameLights.js)",
79
120
  () => {}, { scope: 'objects in the scene', lost: 'a casting light at intensity 0 redraws its shadow map every frame, as in plain three.js' });
@@ -7,9 +7,7 @@ import { codedError } from '../base/errorHints.js';
7
7
  import { thing } from './thingOps.js';
8
8
  import { isUnder } from '../base/util.js';
9
9
  import { freshFrame, renderOnce as drawOnce } from '../../render/backend.js';
10
-
11
- /** The geometry and materials of one object */
12
- const parts = o => [o.geometry, ...[].concat(o.material)].filter(Boolean);
10
+ import { freeParts, partsOf as parts, copyOwns, kept } from '../base/freeParts.js';
13
11
  /**
14
12
  * How many objects in the scene use each geometry and material. Why remove asks: disposing a kit that other streamed blocks still draw makes the renderer
15
13
  * rebuild all of them (worst frame 270 ms against 79 in the city stress run). One walk per task, so removing ten thousand objects in a loop walks once; an object
@@ -71,9 +69,12 @@ export const sceneMethods = {
71
69
  thingConflict(text) { this._things.conflict(text); },
72
70
  /**
73
71
  * Delete an object for good: detach it, unregister its rays and dispose the geometries and materials nothing else in the scene uses (textures are kept).
74
- * One still used by another object stays, and goes with its last user. Geometry and materials shared by assets model clones are only decremented in use count (see Assets.js)
72
+ * One still used by another object stays, and goes with its last user. Geometry and materials shared by assets model clones are only decremented in use count (see Assets.js).
73
+ * The call is the game handing the object over (design.md 6.2), so a part the game made goes too; a model copy's own bones go with the copy
75
74
  */
76
75
  remove(...objs) {
76
+ // every root leaves and is uncounted first, then one free over all of them: two roots sharing a material free it once, and a part one root still
77
+ // drew while the other was freed is not kept by a root that is leaving in the same call
77
78
  for (const o of objs) {
78
79
  const counted = isUnder(o, this.scene) && !!this._users; // the count was made while this object was still in the scene
79
80
  o.removeFromParent();
@@ -81,19 +82,19 @@ export const sceneMethods = {
81
82
  this.rays.forget(o);
82
83
  this.assets.forget(o);
83
84
  this._poses.forget(o);
84
- const shared = this.assets.shared, held = this.batching.held; // a batch still drawing the same geometry / material keeps it alive
85
85
  if (counted) o.traverse(c => { for (const x of parts(c)) this._users.set(x, (this._users.get(x) ?? 0) - 1); });
86
- // The whole-scene count only for a part nothing else keeps: unloading a streamed block whose kit is all held by batches walked every object of the district for nothing (7 ms in one frame of the city run)
87
- const free = []; o.traverse(c => { for (const x of parts(c)) if (!shared.has(x) && !held.has(x)) free.push(x); });
88
- if (free.length) { const users = sceneUsers(this); for (const x of free) if (!(users.get(x) > 0)) x.dispose(); }
89
86
  }
87
+ const shared = this.assets.shared, held = this.batching.held; // a batch still drawing the same geometry / material keeps it alive
88
+ // The whole-scene count only for a part nothing else keeps (mine asks the cheap sets first): unloading a streamed block whose kit is all held by batches
89
+ // walked every object of the district for nothing (7 ms in one frame of the city run). A kept part (keepPart) is its maker's to free
90
+ freeParts(objs, x => !shared.has(x) && !held.has(x) && !kept(x) && !(sceneUsers(this).get(x) > 0), { own: c => copyOwns(shared, c) || c.isInstancedMesh || c.isBatchedMesh });
90
91
  },
91
92
  /**
92
93
  * Draw one picture now, outside the loop, on either renderer. renderOnce() (target null, the engine camera): the frame the player sees, onto
93
94
  * the canvas through engine.post; read the canvas in the same task (canvas.toDataURL / drawImage), as photo mode does.
94
- * renderOnce(target): that frame through engine.post into a render target instead (the canvas's pixels: tone mapped, output color space;
95
- * with no post work on, three's plain draw into a target). renderOnce(target, camera) with another camera: the scene without post (the chain
96
- * is built around the engine camera's screen), into target or, with target null, the canvas. On WebGPURenderer each call is a fresh node frame, so a RenderPipeline's scene
95
+ * renderOnce(target): that frame into a render target instead, always the canvas's pixels (tone mapped, output color space), whether or not an
96
+ * effect is on. renderOnce(target, camera) with another camera: the scene without post (the chain is built around the engine camera's screen) and
97
+ * as three draws into a target, linear and not tone mapped (for data or your own pass); into target or, with target null, the canvas. On WebGPURenderer each call is a fresh node frame, so a RenderPipeline's scene
97
98
  * pass, which three draws once per frame, draws again: two calls in one task give two pictures (docs/plans/2026-11-03-webgpu-phase2.md 3).
98
99
  * @example engine.renderOnce(); const url = engine.renderer.domElement.toDataURL('image/png');
99
100
  * engine.renderOnce(rt, mapCamera); // a minimap / thumbnail into your own render target
@@ -103,6 +104,7 @@ export const sceneMethods = {
103
104
  */
104
105
  renderOnce(target = null, camera = this.camera) {
105
106
  const own = this._ownFrame; // an engine draw, not the game taking the canvas over (render/ownFrame.js)
107
+ this._gameLights?.sync(); // the light watch catches up first: a RectAreaLight added since the last frame gets its tables before this draw (gameLights.js)
106
108
  if (own) own.inside++;
107
109
  try {
108
110
  if (camera === this.camera) { freshFrame(this.renderer); this.post.render(0, target); return; }
@@ -5,6 +5,7 @@
5
5
  // would rewrite the Euler the mover keeps facing in. The object's own matrix is composed here and matrixAutoUpdate is off just for that draw.
6
6
  // Anything that placed the object outside a step (a tween, a frame-driven mover, a platform carried in frame) leaves it different from the step's end: it is then drawn as it stands.
7
7
  import * as THREE from 'three';
8
+ import { codedError } from '../base/errorHints.js';
8
9
 
9
10
  /** Farther than this in one step (squared meters) is a teleport, not motion: drawn at once, never swept across the map */
10
11
  const JUMP2 = 16;
@@ -18,9 +19,16 @@ export class StepPoses {
18
19
  /** objects whose matrix is held for this draw */ this.held = [];
19
20
  engine.time.onMove(() => this.end());
20
21
  }
21
- /** place(at): how to move o if a solver owns its pose (a rigid body); gone(): what that solver does when o leaves for good. Core names no module, so the solver says both here */
22
- add(o, place = null, gone = null) { this.map.set(o, { o, place, gone, last: o.position.clone(), lastRot: o.quaternion.clone(), pos: o.position.clone(), rot: o.quaternion.clone(), moved: false }); }
23
- remove(o) { this.map.delete(o); }
22
+ /** place(at): how to move o if a solver owns its pose (a rigid body); gone(): what that solver does when o leaves for good. Core names no module, so the solver says both here.
23
+ * One object, one owner: a second add throws and names the first (two solvers writing one mesh, the last one winning silently, was the bug). owner() names it for that error (a function, so a character's id is read only if it is needed). Returns the owner's handle:
24
+ * remove() deletes only this entry, so an owner that is already gone cannot delete a newer one's */
25
+ add(o, place = null, gone = null, owner = () => 'another owner') {
26
+ const had = this.map.get(o);
27
+ if (had) throw codedError('rigid-misuse', `This object already has a physics owner: ${had.owner()}. One object has one owner of its pose (a rigid body, a character); ${owner()} cannot also take it. Remove the first (its remove() / dispose()) or give ${owner()} an object of its own`);
28
+ const p = { o, owner, place, gone, last: o.position.clone(), lastRot: o.quaternion.clone(), pos: o.position.clone(), rot: o.quaternion.clone(), moved: false };
29
+ this.map.set(o, p);
30
+ return { remove: () => { if (this.map.get(o) === p) this.map.delete(o); } };
31
+ }
24
32
  /** o and all under it left for good (engine.remove): a level's root takes the crates placed in it along, and a solver must not keep them solid and unseen */
25
33
  forget(o) { if (this.map.size) o.traverse(c => this.map.get(c)?.gone?.()); }
26
34
  /** A write moves o outside any step: the object goes there, and whatever solves it too, or the solver's next pose would undo the write */
@@ -8,9 +8,11 @@ const KEYS = ['radius', 'cone', 'close', 'angleWeight', 'blocked', 'at'];
8
8
  const yawOf = view => typeof view === 'number' ? view : Math.atan2(view.x, view.z);
9
9
  /** Candidate position: an Object3D / NPC / Character / world record has .position; a Vector3 / { x, z } / [x, y, z] is the position itself */
10
10
  const posOf = c => c.position ?? c;
11
+ // these two functions live in api/tools.md, not api/engine.md (the code's default page), so the error carries its own pointer
12
+ const misuse = (code, text) => Object.assign(codedError(code, text), { docs: ['api/tools.md'] });
11
13
  function check(fn, opts) {
12
- if ('range' in opts) throw codedError('unknown-option', `${fn}(): the distance option is radius (meters), as in world.query: write { radius: ${opts.range} }`);
13
- for (const k of Object.keys(opts)) if (!KEYS.includes(k)) throw codedError('unknown-option', `${fn}(): unknown option '${k}'; available: ${KEYS.join(', ')}`);
14
+ if ('range' in opts) throw misuse('unknown-option', `${fn}(): the distance option is radius (meters), as in world.query: write { radius: ${opts.range} }`);
15
+ for (const k of Object.keys(opts)) if (!KEYS.includes(k)) throw misuse('unknown-option', `${fn}(): unknown option '${k}'; available: ${KEYS.join(', ')}`);
14
16
  }
15
17
 
16
18
  /**
@@ -47,7 +49,7 @@ export function pickTarget(from, view, candidates, opts = {}) {
47
49
  */
48
50
  export function switchTarget(from, view, current, candidates, side, opts = {}) {
49
51
  check('switchTarget', opts);
50
- if (side !== 1 && side !== -1) throw codedError('engine-misuse', `switchTarget(): side must be 1 (right) or -1 (left), got ${side}`);
52
+ if (side !== 1 && side !== -1) throw misuse('engine-misuse', `switchTarget(): side must be 1 (right) or -1 (left), got ${side}`);
51
53
  const { radius = 15, blocked = null, at = posOf } = opts;
52
54
  const [fx, fz] = xzOf(posOf(from)), yaw = yawOf(view);
53
55
  // right of the view is the negative angle direction (facing grows toward +X, the screen's right is at -yaw), so negate to sort left → right