threedog 0.8.0 → 1.0.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 (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -58,8 +58,12 @@ export class Views {
58
58
  * view distance)
59
59
  */
60
60
  radius(p) { const r = p.radius; return typeof r === 'function' ? r() : r ?? this.w.radius; }
61
- /** A source was added / removed or moved more than min(cell / 4, 8 m) since the last refresh: refresh (that is the error of "build within radius") */
62
- moved() { return this.w.engine.stream.changed(this.memo, Math.min(this.w._cells.size / 4, 8), FULL, false); }
61
+ /** A source was added / removed or moved more than min(cell / 4, 8 m) since the last refresh, or a radius changed with nothing moving (a view distance set in a menu): refresh (that is the error of "build within radius") */
62
+ moved() {
63
+ if (this.w.engine.stream.changed(this.memo, Math.min(this.w._cells.size / 4, 8), FULL, false)) return true;
64
+ for (const p of this.presenters.values()) if (this.radius(p) !== this.radii.get(p)) return true;
65
+ return false;
66
+ }
63
67
  /** Radius of presentation p for source s (a source radius caps it) */
64
68
  reach(p, s) { return s.reach(this.radii.get(p) ?? this.radius(p)); }
65
69
  /** Squared distance from rec to the nearest source of the last refresh, measured in units of each source's reach (≤ 1 = inside) */
@@ -119,13 +123,20 @@ export class Views {
119
123
  pull() {
120
124
  const W = this.w, S = W._s;
121
125
  for (const id of this.moving) {
122
- const rec = W.records.get(id), o = this.map.get(id).obj.position;
123
- if (S.sims.get(rec.kind)?.near && !S.isNear(id)) { o.copy(rec.position); continue; }
124
- const r = rec.position;
125
- if (r.x === o.x && r.y === o.y && r.z === o.z) continue; // the mover wrote it already (Character, npcSim), or it stood still: nothing to file again
126
- r.x = o.x; r.y = o.y; r.z = o.z; W._index(rec);
126
+ const rec = W.records.get(id), v = this.map.get(id), o = v.obj.position, r = rec.position, at = v.at;
127
+ // the record moved since the last pull (code wrote rec.position, which world.move would have placed at once): that write wins over the model. Far, the record rules anyway
128
+ if (S.recordRules(rec) || r.x !== at.x || r.y !== at.y || r.z !== at.z) { this.placed(rec); continue; }
129
+ if (r.x === o.x && r.y === o.y && r.z === o.z) continue; // stood still: nothing to file again
130
+ r.x = at.x = o.x; r.y = at.y = o.y; r.z = at.z = o.z; W._index(rec);
127
131
  }
128
132
  }
133
+ /** A write to the record of a model that moves itself: the model, and what solves it (a rigid body), go there. A write that agrees is the mover's own (Character, npcSim): only noted */
134
+ placed(rec) {
135
+ const v = this.moving.has(rec.id) && this.map.get(rec.id); if (!v) return;
136
+ const o = v.obj.position, r = rec.position;
137
+ if (r.x !== o.x || r.y !== o.y || r.z !== o.z) { this.w.engine._poses.place(v.obj, r); this.w._index(rec); } // indexed here too: a rec.position write reaches this from pull
138
+ v.at.x = r.x; v.at.y = r.y; v.at.z = r.z;
139
+ }
129
140
  /** Build models that should exist near any full-detail source (at most limit);
130
141
  * tear down those far from all of them, in another zone, or that show says no to */
131
142
  refresh(limit = Infinity) {
@@ -159,7 +170,7 @@ export class Views {
159
170
  if (!obj?.isObject3D) throw codedError('world-present', say(STRINGS.nullBuild, rec.kind, rec.id, String(obj)));
160
171
  if (this.map.get(rec.id) !== v) { this.drop(rec, p, obj); return; } // no longer wanted by the time it was built
161
172
  v.obj = obj; v.pending = false; this.byObj.set(obj, rec.id);
162
- if (p.positionFrom === 'view') this.moving.add(rec.id);
173
+ if (p.positionFrom === 'view') { this.moving.add(rec.id); v.at = { ...rec.position }; } // at: the record as pull last left it
163
174
  obj.position.copy(rec.position);
164
175
  if (!obj.parent) e.add(obj, { owner: 'world', id: rec.id }); // the registry knows it as the record (engine.thing / hit.thing)
165
176
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "threedog",
3
- "version": "0.8.0",
3
+ "version": "1.0.0",
4
4
  "description": "Web 3D game engine on three.js: core + optional modules, no built-in art (the picture comes from your own style), built to be driven by an AI",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -24,8 +24,14 @@
24
24
  "default": "./index.js"
25
25
  },
26
26
  "./error-hints": "./core/base/errorHints.js",
27
+ "./spelling": "./core/base/spelling.js",
28
+ "./metadata": "./core/inspect/metadata.generated.js",
27
29
  "./grid": "./core/scene/grid.js",
28
30
  "./layers": "./render/layers.js",
31
+ "./pixel": {
32
+ "types": "./types/pixel.d.ts",
33
+ "default": "./core/scene/pixel.js"
34
+ },
29
35
  "./worker": {
30
36
  "types": "./types/worker.d.ts",
31
37
  "default": "./core/threads/threadServe.js"
package/render/PostFX.js CHANGED
@@ -14,6 +14,7 @@ import { codedError } from '../core/base/errorHints.js';
14
14
  import { warnOnce } from '../core/base/validate.js';
15
15
  import { readParams, keysSchema } from '../core/base/params.js';
16
16
  import { isWebGPU, backendName, webgpuPart, ownMsaa } from './backend.js';
17
+ import { MSAA_KEY } from '../core/scene/tier.js';
17
18
  import { defineOwned } from '../core/ops/owned.js';
18
19
  import { watchOwnFrame } from './ownFrame.js';
19
20
  /** @import { Engine } from '../types/core' */
@@ -84,9 +85,10 @@ export class PostFX {
84
85
  * @param {{ antialias?: boolean }} [opts]
85
86
  * @internal
86
87
  */
87
- constructor(engine, { antialias = true } = {}) {
88
+ constructor(engine, { antialias = true, authored = antialias } = {}) {
88
89
  /** @internal */ this.engine = engine;
89
90
  /** @internal */ this._aa = antialias;
91
+ /** @internal the antialias this game starts with when the player chose nothing: what a settings row goes back to */ this.authoredAA = authored;
90
92
  /** @internal */ this._list = /** @type {any[]} */ ([]);
91
93
  // effect name -> its tie-break place in a slot, given the first time the name is added (or reserved by engine.plugins in plugin order).
92
94
  // Why kept across remove: plugins.off then on re-added the effect at the end, so A, B with no order of their own came back B, A (review 2026-11-03)
@@ -102,6 +104,7 @@ export class PostFX {
102
104
  /** @internal the chain's backend: postWebGL.js, or the WebGPU one threedog/tsl registers */ this._be = backendFor(engine.renderer);
103
105
  /** @internal the renderer's own MSAA on its canvas (fixed when it was made; the engine makes it with the default antialias) */ this._ownAA = ownMsaa(engine.renderer);
104
106
  this._be.init(this);
107
+ /** @internal the camera the built chain draws with */ this._camera = engine.camera;
105
108
  watchOwnFrame(engine); // a game that renders the canvas itself (own EffectComposer) takes the frame; the loop yields (ownFrame.js)
106
109
  // own(): the game takes the built chain (composer passes / pipeline.outputNode) and the engine stops rebuilding it; handing it
107
110
  // back rebuilds from the list. read is a constant: a direct write to object() is not a takeover (the next chain change replaces it)
@@ -111,21 +114,35 @@ export class PostFX {
111
114
  }
112
115
 
113
116
  /**
114
- * MSAA on. Writing it takes effect like setAntialias.
117
+ * MSAA on or off in the post chain's render targets, for what runs through the chain. It is a render setting, not a drawing part. With no effect on nothing runs through the chain:
118
+ * the canvas's own MSAA shows, fixed when the context was made (createEngine({ antialias })).
119
+ * @example engine.post.antialias = false;
115
120
  * @type {boolean}
116
121
  * @experimental
117
122
  */
118
123
  get antialias() { return this._aa; }
119
- set antialias(on) { this.setAntialias(on); }
124
+ set antialias(on) {
125
+ this._aa = !!on;
126
+ this._be.setAntialias(this, this._aa);
127
+ this._sync();
128
+ }
129
+ /**
130
+ * @internal A player's choice for the next launch. MSAA is fixed with the canvas, so a row that changed it live would have to switch the whole post chain on to do it, and the cheap
131
+ * preset cost more than the middle one. createEngine reads it before the renderer exists (core/scene/tier.js storedMsaa); the same value as the game's own is no choice to store.
132
+ * @param {boolean} on
133
+ */
134
+ nextAntialias(on) {
135
+ const key = this.engine.saves.storageKey(MSAA_KEY);
136
+ try { if (!!on === this.authoredAA) localStorage.removeItem(key); else localStorage.setItem(key, on ? '1' : '0'); } catch { /* storage blocked: the settings file has the row, this launch runs as it is */ }
137
+ }
120
138
  /**
121
- * Whether the post chain runs: an effect is on, or antialias differs from the canvas's own MSAA (fixed when the renderer was made, so a
122
- * runtime switch away from it goes through the chain's targets)
139
+ * Whether the post chain runs: an effect is on
123
140
  * @returns {boolean}
124
141
  */
125
- get active() { return this._aa !== this._ownAA || this._list.some(e => e.enabled); }
142
+ get active() { return this._list.some(e => e.enabled); }
126
143
 
127
144
  /**
128
- * What the chain runs in, for reading, or null while no post work has run yet (built the first time an effect or MSAA is on; it is not built here, so asking never costs a
145
+ * What the chain runs in, for reading, or null while no post work has run yet (built the first time an effect is on; it is not built here, so asking never costs a
129
146
  * render target). WebGLRenderer: the three.js EffectComposer (pass list, sizes, its targets). WebGPURenderer: { pipeline, scenePass }, three's RenderPipeline and the scene's pass() node. Read-only by rule, not by lock:
130
147
  * the engine owns it, rebuilds the chain whenever the list changes and disposes it with the engine. To add a pass use post.add,
131
148
  * to own the whole chain post.own() (recipe 52). Why public: a game reading the chain had to dig into an internal field (review 2026-11-03)
@@ -139,7 +156,7 @@ export class PostFX {
139
156
  * output; EffectComposer swaps them after every pass with needsSwap (most passes; the scene RenderPass does not). The last pass draws to the
140
157
  * canvas and still swaps, so after the frame (engine.onRender(fn, { when: 'after' })) neither target holds the final picture: writeBuffer holds
141
158
  * the input of that last pass (readBuffer when the last pass does not swap) and readBuffer is stale. For the final image, render into a target of your own.
142
- * Owned by the engine like object(): it resizes them, changes samples on setAntialias and adds a depth texture when an effect needs depth;
159
+ * Owned by the engine like object(): it resizes them, changes samples when antialias is written and adds a depth texture when an effect needs depth;
143
160
  * do not dispose them or swap their textures. A target of your own: new THREE.WebGLRenderTarget in onRender (THREE.md)
144
161
  * @returns {{ renderTarget1: any, renderTarget2: any, readBuffer: any, writeBuffer: any } | null}
145
162
  * @experimental
@@ -179,7 +196,8 @@ export class PostFX {
179
196
  if (effect.fuse && s === 'scene') throw codedError('post-effect', `post effect '${effect.name}': a fuse snippet colors an existing image, it cannot replace the scene render; use slot 'hdr' | 'ldr' | 'final'`);
180
197
  const other = s in EXCLUSIVE && this._list.find(e => e.slot === s);
181
198
  if (other) throw codedError('post-effect', `post slot '${s}' already holds '${other.name}'; remove it first (only one effect can ${EXCLUSIVE[s]})`);
182
- const post = this, point = this._point(effect);
199
+ const post = this, point = this.switchPoint(`post.${effect.name}.enabled`);
200
+ point.release('game'); point.base = effect.enabled ?? true; // only the game's own word starts over: the player's off and any other owner's hold stay on the effect that comes back
183
201
  let on = !!point.value();
184
202
  const h = {
185
203
  name: effect.name, slot: s, order: effect.order ?? 0, seq: this._place(effect.name),
@@ -211,7 +229,7 @@ export class PostFX {
211
229
  remove() {
212
230
  if (h._removed) return;
213
231
  h._removed = true;
214
- point.onChange = null; point.clear();
232
+ point.onChange = null; point.release('game');
215
233
  freeImpl(h);
216
234
  post._list = post._list.filter(e => e !== h);
217
235
  if (!post._kept.has(h.name)) post._seq.delete(h.name); // removed for good: a later effect of that name starts at the end (plugins keep theirs)
@@ -254,12 +272,13 @@ export class PostFX {
254
272
  const samples = this._be.samples(this);
255
273
  return { samples, replacedBy: this._aa && !samples ? this._list.find(e => e.enabled && e._def.needsBuffers?.includes('velocity'))?.name ?? null : null };
256
274
  }
257
- /** The shared point of an effect's switch, starting at what the effect says. Kept across a remove (the registry has no delete); a new effect of that name starts it clean @internal */
258
- _point(effect) {
259
- const S = this.engine.stacks, id = `post.${effect.name}.enabled`, base = effect.enabled ?? true;
260
- const p = S.has(id) ? S.get(id) : S.define(id, { kind: 'value', base, save: false });
261
- p.clear(); p.base = base;
262
- return p;
275
+ /**
276
+ * The shared point of an effect's switch ('post.<name>.enabled'), made on first asking. It outlives the effect (the registry has no delete) and may come before it: settings installs before
277
+ * the game's boot code adds its effects, and add() starts under whatever is held here. @param {string} id @internal
278
+ */
279
+ switchPoint(id) {
280
+ const S = this.engine.stacks;
281
+ return S.has(id) ? S.get(id) : S.define(id, { kind: 'value', base: true, save: false });
263
282
  }
264
283
  /**
265
284
  * An added effect's handle (as add() returns it), or undefined.
@@ -278,19 +297,6 @@ export class PostFX {
278
297
  * @experimental
279
298
  */
280
299
  own(on = true) { this._own.manual(!!on); }
281
- /**
282
- * Turn MSAA on or off. It is a render setting, not a drawing part. With no effect on, the start value is the canvas's own MSAA (free: no
283
- * post chain); the other value, and any effect, draws through the chain, whose render targets carry the MSAA.
284
- * @example engine.post.setAntialias(false);
285
- * @param {boolean} on
286
- * @returns {void}
287
- * @experimental
288
- */
289
- setAntialias(on) {
290
- this._aa = !!on;
291
- this._be.setAntialias(this, this._aa);
292
- this._sync();
293
- }
294
300
  /**
295
301
  * Effects in render order: [{ name, slot, order, enabled }]
296
302
  * @returns {{ name: string, slot: PostSlot, order: number, enabled: boolean }[]}
@@ -342,9 +348,21 @@ export class PostFX {
342
348
  * @param {number} dt @param {any} [target] @returns {void}
343
349
  */
344
350
  render(dt, target = null) {
351
+ this._followCamera();
345
352
  if (!this.active) { this._be.direct(this, target); return; }
346
353
  this._be.render(this, dt, target);
347
354
  }
355
+ /**
356
+ * @internal engine.camera was assigned. Passes take the camera when they are built, so the chain is built again from the list, as for a list change. A pass the game made
357
+ * is kept and moves to the new camera if it drew with the old one. While the game owns the chain it is the game's to change; the rebuild waits for the hand-back.
358
+ */
359
+ _followCamera() {
360
+ const now = this.engine.camera, old = this._camera;
361
+ if (now === old || !this._own.on) return;
362
+ this._camera = now;
363
+ for (const e of this._list) { if (e._def._pass?.camera === old) e._def._pass.camera = now; freeImpl(e); }
364
+ this._sync();
365
+ }
348
366
  /**
349
367
  * @internal start() replaced the renderer (fallback: 'webgl'): the chain and every effect's built part (bloom's node, its targets) belong to
350
368
  * the old backend. Dropping each _impl matters: the WebGL backend builds an effect only when it has none, so a WebGPU record left behind
package/render/backend.js CHANGED
@@ -402,7 +402,8 @@ export function rendererSwapped(engine) { for (const fn of [...(SWAP.get(engine)
402
402
  /**
403
403
  * Why this browser cannot give WebGPU, or null when it can. Asks the same two questions three's init() asks (an adapter, then a device),
404
404
  * because three answers "no" only with a console warning and a silent switch to its WebGL2 backend, and the reason is lost there.
405
- * The probe device is destroyed at once; three's init() requests its own.
405
+ * The probe device is destroyed at once; three's init() requests its own. A yes is kept per navigator.gpu, so only the page's first engine pays for a probe device;
406
+ * the adapter is still asked each time, it costs no device. If the GPU goes bad later, three's own fallback still lands and _startRenderer says so.
406
407
  * @returns {Promise<string | null>}
407
408
  */
408
409
  export async function whyNoWebGPU() {
@@ -411,9 +412,12 @@ export async function whyNoWebGPU() {
411
412
  let adapter;
412
413
  try { adapter = await gpu.requestAdapter({ featureLevel: 'compatibility' }); } catch (err) { return `requestAdapter() failed: ${err?.message ?? err}`; }
413
414
  if (!adapter) return 'requestAdapter() returned no adapter';
415
+ if (deviceFrom === gpu) return null;
414
416
  try { (await adapter.requestDevice()).destroy?.(); } catch (err) { return `requestDevice() failed: ${err?.message ?? err}`; }
417
+ deviceFrom = gpu;
415
418
  return null;
416
419
  }
420
+ let deviceFrom = null; // the navigator.gpu that gave a device (a page's stand-in for it is another object, so it is asked again)
417
421
 
418
422
  /** Each material on a scene object, once @param {any} scene @param {(m: any, o: any) => void} fn */
419
423
  function eachMaterial(scene, fn) {
@@ -18,11 +18,11 @@ import { Sprite, PointsNodeMaterial, LineBasicNodeMaterial, InstancedBufferAttri
18
18
  import { valueNode } from './uniforms.tsl.js';
19
19
  import { registerWebGPUPart } from '../backend.js';
20
20
 
21
- const { Fn, texture, instancedDynamicBufferAttribute, attribute, varying, positionGeometry, modelViewMatrix, screenDPR, uv,
21
+ const { Fn, texture, instancedDynamicBufferAttribute, attribute, varying, positionGeometry, modelViewMatrix, screenDPR, uv, viewportLinearDepth, cameraNear, cameraFar,
22
22
  float, vec2, vec3, vec4, select, min, max, cos, sin, mod, smoothstep, step, dot, length, If, Discard } = TSL;
23
23
 
24
24
  /** @template {string} T @typedef {import('three/webgpu').Node<T>} N */
25
- /** The particle uniforms as nodes @typedef {{ uScale: N<'float'>, uMaxPx: N<'float'>, uHasMap: N<'float'> }} ParticleNodes */
25
+ /** The particle uniforms as nodes @typedef {{ uScale: N<'float'>, uMaxPx: N<'float'>, uHasMap: N<'float'>, uSoft?: N<'float'> }} ParticleNodes */
26
26
  /**
27
27
  * The weather uniforms as nodes (modules/weather/particles.js; streaks have uWindDir / uLen, sprites uPx / uMaxPx / uSway / uSwayAmp / uUseMap).
28
28
  * Colors are typed vec3 (what they are in the shader): @types/three's 'color' node type lacks the vec3 operators.
@@ -69,23 +69,25 @@ function sprite(mat, count, attrs) {
69
69
  const pointCoord = () => vec2(uv().x, uv().y.oneMinus());
70
70
 
71
71
  /** Same as modules/particles/shaders.js, per particle from instanced attributes. Returns { material, object }; material.uniforms holds the { value } objects. */
72
- function particles({ attrs, count, fog, additive, maxPixels }) {
73
- const u = { uScale: { value: 400 }, uMaxPx: { value: maxPixels }, uHasMap: { value: 0 }, uMap: { value: null } };
72
+ function particles({ attrs, count, fog, additive, maxPixels, soft }) {
73
+ const u = { uScale: { value: 400 }, uMaxPx: { value: maxPixels }, uHasMap: { value: 0 }, uMap: { value: null }, ...(soft ? { uSoft: { value: soft } } : {}) };
74
74
  const m = new PointsNodeMaterial({ transparent: true, depthWrite: false, fog, sizeAttenuation: false, blending: additive ? AdditiveBlending : NormalBlending });
75
75
  /** @type {ParticleNodes} */ const U = nodesOf(u);
76
76
  const map = mapSlot(u, m);
77
77
  const pos = at(attrs.aPos, 'vec3'), size = at(attrs.aSize, 'float'), alpha = at(attrs.aAlpha, 'float');
78
78
  m.positionNode = pos;
79
+ const z = modelViewMatrix.mul(vec4(pos, 1)).z;
79
80
  m.sizeNode = Fn(() => {
80
- const z = modelViewMatrix.mul(vec4(pos, 1)).z;
81
81
  return select(alpha.lessThanEqual(0), float(0), min(size.mul(U.uScale).div(max(0.1, z.negate())), U.uMaxPx)).div(screenDPR);
82
82
  })();
83
+ // meters between the particle and what is drawn behind it; viewportLinearDepth is three's one copy of the depth buffer per render, shared by every effect that reads it
84
+ const gap = soft ? viewportLinearDepth.mul(cameraFar.sub(cameraNear)).add(cameraNear).add(varying(z)) : null;
83
85
  const vAlpha = varying(alpha), vAngle = varying(at(attrs.aAngle, 'float')), vColor = varying(at(attrs.aColor, 'vec3'));
84
86
  m.colorNode = Fn(() => {
85
87
  const p0 = pointCoord().sub(0.5), c = cos(vAngle), s = sin(vAngle);
86
88
  const p = vec2(c.mul(p0.x).sub(s.mul(p0.y)), s.mul(p0.x).add(c.mul(p0.y)));
87
89
  const tex = select(U.uHasMap.greaterThan(0.5), map.sample(p.add(0.5)), vec4(1, 1, 1, smoothstep(0.2, 0.5, length(p)).oneMinus())); // = GLSL smoothstep(0.5, 0.2, x): reversed edges are undefined in WGSL
88
- const a = tex.a.mul(vAlpha);
90
+ const a = soft ? tex.a.mul(vAlpha).mul(gap.div(U.uSoft).clamp()) : tex.a.mul(vAlpha);
89
91
  If(a.lessThan(0.01), () => { Discard(); });
90
92
  return vec4(vColor.mul(tex.rgb), a);
91
93
  })();
@@ -107,12 +107,12 @@ const webgpuPost = {
107
107
  for (const e of on) if (e._def.fuse ? typeof e._def.fuse.tsl !== 'function' : typeof e._def.node !== 'function') throw e._def.fuse ? glslOnly(e) : onlyCreate(e);
108
108
  // Same effects, same build, same samples: the graph is current (a set() of a number param never gets here)
109
109
  const key = `${samples}|${buffers}|${on.map(e => e.name).join(',')}`;
110
- if (post._pipe?.key === key) return;
110
+ if (post._pipe?.key === key && post._pipe.camera === camera) return;
111
111
  let P = post._pipe;
112
112
  if (!P) P = post._pipe = { pipeline: new RenderPipeline(renderer), scenePass: null, samples: -1, buffers: '', key: null, order: [] };
113
113
  P.key = null; // the graph is coming down: when a node() throws below, PostFX syncs the old list again, and that sync must rebuild, not find its key current
114
- if (P.samples !== samples || P.buffers !== `${buffers}`) {
115
- P.scenePass?.dispose(); P.scenePass = pass(scene, camera, { samples }); P.samples = samples; P.buffers = `${buffers}`;
114
+ if (P.samples !== samples || P.buffers !== `${buffers}` || P.camera !== camera) {
115
+ P.scenePass?.dispose(); P.scenePass = pass(scene, camera, { samples }); P.samples = samples; P.buffers = `${buffers}`; P.camera = camera;
116
116
  if (buffers.length) P.scenePass.setMRT(mrt({ output, ...Object.fromEntries(buffers.map(b => [b, BUFFERS[b]])) }));
117
117
  }
118
118
  // Every structural change rebuilds every effect's nodes: an effect's input is the node before it, which changed too
package/render/layers.js CHANGED
@@ -5,7 +5,7 @@ export const RESERVED_LAYERS = Object.freeze({
5
5
  lightVolumes: 26,
6
6
  /** occlusion culling's query boxes: only the view camera sees them, so voxel GI, probes and shadows never take them for geometry */
7
7
  occlusionBox: 27,
8
- /** what occlusion culling is not drawing now: on shadow cameras, voxel GI and engine.rays, never on the view camera */
8
+ /** nothing sits here: occlusion culling sets it on shadow cameras so three reads their own layers, not the view camera's, and what it hides still casts */
9
9
  occlusionHidden: 28,
10
10
  /** objects outline({ offLayer }) leaves without lines */
11
11
  outlineOff: 29,
@@ -39,6 +39,24 @@ function parse(buf) {
39
39
  return { meta, base };
40
40
  }
41
41
 
42
+ /** Unwrapped geometry -> { vertices: the source's count, place: source vertex -> a vertex holding it now, or -1 }. A second file's list speaks of the source, not of the layout the first file left */
43
+ const layouts = new WeakMap();
44
+
45
+ /** The source vertex list in terms of the geometry as it stands; null when a vertex the file names did not survive the earlier layout @param {any} g @param {Uint32Array} from */
46
+ function gatherList(g, from) {
47
+ const was = layouts.get(g);
48
+ if (!was) return from;
49
+ const list = from.map(v => was.place[v]); // Uint32Array: a -1 reads back as the maximum
50
+ return list.some(v => v >= g.attributes.position.count) ? null : list;
51
+ }
52
+
53
+ /** Remember where each source vertex went @param {any} g the new geometry @param {number} vertices the source's count @param {Uint32Array} from the file's list */
54
+ function noteLayout(g, vertices, from) {
55
+ const place = new Int32Array(vertices).fill(-1);
56
+ from.forEach((v, i) => { place[v] = i; });
57
+ layouts.set(g, { vertices, place });
58
+ }
59
+
42
60
  /** The mesh with the unwrapped layout: every attribute gathered through the source vertex list, the new index, and uv1 */
43
61
  function relayout(src, from, index, uv1) {
44
62
  const g = new THREE.BufferGeometry();
@@ -123,10 +141,12 @@ export const lightmapMethods = {
123
141
  for (const m of meta.meshes) {
124
142
  const mesh = names.get(m.name);
125
143
  // the vertex count is what the bake's list was made from: another count means another mesh, and its UVs would be noise
126
- if (!mesh || mesh.isInstancedMesh || mesh.geometry.attributes.position.count !== m.vertices) { set.missing.push(m.name); continue; }
127
- const at = binary + m.at, old = mesh.geometry;
128
- mesh.geometry = relayout(old, new Uint32Array(/** @type {ArrayBuffer} */ (buf), at, m.count), new Uint32Array(/** @type {ArrayBuffer} */ (buf), at + m.count * 4, m.indices),
144
+ if (!mesh || mesh.isInstancedMesh || (layouts.get(mesh.geometry)?.vertices ?? mesh.geometry.attributes.position.count) !== m.vertices) { set.missing.push(m.name); continue; }
145
+ const at = binary + m.at, old = mesh.geometry, from = new Uint32Array(/** @type {ArrayBuffer} */ (buf), at, m.count), list = gatherList(old, from);
146
+ if (!list) { set.missing.push(m.name); continue; }
147
+ mesh.geometry = relayout(old, list, new Uint32Array(/** @type {ArrayBuffer} */ (buf), at + m.count * 4, m.indices),
129
148
  new Float32Array(/** @type {ArrayBuffer} */ (buf), at + (m.count + m.indices) * 4, m.count * 2));
149
+ noteLayout(mesh.geometry, m.vertices, from);
130
150
  old.dispose(); // nothing else frees its GPU buffers; a mesh that shares it just uploads it again
131
151
  for (const x of mats(mesh)) { x.lightMap = tex; x.needsUpdate = true; }
132
152
  set._entries.set(mesh, m.matrix);
@@ -5,17 +5,24 @@
5
5
  // property, so the box wraps its draw in a WebGL2 query.
6
6
  // Results arrive frames late, so nothing may wait for them to appear:
7
7
  // - the box grows by the distance the camera covers in that delay, so it peeks out before the object does;
8
- // - a box that was not drawn (off screen) or a camera that jumped farther than the item's size means "show it": the frustum still culls it for free;
8
+ // - a box that was not drawn (off screen) or a camera that outran the box's growth or was swapped means "show it": the frustum still culls it for free;
9
+ // - answers asked before such a moment say nothing about the view after it, so they are thrown away, also those still on their way (DELAY frames);
9
10
  // - hiding takes HIDE_AFTER results in a row, showing takes one.
10
- // Hiding moves the meshes to HIDDEN_LAYER, not visible = false: visible stays the game's, shadow cameras keep that layer (a hidden thing still casts), engine.rays and voxelGI's volume enable it.
11
+ // A query measures one camera, so hiding holds for that camera alone. No layer mask can say so: three shows an object when any bit is shared, and a mesh hidden from the view camera
12
+ // would need every other camera (a minimap, a mirror, a probe, shadows, voxelGI's volume) to hold a bit the game never gave it. Both renderers ask object.layers.test(camera.layers), so a hidden
13
+ // mesh's Layers gets its own test that says no to the view camera's layers object and is three's test for any other. visible and the mask stay the game's; a Raycaster passes as any other camera.
11
14
  // The boxes are for the scene render alone: any other render of the same camera would draw them through its override material. The chains see to it: WebGL takes the layer off the camera
12
15
  // once the scene is drawn (_sceneDrawn), every display.pass on WebGPU renders without it.
13
16
  import * as THREE from 'three';
14
17
  import { isWebGPU, onRendererSwap } from './backend.js';
15
18
  import { codedError } from '../core/base/errorHints.js';
16
19
  import { engineOwned } from '../core/scene/things.js';
20
+ import { notePatch } from '../core/scene/threePatches.js';
17
21
  import { RESERVED_LAYERS } from './layers.js';
18
22
 
23
+ notePatch('occlusion-layers-test', "layers.test on the Layers of a mesh occlusion culling hides (own property, gone when it shows): false for engine.camera's layers, three's test for any other camera", null,
24
+ { scope: 'objects in the scene', lost: 'cannot be switched off alone: engine.occlusion.enabled = false takes it off every mesh' });
25
+
19
26
  const { occlusionHidden: HIDDEN_LAYER, occlusionBox: BOX_LAYER } = RESERVED_LAYERS;
20
27
  const HIDE_AFTER = 2;
21
28
  const DELAY = 3; // frames between a box being drawn and its result being read, at worst
@@ -36,6 +43,18 @@ export function unhideMask(now, bit, before) {
36
43
  return now & bit ? ((now & ~bit) | before) >>> 0 : now;
37
44
  }
38
45
 
46
+ const quiet = new WeakSet();
47
+ /** three starts this readback without keeping its promise, so a renderer disposed while one is on its way rejects with nobody to catch it, and the page reports an error for a game that did nothing wrong */
48
+ function quietReadback(renderer) {
49
+ const b = renderer.backend;
50
+ if (!b?.isWebGPUBackend || quiet.has(b)) return;
51
+ quiet.add(b);
52
+ notePatch('occlusion-readback', 'resolveOccludedAsync of the WebGPU backend, that one instance, once engine.occlusion is on: an AbortError from a buffer destroyed with the renderer is dropped', null,
53
+ { scope: 'the renderer in use', lost: 'disposing an engine while occlusion answers are on their way reports an unhandled rejection' });
54
+ const read = b.resolveOccludedAsync;
55
+ b.resolveOccludedAsync = function (c) { return read.call(this, c).catch(err => { if (err?.name !== 'AbortError') throw err; }); };
56
+ }
57
+
39
58
  const unitBox = new THREE.BoxGeometry(1, 1, 1);
40
59
  const size = new THREE.Vector3(), center = new THREE.Vector3(), here = new THREE.Vector3(), grown = new THREE.Box3();
41
60
  const trianglesOf = m => (m.geometry.index?.count ?? m.geometry.attributes.position.count) / 3 * (m.isInstancedMesh ? m.count : 1);
@@ -48,9 +67,14 @@ export class Occlusion {
48
67
  /** @internal */ this._items = new Set();
49
68
  /** @internal */ this._frameNo = 0;
50
69
  /** @internal */ this._last = /** @type {THREE.Vector3 | null} */ (null);
70
+ /** @internal the camera of the last frame */ this._cam = null;
51
71
  /** @internal */ this._root = null;
52
72
  /** @internal */ this._hook = null;
53
73
  /** @internal the layer bits this added to each shadow camera, taken back when culling goes off */ this._shadowBits = new Map();
74
+ const test = THREE.Layers.prototype.test;
75
+ /** @internal layers.test of a hidden mesh; `this` is its Layers @this {THREE.Layers} @param {THREE.Layers} layers */ this._unseen = function (layers) { return layers !== engine.camera.layers && test.call(this, layers); };
76
+ // a restored context holds none of the old queries: one still pending would never answer and its item would stay hidden. Each item starts over and shows until new answers say otherwise
77
+ /** @internal */ this._restored = engine.events.on('page:contextrestored', () => { for (const it of this._items) { it.query = null; it.pending = it.open = false; it.runs = 0; } });
54
78
  // fallback 'webgl' replaces the renderer inside start(), and each renderer needs its own query hook on the box
55
79
  /** @internal */ this._swap = onRendererSwap(engine, () => { if (this._on) for (const it of this._items) { this._unbox(it); this._box(it); } });
56
80
  }
@@ -89,7 +113,7 @@ export class Occlusion {
89
113
  */
90
114
  watch(meshes, box) {
91
115
  const read = typeof box === 'function' ? box : null;
92
- const it = { meshes, read, box: read ? null : box ?? null, masks: null, hidden: false, runs: 0, drawn: -1, proxy: null, query: null, pending: false, open: false };
116
+ const it = { meshes, read, box: read ? null : box ?? null, hidden: false, runs: 0, drawn: -1, wait: 0, pad: 0, proxy: null, query: null, pending: false, open: false };
93
117
  this._items.add(it);
94
118
  if (this._on) this._box(it);
95
119
  return { remove: () => { this._unbox(it); this._items.delete(it); } };
@@ -101,6 +125,7 @@ export class Occlusion {
101
125
  p.name = 'occlusion box'; p.layers.set(BOX_LAYER); p.renderOrder = Number.MAX_SAFE_INTEGER; p.matrixAutoUpdate = false; p.raycast = noRaycast;
102
126
  p.userData.batch = false;
103
127
  if (isWebGPU(this.engine.renderer)) {
128
+ quietReadback(this.engine.renderer);
104
129
  p.occlusionTest = true;
105
130
  p.onBeforeRender = (r, s, camera) => {
106
131
  if (camera !== this.engine.camera) return;
@@ -148,15 +173,17 @@ export class Occlusion {
148
173
  }
149
174
  _hide(it) {
150
175
  it.hidden = true;
151
- it.masks = it.meshes.map(m => m.layers.mask);
152
- for (const m of it.meshes) m.layers.set(HIDDEN_LAYER);
176
+ for (const m of it.meshes) m.layers.test = this._unseen;
153
177
  }
154
178
  _show(it) {
155
179
  if (!it.hidden) return;
156
- it.meshes.forEach((m, i) => { m.layers.mask = unhideMask(m.layers.mask, 1 << HIDDEN_LAYER, it.masks[i]); });
157
- it.hidden = false; it.masks = null;
180
+ for (const m of it.meshes) delete m.layers.test;
181
+ it.hidden = false;
158
182
  }
159
- /** Shadow cameras see HIDDEN_LAYER plus what the view camera sees, the boxes apart. A cascade's own lights hang off its shadow node, not the scene */
183
+ /**
184
+ * Shadow cameras see what the view camera sees, the boxes apart, plus HIDDEN_LAYER, which nothing sits on: a shadow camera with layer 0 alone is read through the view camera's layers
185
+ * by both renderers, and then the boxes would cast and WebGL would drop what is hidden. A cascade's own lights hang off its shadow node, not the scene
186
+ */
160
187
  _shadowCameras(cam) {
161
188
  const want = (cam.layers.mask & ~(1 << BOX_LAYER)) | (1 << HIDDEN_LAYER);
162
189
  // OR, never a plain write: a shadow camera can hold layers of its own (a first-person body on the camera's hide layer). Only what was added is noted, so off takes back no more
@@ -173,8 +200,8 @@ export class Occlusion {
173
200
  const cam = this.engine.camera, n = ++this._frameNo;
174
201
  cam.layers.enable(BOX_LAYER);
175
202
  cam.getWorldPosition(here);
176
- const moved = this._last ? here.distanceTo(this._last) : Infinity;
177
- (this._last ??= new THREE.Vector3()).copy(here);
203
+ const moved = this._last && cam === this._cam ? here.distanceTo(this._last) : Infinity;
204
+ (this._last ??= new THREE.Vector3()).copy(here); this._cam = cam;
178
205
  const gl = !isWebGPU(this.engine.renderer);
179
206
  let hidNow = false;
180
207
  for (const it of this._items) {
@@ -187,7 +214,11 @@ export class Occlusion {
187
214
  grown.copy(it.box).expandByScalar(pad);
188
215
  const inside = grown.distanceToPoint(here) <= cam.near * 2;
189
216
  const seenLast = n - it.drawn <= 1;
190
- const hide = seenLast && !inside && moved <= size.length() / 2 && it.runs >= HIDE_AFTER;
217
+ // an answer covers a camera move as far as the growth its box had when asked; a cut beyond that is a different view, however big the item is
218
+ if (moved * DELAY > it.pad) it.wait = n + DELAY;
219
+ it.pad = pad;
220
+ if (n <= it.wait || !seenLast) it.runs = 0;
221
+ const hide = seenLast && !inside && it.runs >= HIDE_AFTER;
191
222
  if (hide && !it.hidden) { this._hide(it); hidNow = true; } else if (!hide) this._show(it);
192
223
  grown.getSize(size);
193
224
  it.proxy.matrix.makeScale(size.x, size.y, size.z).setPosition(center);
@@ -196,5 +227,5 @@ export class Occlusion {
196
227
  if (hidNow || n % LIGHT_WALK === 0) this._shadowCameras(cam);
197
228
  }
198
229
  /** @internal */
199
- dispose() { this.enabled = false; this._swap.remove(); this._items.clear(); this._material?.dispose(); }
230
+ dispose() { this.enabled = false; this._swap.remove(); this._restored.remove(); this._items.clear(); this._material?.dispose(); }
200
231
  }
package/render/patches.js CHANGED
@@ -515,9 +515,9 @@ function shadowMaterial(material, kind) {
515
515
  () => { for (const [p, d] of before) { if (d) Object.defineProperty(THREE.Mesh.prototype, p, d); else delete THREE.Mesh.prototype[p]; } },
516
516
  { lost: 'meshes with wind or another vertex-moving patch cast a still shadow' });
517
517
  }
518
- notePatch('material-compile-accessor', "onBeforeCompile / customProgramCacheKey on each material the engine patches (what applyEffects was asked for, wind, fog): an own get / set, so the game's own hook assigned before or after still runs, then the engine's",
518
+ notePatch('material-compile-accessor', "onBeforeCompile / customProgramCacheKey on each material the engine patches (what applyEffects was asked for, wind, the game's own shader slots): an own get / set, so the game's own hook assigned before or after still runs, then the engine's",
519
519
  () => {}, // off: materials patched from now on get three's plain properties (patchMaterial asks patchOn)
520
- { scope: 'patched materials', lost: "on materials patched from now on, assigning material.onBeforeCompile replaces the engine's patches (wind, cloud shadow, fog) instead of running before them" });
520
+ { scope: 'patched materials', lost: "on materials patched from now on, assigning material.onBeforeCompile replaces the engine's patches (wind, cloud shadow) instead of running before them" });
521
521
  for (const [prop, kind] of [['customDepthMaterial', 'depth'], ['customDistanceMaterial', 'distance']]) {
522
522
  const own = Symbol.for('threedog.' + prop);
523
523
  Object.defineProperty(THREE.Mesh.prototype, prop, {
@@ -6,8 +6,8 @@
6
6
  //
7
7
  // MSAA: with no effect on, the canvas's own (the engine makes the context with the default antialias), and the scene renders straight to the
8
8
  // canvas with nothing allocated (direct: Color, clear-color and sRGB texture backgrounds are drawn tone-mapped there too, as the composer does).
9
- // With an effect on, or antialias switched away from the canvas's at runtime (a context's MSAA is fixed when it is made), it lives in the
10
- // composer's render targets, so it survives any effect and can be switched at runtime.
9
+ // With an effect on it lives in the composer's render targets, so it survives any effect and can be switched at runtime. Writing antialias with no effect
10
+ // on does not start the chain: a context's MSAA is fixed when it is made, and a chain run only to differ from it cost more than the picture was worth.
11
11
  // Why the state stays on the PostFX object (post.composer, post._fused ...): tests and post.object() read it there; splitting the file changed no behavior.
12
12
  import * as THREE from 'three';
13
13
  import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
@@ -133,6 +133,7 @@ export const webglPost = {
133
133
  post._scenePass = new RenderPass(scene, camera);
134
134
  post._output = new OutputPass();
135
135
  }
136
+ post._scenePass.camera = camera;
136
137
  const c = post.composer, on = post._sorted().filter(e => e.enabled);
137
138
  for (const e of on) if (!e._impl && !e._def.fuse) {
138
139
  if (typeof e._def.create !== 'function') throw codedError('post-effect', `post effect '${e.name}' has only node() (a TSL node, WebGPURenderer only) and this game chose WebGLRenderer: use createEngine({ renderer: 'webgpu' }), or give it create: (ctx) => pass (a three.js postprocessing Pass)`);
@@ -150,7 +151,7 @@ export const webglPost = {
150
151
  c.passes = named.map(e => e._impl);
151
152
  holdAfterScene(post, c.passes[0]);
152
153
  for (const p of c.passes) p.setSize(size.x, size.y);
153
- // nothing on and the canvas's own MSAA in use: the frame draws straight to the canvas, so the targets give their memory back (over 200 MB at 1080p with MSAA); three allocates them again on the next use
154
+ // nothing on: the frame draws straight to the canvas, so the targets give their memory back (over 200 MB at 1080p with MSAA); three allocates them again on the next use
154
155
  if (!post.active) for (const rt of [c.renderTarget1, c.renderTarget2]) rt.dispose();
155
156
  },
156
157
  dispose(post) {
package/render/probes.js CHANGED
@@ -35,6 +35,8 @@ const STRINGS = {
35
35
  noFloat: 'engine.bakeProbes(): this device cannot render to float textures (EXT_color_buffer_float), which three\'s WebGL bake needs. Bake on a desktop and ship the file: engine.loadProbes(json) works here',
36
36
  data: 'engine.loadProbes(json): {why}. Pass what handle.toJSON() returned (format \'' + FORMAT + '\', version ' + VERSION + '), or bake again',
37
37
  outside: '{n} lit object(s) reach outside the probe grid ({names}): the part outside gets no probe light and can go black. Widen bounds, or add light there. describe().render.probes lists them',
38
+ filled: 'engine.bakeProbes(): {n} probe(s) saw a pixel that is not a number (a shader dividing by zero or taking pow of a negative; first at {at}) and took the light of their nearest good neighbours. Fix that material, or leave it out with include',
39
+ noLight: 'engine.bakeProbes(): every probe saw a pixel that is not a number, so nothing usable was baked. A material in view writes NaN (a shader dividing by zero or taking pow of a negative): fix it, or leave it out with include',
38
40
  doubled: 'probe light is added on top of {what}, which the bake already saw, so that light counts twice. Lower it where the probes take over, or bake without it',
39
41
  };
40
42
  const sets = e => (e._probeSets ??= new Set());
@@ -124,6 +126,25 @@ function probeChecks(e) {
124
126
  return { outside, doubled };
125
127
  }
126
128
 
129
+ /**
130
+ * A game's shader can write NaN, and one such pixel in a probe's cube turns all of its numbers to NaN; three's sum cannot skip it: the light of that one pixel is lost, but what the probe stands in is known from its neighbours.
131
+ * So a broken probe takes the mean of the nearest good ones. Good ones only, so the result does not depend on the order. A file must hold finite numbers (readData refuses others).
132
+ * @param {{ sh: Float32Array, counts: number[], step: number[], origin: number[] }} d
133
+ */
134
+ function fillBroken(d) {
135
+ const [nx, ny, nz] = d.counts, n = nx * ny * nz, good = [], broken = [];
136
+ const at = i => [(i % nx) * d.step[0], (Math.floor(i / nx) % ny) * d.step[1], Math.floor(i / (nx * ny)) * d.step[2]];
137
+ for (let i = 0; i < n; i++) (d.sh.subarray(i * SH, (i + 1) * SH).every(Number.isFinite) ? good : broken).push(i);
138
+ if (!broken.length) return;
139
+ if (!good.length) throw codedError('probes-data', STRINGS.noLight);
140
+ for (const i of broken) {
141
+ const p = at(i), far = good.map(g => at(g).reduce((s, v, k) => s + (v - p[k]) ** 2, 0)), near = Math.min(...far), from = good.filter((_, k) => far[k] <= near * (1 + 1e-6));
142
+ for (let c = 0; c < SH; c++) d.sh[i * SH + c] = from.reduce((s, g) => s + d.sh[g * SH + c], 0) / from.length;
143
+ }
144
+ const first = at(broken[0]).map((v, k) => +(v + d.origin[k]).toFixed(2));
145
+ warnOnce(coded('probes-check', fmt(STRINGS.filled, { n: broken.length, at: first.join(', ') })));
146
+ }
147
+
127
148
  /** A probe set: grid data + the three.js grid in the scene that draws it. Made by bakeProbes / loadProbes only */
128
149
  class ProbeSet {
129
150
  constructor(e, data, { owner, source }) {
@@ -254,6 +275,9 @@ export const probeMethods = {
254
275
  if (!isWebGPU(r) && !r.extensions.has('EXT_color_buffer_float')) throw codedError('probes-option', STRINGS.noFloat);
255
276
  const t0 = performance.now(); // measure
256
277
  const grid = makeGrid(r, d);
278
+ // Off the round numbers meshes keep their vertices on, by less than light can show: a vertex exactly on a cube camera's plane leaves a software rasterizer no slopes, so a flat-shaded
279
+ // triangle there is NaN (plain three.js too; no real GPU tried shows it). This grid only bakes: the one in the scene is built from the data, unshifted.
280
+ grid.position.addScalar(1.3e-3);
257
281
  // hidden while the cubes render: meshes the filter rejects, and every other probe light (an earlier set lighting the capture would count twice)
258
282
  const hide = [];
259
283
  this.scene.traverse(x => { if (x.visible && (x.isLightProbe || x.isLightProbeGrid || (o.include && (x.isMesh || x.isPoints || x.isLine || x.isSprite) && !o.include(x)))) hide.push(x); });
@@ -267,6 +291,7 @@ export const probeMethods = {
267
291
  await new Promise(go => setTimeout(go));
268
292
  }
269
293
  d.sh = await readGrid(r, grid, d.counts);
294
+ fillBroken(d);
270
295
  } finally { grid.dispose(); }
271
296
  d.bakeMs = performance.now() - t0; // measure
272
297
  return addSet(this, d, { owner: o.owner, source: 'bake' });