threedog 0.0.0-stage → 0.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 (506) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +268 -0
  5. package/core/Assets.js +256 -0
  6. package/core/Audio.js +267 -0
  7. package/core/Baked.js +72 -0
  8. package/core/Batching.js +247 -0
  9. package/core/Budget.js +221 -0
  10. package/core/Clock.js +94 -0
  11. package/core/Commits.js +77 -0
  12. package/core/DebugOverrides.js +143 -0
  13. package/core/Describe.js +145 -0
  14. package/core/Engine.js +184 -0
  15. package/core/Events.js +153 -0
  16. package/core/I18n.js +94 -0
  17. package/core/Input.js +245 -0
  18. package/core/Inspect.js +77 -0
  19. package/core/InspectScene.js +191 -0
  20. package/core/Jobs.js +146 -0
  21. package/core/Loading.js +149 -0
  22. package/core/MaterialInfo.js +32 -0
  23. package/core/Ops.js +256 -0
  24. package/core/Random.js +52 -0
  25. package/core/Rays.js +160 -0
  26. package/core/SaveStore.js +85 -0
  27. package/core/Saves.js +254 -0
  28. package/core/Stream.js +279 -0
  29. package/core/Threads.js +158 -0
  30. package/core/UrlState.js +94 -0
  31. package/core/Vars.js +35 -0
  32. package/core/Views.js +49 -0
  33. package/core/actor.js +23 -0
  34. package/core/assetEntry.js +89 -0
  35. package/core/assetLoad.js +190 -0
  36. package/core/assetManifest.js +35 -0
  37. package/core/assetReport.js +83 -0
  38. package/core/audioRules.js +121 -0
  39. package/core/audioVoice.js +225 -0
  40. package/core/batchGroups.js +116 -0
  41. package/core/canvasBox.js +63 -0
  42. package/core/catalog.js +169 -0
  43. package/core/checks.js +67 -0
  44. package/core/claims.js +51 -0
  45. package/core/dayTime.js +15 -0
  46. package/core/debugView.js +76 -0
  47. package/core/describeRender.js +45 -0
  48. package/core/describeText.js +143 -0
  49. package/core/easing.js +34 -0
  50. package/core/errorCodes.js +205 -0
  51. package/core/errorHints.js +208 -0
  52. package/core/errors.js +40 -0
  53. package/core/events.generated.js +84 -0
  54. package/core/ground.js +102 -0
  55. package/core/holds.js +106 -0
  56. package/core/inputContext.js +69 -0
  57. package/core/inputDefaults.js +22 -0
  58. package/core/inputPad.js +35 -0
  59. package/core/inputPointer.js +48 -0
  60. package/core/inputTouch.js +48 -0
  61. package/core/lifecycle.js +69 -0
  62. package/core/lightWatch.js +56 -0
  63. package/core/look/coreParts.js +112 -0
  64. package/core/look/layers.js +136 -0
  65. package/core/look/part.js +173 -0
  66. package/core/look/report.js +79 -0
  67. package/core/look/write.js +86 -0
  68. package/core/loop.js +200 -0
  69. package/core/math.js +33 -0
  70. package/core/modules.js +196 -0
  71. package/core/movement.js +19 -0
  72. package/core/mulberry32.js +14 -0
  73. package/core/opsAtomic.js +31 -0
  74. package/core/opsCheck.js +97 -0
  75. package/core/opsFail.js +20 -0
  76. package/core/opsGuard.js +26 -0
  77. package/core/opsHistory.js +27 -0
  78. package/core/opsRun.js +77 -0
  79. package/core/page.js +78 -0
  80. package/core/params.js +132 -0
  81. package/core/pureWorker.js +5 -0
  82. package/core/renamed.js +21 -0
  83. package/core/saveApply.js +128 -0
  84. package/core/saveFiles.js +139 -0
  85. package/core/saveIds.js +53 -0
  86. package/core/saveVersions.js +97 -0
  87. package/core/scatter.js +92 -0
  88. package/core/sceneMethods.js +100 -0
  89. package/core/screenToGround.js +39 -0
  90. package/core/services.js +73 -0
  91. package/core/session.js +171 -0
  92. package/core/shadowTypes.js +15 -0
  93. package/core/skip.js +104 -0
  94. package/core/startup.js +135 -0
  95. package/core/streamCells.js +24 -0
  96. package/core/streamSources.js +73 -0
  97. package/core/styleParts.js +96 -0
  98. package/core/targeting.js +64 -0
  99. package/core/thingExplain.js +68 -0
  100. package/core/thingOps.js +168 -0
  101. package/core/things.js +212 -0
  102. package/core/threadPure.js +120 -0
  103. package/core/threadServe.js +25 -0
  104. package/core/tier.js +11 -0
  105. package/core/util.js +11 -0
  106. package/core/validate.js +204 -0
  107. package/docs/AI.md +123 -0
  108. package/docs/API.md +83 -0
  109. package/docs/CODEMAP.md +347 -0
  110. package/docs/COMMANDS.md +108 -0
  111. package/docs/CONVENTIONS.md +145 -0
  112. package/docs/PERF.md +217 -0
  113. package/docs/THREE.md +86 -0
  114. package/docs/api/ambience.md +15 -0
  115. package/docs/api/assets.md +62 -0
  116. package/docs/api/audio.md +53 -0
  117. package/docs/api/budget.md +40 -0
  118. package/docs/api/cameraRig.md +120 -0
  119. package/docs/api/characters.md +144 -0
  120. package/docs/api/clock.md +7 -0
  121. package/docs/api/collision.md +39 -0
  122. package/docs/api/content.md +64 -0
  123. package/docs/api/dialogue.md +39 -0
  124. package/docs/api/engine.md +199 -0
  125. package/docs/api/entities.md +61 -0
  126. package/docs/api/events.md +95 -0
  127. package/docs/api/flow.md +27 -0
  128. package/docs/api/grids.md +11 -0
  129. package/docs/api/ground.md +16 -0
  130. package/docs/api/hlod.md +34 -0
  131. package/docs/api/hud.md +31 -0
  132. package/docs/api/i18n.md +10 -0
  133. package/docs/api/input.md +24 -0
  134. package/docs/api/interactions.md +31 -0
  135. package/docs/api/inventory.md +66 -0
  136. package/docs/api/jobs.md +10 -0
  137. package/docs/api/level.md +41 -0
  138. package/docs/api/lightPool.md +56 -0
  139. package/docs/api/music.md +34 -0
  140. package/docs/api/nav.md +26 -0
  141. package/docs/api/net.md +14 -0
  142. package/docs/api/openWorld.md +24 -0
  143. package/docs/api/particles.md +41 -0
  144. package/docs/api/photo.md +15 -0
  145. package/docs/api/post.md +10 -0
  146. package/docs/api/quests.md +36 -0
  147. package/docs/api/rays.md +26 -0
  148. package/docs/api/rigid.md +84 -0
  149. package/docs/api/saves.md +32 -0
  150. package/docs/api/settings.md +36 -0
  151. package/docs/api/sky.md +58 -0
  152. package/docs/api/stream.md +31 -0
  153. package/docs/api/style.md +134 -0
  154. package/docs/api/terrain.md +34 -0
  155. package/docs/api/timeline.md +39 -0
  156. package/docs/api/tools.md +57 -0
  157. package/docs/api/triggers.md +56 -0
  158. package/docs/api/vars.md +9 -0
  159. package/docs/api/vegetation.md +52 -0
  160. package/docs/api/water.md +48 -0
  161. package/docs/api/weather.md +29 -0
  162. package/docs/api/world.md +30 -0
  163. package/docs/recipes/01-new-game.md +148 -0
  164. package/docs/recipes/02-npc.md +167 -0
  165. package/docs/recipes/03-items-pickups.md +158 -0
  166. package/docs/recipes/04-quests.md +83 -0
  167. package/docs/recipes/05-props-bake.md +159 -0
  168. package/docs/recipes/06-clock-events.md +117 -0
  169. package/docs/recipes/07-flow-scenes-pause.md +132 -0
  170. package/docs/recipes/08-weather-sky.md +74 -0
  171. package/docs/recipes/09-style-pack.md +234 -0
  172. package/docs/recipes/10-blender-level.md +67 -0
  173. package/docs/recipes/11-vehicles.md +55 -0
  174. package/docs/recipes/12-navmesh.md +79 -0
  175. package/docs/recipes/13-animation.md +149 -0
  176. package/docs/recipes/14-custom-module.md +91 -0
  177. package/docs/recipes/15-perf.md +78 -0
  178. package/docs/recipes/16-dev-bridge.md +180 -0
  179. package/docs/recipes/18-world.md +185 -0
  180. package/docs/recipes/19-shooting-picking.md +76 -0
  181. package/docs/recipes/20-content-actions-save.md +176 -0
  182. package/docs/recipes/21-camera.md +153 -0
  183. package/docs/recipes/22-shop-gold.md +107 -0
  184. package/docs/recipes/23-ops.md +175 -0
  185. package/docs/recipes/26-ui-parts.md +138 -0
  186. package/docs/recipes/27-net.md +96 -0
  187. package/docs/recipes/28-terrain.md +80 -0
  188. package/docs/recipes/29-grid.md +87 -0
  189. package/docs/recipes/30-templates.md +131 -0
  190. package/docs/recipes/31-audio.md +126 -0
  191. package/docs/recipes/32-action-game.md +33 -0
  192. package/docs/recipes/33-stream-sources.md +37 -0
  193. package/docs/recipes/34-environment-lighting.md +36 -0
  194. package/docs/recipes/35-style-from-reference.md +89 -0
  195. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  196. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  197. package/docs/recipes/38-environment-look-hooks.md +83 -0
  198. package/docs/recipes/40-scene.md +108 -0
  199. package/docs/recipes/41-thing-registry.md +93 -0
  200. package/docs/recipes/42-terrain-shape.md +64 -0
  201. package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
  202. package/docs/recipes/44-water-weather-look-hooks.md +135 -0
  203. package/docs/recipes/45-cascaded-shadows.md +51 -0
  204. package/docs/recipes/46-blender-art-route.md +114 -0
  205. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  206. package/docs/recipes/48-make-material.md +70 -0
  207. package/docs/recipes/49-game-module-contract.md +71 -0
  208. package/docs/recipes/50-own-renderer.md +12 -0
  209. package/docs/recipes/51-capability-catalog.md +63 -0
  210. package/docs/recipes/52-look.md +108 -0
  211. package/examples/action/DESIGN.md +3 -0
  212. package/examples/action/GAMEMAP.md +127 -0
  213. package/examples/action/content/actions.js +8 -0
  214. package/examples/action/content/audio.js +9 -0
  215. package/examples/action/content/index.js +10 -0
  216. package/examples/action/content/items.js +4 -0
  217. package/examples/action/content/places.js +4 -0
  218. package/examples/action/content/props.js +11 -0
  219. package/examples/action/content/templates.js +10 -0
  220. package/examples/action/content/views.js +6 -0
  221. package/examples/action/look.js +5 -0
  222. package/examples/action/main.js +137 -0
  223. package/examples/action/models.js +25 -0
  224. package/examples/sheepisland/GAMEMAP.md +107 -0
  225. package/examples/sheepisland/content/index.js +6 -0
  226. package/examples/sheepisland/content/props.js +19 -0
  227. package/examples/sheepisland/content/templates.js +5 -0
  228. package/examples/sheepisland/content/vegetation.js +8 -0
  229. package/examples/sheepisland/main.js +71 -0
  230. package/examples/sheepisland/params.js +25 -0
  231. package/examples/sheepisland/style/index.js +79 -0
  232. package/examples/sheepisland/style/models.js +59 -0
  233. package/examples/sheepisland/views.js +9 -0
  234. package/examples/styletest/GAMEMAP.md +135 -0
  235. package/examples/styletest/content/index.js +9 -0
  236. package/examples/styletest/content/items.js +8 -0
  237. package/examples/styletest/content/npcs.js +8 -0
  238. package/examples/styletest/content/places.js +5 -0
  239. package/examples/styletest/content/props.js +16 -0
  240. package/examples/styletest/content/templates.js +9 -0
  241. package/examples/styletest/content/vegetation.js +31 -0
  242. package/examples/styletest/look.js +11 -0
  243. package/examples/styletest/main.js +95 -0
  244. package/examples/styletest/models.js +87 -0
  245. package/examples/styletest/overrides.js +33 -0
  246. package/examples/styletest/panel.js +135 -0
  247. package/examples/styletest/params.js +32 -0
  248. package/examples/styletest/views.js +31 -0
  249. package/examples/world/DESIGN.md +5 -0
  250. package/examples/world/GAMEMAP.md +171 -0
  251. package/examples/world/content/actions.js +8 -0
  252. package/examples/world/content/audio.js +25 -0
  253. package/examples/world/content/bodies.js +12 -0
  254. package/examples/world/content/containers.js +4 -0
  255. package/examples/world/content/dialogues.js +33 -0
  256. package/examples/world/content/index.js +17 -0
  257. package/examples/world/content/items.js +10 -0
  258. package/examples/world/content/npcs.js +14 -0
  259. package/examples/world/content/pickups.js +11 -0
  260. package/examples/world/content/places.js +6 -0
  261. package/examples/world/content/props.js +12 -0
  262. package/examples/world/content/quests.js +15 -0
  263. package/examples/world/content/rules.js +23 -0
  264. package/examples/world/content/templates.js +5 -0
  265. package/examples/world/content/vegetation.js +32 -0
  266. package/examples/world/main.js +168 -0
  267. package/examples/world/models.js +28 -0
  268. package/index.d.ts +306 -0
  269. package/index.js +122 -0
  270. package/llms.txt +61 -0
  271. package/modules/ambience/Ambience.js +186 -0
  272. package/modules/camera/FirstPersonCamera.js +131 -0
  273. package/modules/camera/FixedCamera.js +162 -0
  274. package/modules/camera/FollowCamera.js +91 -0
  275. package/modules/camera/RtsCamera.js +132 -0
  276. package/modules/camera/common.js +182 -0
  277. package/modules/camera/index.js +11 -0
  278. package/modules/camera/projection.js +34 -0
  279. package/modules/characters/Character.js +235 -0
  280. package/modules/characters/NPC.js +242 -0
  281. package/modules/characters/assetModel.js +42 -0
  282. package/modules/characters/astar.js +66 -0
  283. package/modules/characters/behaviors.js +72 -0
  284. package/modules/characters/footsteps.js +13 -0
  285. package/modules/characters/index.js +215 -0
  286. package/modules/characters/moveHelpers.js +29 -0
  287. package/modules/characters/movers/common.js +62 -0
  288. package/modules/characters/movers/rapier.js +74 -0
  289. package/modules/characters/movers/simple.js +43 -0
  290. package/modules/characters/npcAvoid.js +129 -0
  291. package/modules/characters/npcSim.js +150 -0
  292. package/modules/characters/npcView.js +42 -0
  293. package/modules/characters/pathAsync.js +113 -0
  294. package/modules/characters/pathJob.js +62 -0
  295. package/modules/characters/pathWorker.js +7 -0
  296. package/modules/characters/playerStrings.js +12 -0
  297. package/modules/characters/proceduralRig.js +58 -0
  298. package/modules/characters/useModel.js +22 -0
  299. package/modules/characters/walkTo.js +58 -0
  300. package/modules/collision/Collision.js +274 -0
  301. package/modules/collision/grid.js +63 -0
  302. package/modules/content/explain.js +13 -0
  303. package/modules/content/ids.js +95 -0
  304. package/modules/content/index.js +154 -0
  305. package/modules/content/loader.js +190 -0
  306. package/modules/content/models.js +69 -0
  307. package/modules/content/packs.js +69 -0
  308. package/modules/content/props.js +89 -0
  309. package/modules/content/rules.js +134 -0
  310. package/modules/content/templates.js +189 -0
  311. package/modules/debug/DebugPanel.js +174 -0
  312. package/modules/entities/Entities.js +243 -0
  313. package/modules/entities/build.js +25 -0
  314. package/modules/entities/index.js +4 -0
  315. package/modules/flow/index.js +101 -0
  316. package/modules/gameplay/Container.js +227 -0
  317. package/modules/gameplay/Containers.js +89 -0
  318. package/modules/gameplay/Dialogue.js +219 -0
  319. package/modules/gameplay/Interactions.js +253 -0
  320. package/modules/gameplay/Inventory.js +224 -0
  321. package/modules/gameplay/Quests.js +205 -0
  322. package/modules/gameplay/boxOps.js +60 -0
  323. package/modules/gameplay/dialogueBox.js +48 -0
  324. package/modules/gameplay/interactionPrompt.js +28 -0
  325. package/modules/gameplay/inventoryOps.js +137 -0
  326. package/modules/gameplay/pickups.js +115 -0
  327. package/modules/gameplay/questLog.js +54 -0
  328. package/modules/gameplay/questSave.js +71 -0
  329. package/modules/grid/Grid.js +184 -0
  330. package/modules/grid/Layer.js +142 -0
  331. package/modules/grid/index.js +236 -0
  332. package/modules/grid/ops.js +73 -0
  333. package/modules/grid/preview.js +85 -0
  334. package/modules/grid/tiles.js +79 -0
  335. package/modules/hlod/index.js +167 -0
  336. package/modules/hud/index.js +167 -0
  337. package/modules/hud/parts.js +80 -0
  338. package/modules/level/geometry.js +46 -0
  339. package/modules/level/heightfield.js +160 -0
  340. package/modules/level/index.js +233 -0
  341. package/modules/level/nodes.js +84 -0
  342. package/modules/lights/index.js +227 -0
  343. package/modules/music/Music.js +294 -0
  344. package/modules/music/index.js +2 -0
  345. package/modules/music/rules.js +28 -0
  346. package/modules/nav/index.js +156 -0
  347. package/modules/nav/navPath.js +17 -0
  348. package/modules/net/Client.js +137 -0
  349. package/modules/net/Host.js +117 -0
  350. package/modules/net/Net.js +49 -0
  351. package/modules/net/index.js +77 -0
  352. package/modules/net/sync.js +114 -0
  353. package/modules/net/transports.js +118 -0
  354. package/modules/particles/Particles.js +179 -0
  355. package/modules/particles/effect.js +112 -0
  356. package/modules/particles/shaders.js +28 -0
  357. package/modules/photo/Photo.js +146 -0
  358. package/modules/rigid/RigidBodies.js +265 -0
  359. package/modules/rigid/Vehicles.js +97 -0
  360. package/modules/rigid/sync.js +158 -0
  361. package/modules/settings/Settings.js +297 -0
  362. package/modules/settings/apply.js +21 -0
  363. package/modules/settings/index.js +3 -0
  364. package/modules/settings/sections.js +156 -0
  365. package/modules/settings/strings.js +53 -0
  366. package/modules/settings/view.js +65 -0
  367. package/modules/sky/Sky.js +259 -0
  368. package/modules/sky/calendar.js +80 -0
  369. package/modules/sky/cascades.js +125 -0
  370. package/modules/sky/clouds.js +79 -0
  371. package/modules/sky/domeLayers.js +33 -0
  372. package/modules/sky/environment.js +141 -0
  373. package/modules/sky/fog.js +139 -0
  374. package/modules/sky/frame.js +77 -0
  375. package/modules/sky/layers.js +69 -0
  376. package/modules/sky/look.js +51 -0
  377. package/modules/sky/lookFog.js +80 -0
  378. package/modules/sky/lookShadow.js +50 -0
  379. package/modules/sky/lookSky.js +108 -0
  380. package/modules/sky/schedule.js +80 -0
  381. package/modules/sky/shader.js +96 -0
  382. package/modules/sky/shadow.js +74 -0
  383. package/modules/sky/skyModule.js +60 -0
  384. package/modules/terrain/ChunkManager.js +260 -0
  385. package/modules/terrain/chunkJob.js +19 -0
  386. package/modules/terrain/chunkLevels.js +40 -0
  387. package/modules/terrain/chunkQueries.js +42 -0
  388. package/modules/terrain/chunkWorker.js +5 -0
  389. package/modules/terrain/index.js +118 -0
  390. package/modules/terrain/lookGround.js +61 -0
  391. package/modules/terrain/mountTerrain.js +32 -0
  392. package/modules/terrain/terrainColorMap.js +41 -0
  393. package/modules/terrain/terrainDefaults.js +39 -0
  394. package/modules/terrain/terrainEdit.js +139 -0
  395. package/modules/terrain/terrainGen.js +155 -0
  396. package/modules/terrain/terrainIsland.js +131 -0
  397. package/modules/terrain/terrainMesh.js +92 -0
  398. package/modules/terrain/terrainShape.js +108 -0
  399. package/modules/terrain/terrainShapeMain.js +41 -0
  400. package/modules/terrain/terrainTexture.js +44 -0
  401. package/modules/timeline/Timeline.js +253 -0
  402. package/modules/timeline/Tween.js +114 -0
  403. package/modules/timeline/letterbox.js +24 -0
  404. package/modules/timeline/shots.js +90 -0
  405. package/modules/triggers/index.js +268 -0
  406. package/modules/vegetation/Vegetation.js +256 -0
  407. package/modules/vegetation/groundChunks.js +177 -0
  408. package/modules/vegetation/index.js +43 -0
  409. package/modules/vegetation/lookWind.js +37 -0
  410. package/modules/vegetation/modelGeometry.js +21 -0
  411. package/modules/water/Water.js +160 -0
  412. package/modules/water/look.js +80 -0
  413. package/modules/water/surface.js +88 -0
  414. package/modules/weather/Weather.js +242 -0
  415. package/modules/weather/look.js +75 -0
  416. package/modules/weather/particles.js +92 -0
  417. package/modules/weather/shaders.js +49 -0
  418. package/modules/weather/strings.js +15 -0
  419. package/modules/world/World.js +231 -0
  420. package/modules/world/cells.js +42 -0
  421. package/modules/world/explain.js +11 -0
  422. package/modules/world/index.js +71 -0
  423. package/modules/world/persist.js +107 -0
  424. package/modules/world/pos.js +20 -0
  425. package/modules/world/records.js +89 -0
  426. package/modules/world/sim.js +175 -0
  427. package/modules/world/simFar.js +82 -0
  428. package/modules/world/state.js +115 -0
  429. package/modules/world/thingSource.js +44 -0
  430. package/modules/world/views.js +182 -0
  431. package/package.json +66 -4
  432. package/presets.js +96 -0
  433. package/render/PostFX.js +240 -0
  434. package/render/detail.js +105 -0
  435. package/render/effects.js +144 -0
  436. package/render/engineUniforms.js +23 -0
  437. package/render/fuse.js +84 -0
  438. package/render/lighting.js +100 -0
  439. package/render/lights.js +18 -0
  440. package/render/lookSurface.js +161 -0
  441. package/render/materials.js +220 -0
  442. package/render/patches.js +252 -0
  443. package/render/postLook.js +86 -0
  444. package/render/surface.js +69 -0
  445. package/render/uniformDecl.js +29 -0
  446. package/types/common.d.ts +34 -0
  447. package/types/core.d.ts +1965 -0
  448. package/types/gameplay.d.ts +1822 -0
  449. package/types/generated/core/Audio.d.ts +200 -0
  450. package/types/generated/core/Batching.d.ts +47 -0
  451. package/types/generated/core/Budget.d.ts +90 -0
  452. package/types/generated/core/Commits.d.ts +31 -0
  453. package/types/generated/core/DebugOverrides.d.ts +52 -0
  454. package/types/generated/core/Events.d.ts +89 -0
  455. package/types/generated/core/I18n.d.ts +30 -0
  456. package/types/generated/core/Input.d.ts +118 -0
  457. package/types/generated/core/Jobs.d.ts +41 -0
  458. package/types/generated/core/Ops.d.ts +203 -0
  459. package/types/generated/core/Random.d.ts +49 -0
  460. package/types/generated/core/Rays.d.ts +49 -0
  461. package/types/generated/core/Saves.d.ts +162 -0
  462. package/types/generated/core/Stream.d.ts +93 -0
  463. package/types/generated/core/Threads.d.ts +82 -0
  464. package/types/generated/core/Views.d.ts +33 -0
  465. package/types/generated/core/audioVoice.d.ts +47 -0
  466. package/types/generated/core/page.d.ts +18 -0
  467. package/types/generated/core/session.d.ts +48 -0
  468. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  469. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  470. package/types/generated/modules/flow/index.d.ts +10 -0
  471. package/types/generated/modules/grid/Grid.d.ts +151 -0
  472. package/types/generated/modules/grid/Layer.d.ts +65 -0
  473. package/types/generated/modules/grid/index.d.ts +86 -0
  474. package/types/generated/modules/hlod/index.d.ts +11 -0
  475. package/types/generated/modules/hud/index.d.ts +10 -0
  476. package/types/generated/modules/lights/index.d.ts +13 -0
  477. package/types/generated/modules/music/Music.d.ts +111 -0
  478. package/types/generated/modules/net/Net.d.ts +34 -0
  479. package/types/generated/modules/net/index.d.ts +53 -0
  480. package/types/generated/modules/net/transports.d.ts +58 -0
  481. package/types/generated/modules/particles/Particles.d.ts +69 -0
  482. package/types/generated/modules/sky/Sky.d.ts +145 -0
  483. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  484. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  485. package/types/generated/modules/water/Water.d.ts +29 -0
  486. package/types/generated/modules/weather/Weather.d.ts +62 -0
  487. package/types/generated/modules/world/World.d.ts +242 -0
  488. package/types/generated/modules/world/index.d.ts +15 -0
  489. package/types/generated/render/PostFX.d.ts +125 -0
  490. package/types/generated/render/materials.d.ts +100 -0
  491. package/types/generated/render/patches.d.ts +41 -0
  492. package/types/generated/ui/Focus.d.ts +11 -0
  493. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  494. package/types/generated/ui/UI.d.ts +57 -0
  495. package/types/nav.d.ts +52 -0
  496. package/types/physics.d.ts +592 -0
  497. package/types/style.d.ts +638 -0
  498. package/types/worker.d.ts +11 -0
  499. package/types/world.d.ts +772 -0
  500. package/ui/Focus.js +51 -0
  501. package/ui/LoadingScreen.js +42 -0
  502. package/ui/Parts.js +199 -0
  503. package/ui/UI.js +167 -0
  504. package/ui/defaults.js +85 -0
  505. package/ui/theme.js +124 -0
  506. package/ui/touchPart.js +49 -0
package/core/params.js ADDED
@@ -0,0 +1,132 @@
1
+ // Param schemas: one plain-object description per field, shared by op args (ops.define args) and module params (readParams).
2
+ // Why one shape for both: the same schema validates the call, fills its defaults and is what engine.catalog() shows, so code,
3
+ // catalog and the dev bridge cannot disagree about a field (no second copy in docs or TypeScript).
4
+ // short form: 'int' / 'int?' (type, ? = optional)
5
+ // full form: { type: 'int', default: 1, min: 1, max: 99, values: [...], desc: 'how many', optional: true } (default implies optional)
6
+ import { closest, fmt, DEV, warnOnce, unknownOptionText } from './validate.js';
7
+ import { codedError, coded } from './errorHints.js';
8
+
9
+ /** Types an op arg may use: plain data only. Two meanings of 'id' on purpose: as a module param it is any string; as an op arg it must also be a world record id (checked in dev by opsCheck) */
10
+ export const OP_TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any'];
11
+ export const TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any', 'object', 'array', 'function'];
12
+ const SPEC_KEYS = ['type', 'default', 'min', 'max', 'values', 'desc', 'optional'];
13
+ const isPos = v => Array.isArray(v) && (v.length === 2 || v.length === 3) && v.every(Number.isFinite);
14
+ /** type name -> value check (op args use the first seven: plain data only) */
15
+ export const CHECK = {
16
+ string: v => typeof v === 'string', number: v => Number.isFinite(v), int: v => Number.isInteger(v), bool: v => typeof v === 'boolean',
17
+ position: isPos, id: v => typeof v === 'string', any: () => true, object: v => !!v && typeof v === 'object' && !Array.isArray(v),
18
+ array: Array.isArray, function: v => typeof v === 'function',
19
+ };
20
+ const STRINGS = {
21
+ badType: "{where}: {key} has type '{type}'; use one of {list} (add ? for optional, e.g. 'int?', or { type: 'int', default: 1 })",
22
+ badSpec: '{where}: {key} has unknown schema field {field}{hint}; schema fields: ' + SPEC_KEYS.join(', '),
23
+ badDefault: '{where}: the default of {key} ({got}) does not fit its own schema: {why}',
24
+ wrong: '{where}: {key} {why}',
25
+ };
26
+
27
+ /** Parse one field spec ('int?' or { type, default, ... }) into { type, optional, default?, min?, max?, values?, desc? }; throws on a bad spec */
28
+ export function parseSpec(where, key, spec, err = codedError.bind(null, 'engine-misuse')) {
29
+ const s = typeof spec === 'string' ? { type: spec.replace(/\?$/, ''), optional: spec.endsWith('?') } : { ...spec };
30
+ if (typeof spec !== 'string') {
31
+ for (const f of Object.keys(s)) if (!SPEC_KEYS.includes(f)) {
32
+ const c = closest(f, SPEC_KEYS);
33
+ throw err(fmt(STRINGS.badSpec, { where, key, field: f, hint: c ? ` (did you mean ${c}?)` : '' }));
34
+ }
35
+ s.optional = !!s.optional || 'default' in s;
36
+ }
37
+ if (!TYPES.includes(s.type)) throw err(fmt(STRINGS.badType, { where, key, type: String(s.type ?? spec), list: TYPES.join(' ') }));
38
+ if ('default' in s) { const why = whyBad(s, s.default); if (why) throw err(fmt(STRINGS.badDefault, { where, key, got: JSON.stringify(s.default), why })); }
39
+ return s;
40
+ }
41
+
42
+ /** Parse a whole schema ({ key: spec }) -> { key: parsed } (null when there is none) */
43
+ export function parseSchema(where, schema, err) {
44
+ if (!schema) return null;
45
+ const out = {};
46
+ for (const key in schema) out[key] = parseSpec(where, key, schema[key], err);
47
+ return out;
48
+ }
49
+
50
+ /** Why v does not fit the parsed spec s (type, range, allowed values), or null when it does */
51
+ export function whyBad(s, v) {
52
+ if (!CHECK[s.type](v)) return `should be ${s.type === 'position' ? '[x, y, z]' : s.type}, got ${JSON.stringify(v) ?? typeof v}`;
53
+ if (s.min != null && v < s.min) return `must be >= ${s.min}, got ${v}`;
54
+ if (s.max != null && v > s.max) return `must be <= ${s.max}, got ${v}`;
55
+ if (s.values && !s.values.includes(v)) return `must be one of ${s.values.map(x => JSON.stringify(x)).join(', ')}, got ${JSON.stringify(v)}`;
56
+ return null;
57
+ }
58
+
59
+ /** { key: default } of the fields that declare one, or null when none do (so callers skip the copy) */
60
+ export function defaultsOf(shape) {
61
+ let out = null;
62
+ for (const key in shape || {}) if ('default' in shape[key]) (out ??= {})[key] = shape[key].default;
63
+ return out;
64
+ }
65
+
66
+ /** args with the missing fields filled from defaults (a new object; args itself may be frozen) */
67
+ export function withDefaults(defaults, args) {
68
+ if (!defaults) return args;
69
+ const out = { ...args };
70
+ for (const k in defaults) if (out[k] === undefined) out[k] = defaults[k];
71
+ return out;
72
+ }
73
+
74
+ /** Shape as plain data for engine.catalog() and the dev bridge: functions and undefined fields left out */
75
+ export function schemaInfo(shape) {
76
+ if (!shape) return null;
77
+ const out = {};
78
+ for (const key in shape) {
79
+ const s = shape[key], o = { type: s.type };
80
+ if (s.optional) o.optional = true;
81
+ for (const f of ['default', 'min', 'max', 'values', 'desc']) if (s[f] !== undefined && typeof s[f] !== 'function') o[f] = s[f];
82
+ out[key] = o;
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * Module options read through a params schema: unknown keys and wrong types throw (with the fix), defaults are filled in.
89
+ * Put the schema on the module definition too (`params`, `options`), so engine.catalog(name) shows every option, its default and the value in use.
90
+ * @param {string} where who reads them, for the error text (the module name)
91
+ * @param {Record<string, string | { type: string, default?: any, min?: number, max?: number, values?: any[], desc?: string, optional?: boolean }>} schema
92
+ * @param {object} [opts] what the game passed
93
+ * @returns {object} opts with defaults filled in
94
+ * @example
95
+ * const PARAMS = { radius: { type: 'number', default: 2, min: 0, desc: 'pickup reach in m' }, sound: 'string?' };
96
+ * export const magnet = (opts) => {
97
+ * const o = readParams('magnet', PARAMS, opts);
98
+ * return { name: 'magnet', params: PARAMS, options: o, install(e) { return { radius: o.radius }; } };
99
+ * };
100
+ */
101
+ export function readParams(where, schema, opts = {}) {
102
+ const shape = parseSchema(where, schema), err = msg => codedError('module-params', msg);
103
+ const out = withDefaults(defaultsOf(shape), opts ?? {}); // checked in every build: it runs once per factory call, and a wrong option is a bug anywhere
104
+ const keys = Object.keys(shape);
105
+ for (const key of Object.keys(out)) if (!shape[key]) {
106
+ const msg = unknownOptionText(where, key, keys); // one rule with checkOptions (validate.js)
107
+ if (DEV) throw err(msg); // an option typo: dev throws, a release build warns once and ignores it (decision 2026-11-01), so a shipped game never dies on a typo
108
+ warnOnce(coded('module-params', msg));
109
+ }
110
+ for (const key of keys) {
111
+ const v = out[key];
112
+ if (v === undefined) { if (!shape[key].optional) throw err(fmt(STRINGS.wrong, { where, key, why: 'is required' })); continue; }
113
+ const why = whyBad(shape[key], v);
114
+ if (why) throw err(fmt(STRINGS.wrong, { where, key, why }));
115
+ }
116
+ return out;
117
+ }
118
+
119
+ /**
120
+ * Schema for a module whose options are a key list (and maybe a defaults object): every key is `any` (nothing about the value is checked
121
+ * beyond the spelling of the key), and a key present in `defaults` shows that default in engine.catalog(). Why `any`: these modules' options
122
+ * accept several shapes (number | [x, z], preset name | object), and their own code already checks the values; the schema is for the key
123
+ * list, the catalog and R06. Pass `specs` ({ key: 'int?' | { type, ... } }) to give a key a real type; it wins over the generic one.
124
+ * @param {string[]} keys
125
+ * @param {Record<string, any>} [defaults] defaults shown in the catalog (not applied: the module's own code still does that)
126
+ * @param {Record<string, any>} [specs]
127
+ */
128
+ export function keysSchema(keys, defaults = {}, specs = {}) {
129
+ const out = {};
130
+ for (const k of keys) out[k] = specs[k] ?? (defaults[k] !== undefined ? { type: 'any', default: defaults[k] } : 'any?');
131
+ return out;
132
+ }
@@ -0,0 +1,5 @@
1
+ // Worker that runs pure-function batches for engine.threads (world far simulation with worker: true). Same handler as the main-thread fallback.
2
+ import { serve } from './threadServe.js';
3
+ import { pureHandler } from './threadPure.js';
4
+
5
+ serve(pureHandler());
@@ -0,0 +1,21 @@
1
+ // The ONE list of names renamed in 0.2: plain data with no imports (errorHints.js re-exports it for the stubs; rule R39 reads it through 'threedog/error-hints').
2
+ /**
3
+ * The ONE list of names renamed in 0.2 (recipes/52-look.md "Renamed in 0.2"): key -> { old call, new call, find = a regex source that spots a
4
+ * use of the old name in source text }. The throwing stubs read `old` / `now` through renamed(key); rule R39 reads `find` to keep the old names out of the repo.
5
+ * `find: null` = no safe text pattern (the old name is a field name shared with unrelated objects).
6
+ * @type {Record<string, { old: string, now: string, find: string | null }>}
7
+ */
8
+ export const RENAMED = {
9
+ setExposure: { old: 'engine.setExposure(v)', now: 'engine.look.tone.set({ exposure: v })', find: '\\bsetExposure\\b' },
10
+ setToneMapping: { old: 'engine.setToneMapping(kind)', now: "engine.look.tone.set({ mapping: 'aces' })", find: '\\bsetToneMapping\\b' },
11
+ setEnvironment: { old: 'engine.sky.setEnvironment(o)', now: "engine.look.env.replace('sky') then engine.look.env.set({ intensity, rotation }); engine.look.env.replace(false) turns it off", find: '\\bsetEnvironment\\b' },
12
+ setShadow: { old: 'engine.sky.setShadow(o)', now: 'engine.look.shadow.set(o)', find: '\\bsetShadow\\b' },
13
+ weatherDefine: { old: 'engine.weather.define(field, spec)', now: 'engine.look.weather.replace({ [field]: spec })', find: '\\bweather\\??\\.define\\b' },
14
+ postAdd: { old: 'engine.post.add(effect)', now: 'engine.look.post.add(effect, { owner }) for one pass (returns { remove() }), patch(name, { glsl }) for a color effect, or replace([...effects]) for the whole chain', find: '(?<!look\\.)\\bpost\\??\\.add\\b' },
15
+ postEnable: { old: 'engine.post.enable(name, on)', now: "engine.look.post.set({ 'bloom.enabled': on }); MSAA: engine.post.setAntialias(on)", find: '\\bpost\\??\\.enable\\b' },
16
+ postHandle: { old: 'engine.post.get(name).set / .enable / .remove', now: "engine.look.post.set({ 'bloom.strength': 0.6 }); read with engine.post.get(name)", find: '\\bpost\\??\\.get\\([^)]*\\)\\??\\.(set|enable|remove)\\b' },
17
+ lookClouds: { old: 'engine.look.clouds', now: 'engine.look.cloudShadow', find: '\\blook\\.clouds\\b' },
18
+ cameraOverride: { old: 'engine.cameraOverride = {...}', now: "const cam = engine.takeCamera('owner', { focus }); cam.remove() releases it", find: '\\bcameraOverride\\s*=(?!=)' },
19
+ viewsPos: { old: "views.define(name, { pos })", now: 'views.define(name, { position: [x, y, z] })', find: null },
20
+ reason: { old: 'result.reason (ops.run / can / undo failures), ops.recent() / catalog(op).last / net:result .reason', now: 'result.code (the same name in history, catalog and net:result)', find: null },
21
+ };
@@ -0,0 +1,128 @@
1
+ // Applying a save (split out of Saves.js): every part is checked and migrated before anything changes (saveVersions.js), then loaded in order;
2
+ // if any part's load throws, every part reloads the state from just before the load (rollback), so a game is never left half-loaded.
3
+ import { toast } from '../ui/UI.js';
4
+ import { fmt } from './validate.js';
5
+ import { reportError } from './errors.js';
6
+ import { codedError, coded } from './errorHints.js';
7
+ import { FORMAT, readSave, parseSave, upgradePart } from './saveVersions.js';
8
+
9
+ const DEV_STRINGS = {
10
+ loadThrew: "load() of save part '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
11
+ partAt: "load() of save part '{k}'", adoptAt: "load() of save part '{k}' (registered after the save was loaded)",
12
+ rollback: "rollback of save part '{k}' after a failed load (that part may be half-loaded; the other parts rolled back)",
13
+ };
14
+
15
+ /** A save part's load threw: the error named after the part (thrown on, so the caller can roll back) */
16
+ const loadError = (k, err, slot) => Object.assign(codedError('save-load-threw', fmt(DEV_STRINGS.loadThrew, { k, slot, msg: err?.message ?? String(err) })), { part: k, cause: err });
17
+
18
+ /**
19
+ * Implementation of saves.apply (see its JSDoc): checked first, applied part by part, rolled back to the pre-load state if any part throws.
20
+ * @param {any} s the Saves instance
21
+ * @param {any} data
22
+ * @param {string} slot
23
+ * @returns {Promise<boolean>}
24
+ * @internal
25
+ */
26
+ export function applySave(s, data, slot) {
27
+ const r = readSave(data, s.providers, slot);
28
+ if ('reason' in r) {
29
+ if (r.reason !== 'missing') { console.warn(coded('save-refused', r.dev)); // handled: the player is told, nothing changed
30
+ toast(s.engine, s.engine.t('saves.' + r.reason), { kind: 'error', ms: 5000 }); }
31
+ return Promise.resolve(false);
32
+ }
33
+ const e = s.engine, before = s._collect().data, foreign0 = s._foreign; // the rollback point
34
+ e.commits.invalidate(); e.ops._mark('(load)'); // old background results die with the old world; the op log shows where the load cut in
35
+ s._foreign = r.foreign;
36
+ const fail = err => {
37
+ reportError(e, err, err?.part ? fmt(DEV_STRINGS.partAt, { k: err.part }) : `saves.apply('${slot}')`);
38
+ s._foreign = foreign0;
39
+ const back = readSave(before, s.providers, '(rollback)');
40
+ // every part reloads its pre-load state; a part that throws again is reported (once) and the rest still roll back
41
+ const onPart = er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }), { soft: true });
42
+ return Promise.resolve('list' in back ? e.ops.allow(() => runParts(back.list, '(rollback)', onPart)) : null).then(() => false);
43
+ };
44
+ let out;
45
+ try { out = e.ops.allow(() => runParts(r.list, slot)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
46
+ return Promise.resolve(out).then(() => true, fail);
47
+ }
48
+
49
+ /**
50
+ * Load parts in order; a part returning a Promise makes the rest wait for it. A failing part throws (or rejects) with the part named,
51
+ * unless onFail is given (rollback): then onFail(err) is called and the next part loads anyway.
52
+ */
53
+ function runParts(list, slot, onFail = null) {
54
+ const failed = (k, err) => { const er = loadError(k, err, slot); if (!onFail) throw er; onFail(er); };
55
+ const step = i => {
56
+ for (; i < list.length; i++) {
57
+ const [k, p, d] = list[i];
58
+ let r;
59
+ try { r = p.load(d); } catch (err) { failed(k, err); continue; }
60
+ if (r && typeof r.then === 'function') return r.then(() => step(i + 1), err => { failed(k, err); return step(i + 1); });
61
+ }
62
+ return true;
63
+ };
64
+ return step(0);
65
+ }
66
+
67
+ /**
68
+ * A part registered after a save was loaded (a module installed later): hand it its data from that save now.
69
+ * @param {any} s the Saves instance
70
+ * @param {string} key
71
+ * @internal
72
+ */
73
+ export function adoptPart(s, key) {
74
+ const p = s.providers.get(key), d = s._foreign.parts[key], v = s._foreign.versions[key] ?? 1;
75
+ delete s._foreign.parts[key]; delete s._foreign.versions[key];
76
+ const where = fmt(DEV_STRINGS.adoptAt, { k: key });
77
+ try {
78
+ if (v > p.version) throw codedError('save-refused', `save part '${key}' is version ${v}, this build reads up to ${p.version}`);
79
+ const r = s.engine.ops.allow(() => p.load(upgradePart(key, p, d, v, s._foreign.whole)));
80
+ if (r && typeof r.then === 'function') r.catch(err => reportError(s.engine, err, where));
81
+ } catch (err) { reportError(s.engine, err, where); }
82
+ }
83
+
84
+
85
+ /**
86
+ * Load a slot; with base (a collect() result) the save goes on top of it, so a part missing from the save gets base's state (session.load).
87
+ * @param {any} s the Saves instance
88
+ * @param {string} slot
89
+ * @param {any} [base]
90
+ * @returns {Promise<boolean>}
91
+ * @internal
92
+ */
93
+ export function loadSlot(s, slot, base) {
94
+ let data = s._json.get(slot);
95
+ if (base && data != null) {
96
+ try {
97
+ const sv = parseSave(data);
98
+ if (sv?.parts && typeof sv.parts === 'object' && !Array.isArray(sv.parts)) {
99
+ const own = Object.fromEntries(Object.keys(sv.parts).map(k => [k, sv.versions?.[k] ?? 1])); // a part without a version is version 1, not base's
100
+ data = { ...sv, parts: { ...base.parts, ...sv.parts }, versions: { ...base.versions, ...own } };
101
+ }
102
+ } catch { /* unreadable: apply refuses the text itself with the reason */ }
103
+ }
104
+ return s.apply(data, slot).then(ok => { // apply already ran the modules' afterLoad hooks
105
+ if (ok) s.engine.events.emit('save:loaded', slot);
106
+ return ok;
107
+ });
108
+ }
109
+
110
+ /** Modules with an afterLoad hook rebuild what the loaded state needs nearby (models and the colliders their build adds); gameplay waits frozen
111
+ * until every one resolves, so the first step after `await saves.load()` never runs on missing ground or walls.
112
+ * Saves.apply runs it (not only saves.load): session.newGame() / quit() apply the base data the same way and need the same rebuild */
113
+ export async function afterLoad(e) {
114
+ const hooks = [...e.modules.values()].filter(m => m.afterLoad);
115
+ if (!hooks.length) return;
116
+ e.freeze('threedog:load'); // a namespaced owner: a game's own freeze('load') must not be released by (or release) the engine's
117
+ try { await Promise.all(hooks.map(m => m.afterLoad(e))); } finally { e.unfreeze('threedog:load'); }
118
+ }
119
+
120
+ /** Collect every part: { data, failed: [[key, error]] }. Parts of the loaded save that no module owns are carried along. */
121
+ export function collectParts(s) {
122
+ const f = s._foreign, failed = [];
123
+ const data = { format: FORMAT, savedAt: Date.now(), versions: { ...f.versions }, parts: { ...f.parts } }; // wall-clock: real time of the save
124
+ for (const [k, p] of s.providers) {
125
+ try { data.parts[k] = p.save(); data.versions[k] = p.version; } catch (e) { failed.push([k, e]); delete data.parts[k]; delete data.versions[k]; }
126
+ }
127
+ return { data, failed };
128
+ }
@@ -0,0 +1,139 @@
1
+ // Save files (.json download / restore), split out of Saves.js: the world save plus every binary attachment, for backups that survive wiped browser data.
2
+ // File shape: { threedog: 'save', format: FILE_FORMAT, game, slot, savedAt, data: <the save envelope>, files: [{ group, id, at, meta, type, url: 'data:...' }] }.
3
+ // Import is offline: attachments must be data: URLs and are decoded in place, never fetched.
4
+ import { toast } from '../ui/UI.js';
5
+ import { coded } from './errorHints.js';
6
+ import { fmt } from './validate.js';
7
+ import { readSave, parseSave } from './saveVersions.js';
8
+
9
+ /** Version of the export file wrapper (the save inside carries its own format) */
10
+ const FILE_FORMAT = 1;
11
+ /** Player-facing save messages (registered by Saves) */
12
+ export const SAVE_STRINGS = {
13
+ 'zh-CN': { 'saves.failed': '存档失败:{why}(之前的存档还在)', 'saves.badFile': '这不是有效的存档文件', 'saves.imported': '存档已导入到「{slot}」', 'saves.noSlot': '没有可导出的存档',
14
+ 'saves.tooNew': '这个存档来自更新版本的游戏,无法读取(存档没有改动)', 'saves.corrupt': '这个存档已损坏,无法读取(存档没有改动)',
15
+ 'saves.migrate': '这个存档的版本无法升级,无法读取(存档没有改动)' },
16
+ en: { 'saves.failed': 'Save failed: {why} (the previous save is kept)', 'saves.badFile': 'This is not a valid save file',
17
+ 'saves.imported': 'Save imported into "{slot}"', 'saves.noSlot': 'Nothing to export',
18
+ 'saves.tooNew': 'This save is from a newer version of the game and cannot be loaded (the save is unchanged)',
19
+ 'saves.corrupt': 'This save is damaged and cannot be loaded (the save is unchanged)',
20
+ 'saves.migrate': 'This save\'s version cannot be upgraded, so it cannot be loaded (the save is unchanged)' },
21
+ };
22
+ const MAX_BYTES = 512 * 1024 * 1024; // a bigger "save" is not one of ours; reading it would stall the tab
23
+ const STRINGS = {
24
+ badText: '[saves] import(text): not a save ({why}); nothing was imported',
25
+ bad: '[saves] importFile: not a save file ({why}); nothing was imported',
26
+ attachment: '[saves] importFile: attachment {i} is not a data: URL with a string group and id; nothing was imported',
27
+ };
28
+
29
+ /** Blob -> data: URL (attachments are stored as text in the export file) */
30
+ const toDataURL = blob => new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = () => rej(r.error); r.readAsDataURL(blob); });
31
+
32
+ /** data: URL -> Blob without the network; null when it is not a data: URL */
33
+ function dataUrlBlob(url, type) {
34
+ const m = typeof url === 'string' && /^data:([^,]*?)(;base64)?,(.*)$/s.exec(url);
35
+ if (!m) return null;
36
+ const bytes = m[2] ? Uint8Array.from(atob(m[3]), c => c.charCodeAt(0)) : new TextEncoder().encode(decodeURIComponent(m[3]));
37
+ return new Blob([bytes], { type: typeof type === 'string' ? type : m[1].split(';')[0] });
38
+ }
39
+
40
+ /**
41
+ * Implementation of saves.exportFile (see its JSDoc).
42
+ * @param {any} s the Saves instance
43
+ * @param {string} slot
44
+ * @param {{ files?: boolean }} opts
45
+ * @returns {Promise<boolean>}
46
+ * @internal
47
+ */
48
+ export async function exportSaveFile(s, slot, { files = true } = {}) {
49
+ const json = s._json.get(slot);
50
+ if (!json) { toast(s.engine, s.engine.t('saves.noSlot'), { kind: 'save' }); return false; }
51
+ await s.flush(); // wait for freshly saved attachments to finish writing
52
+ const list = [];
53
+ if (files) for (const b of await s.store.blobs()) list.push({ group: b.group, id: b.id, at: b.at, meta: b.meta, type: b.blob.type, url: await toDataURL(b.blob) });
54
+ // splice the world save's JSON text in directly instead of parsing it again (halves memory at tens of MB)
55
+ const head = `{"threedog":"save","format":${FILE_FORMAT},"game":${JSON.stringify(s.prefix)},"slot":${JSON.stringify(slot)},"savedAt":${s._meta.get(slot)},"data":`;
56
+ const blob = new Blob([head, json, ',"files":', JSON.stringify(list), '}'], { type: 'application/json' });
57
+ const a = document.createElement('a'), url = URL.createObjectURL(blob);
58
+ a.href = url; a.download = `${s.prefix.replace(/-save-$/, '')}-${slot}-${new Date().toISOString().slice(0, 10)}.json`;
59
+ document.body.appendChild(a); a.click(); a.remove();
60
+ setTimeout(() => URL.revokeObjectURL(url), 10000); // presentation: release only after the browser has started the download
61
+ return true;
62
+ }
63
+
64
+ /**
65
+ * Implementation of saves.importFile (see its JSDoc). Everything is checked before anything is written.
66
+ * @param {any} s the Saves instance
67
+ * @param {Blob} [file]
68
+ * @param {string} [slot]
69
+ * @returns {Promise<string | null>}
70
+ * @internal
71
+ */
72
+ export async function importSaveFile(s, file, slot = 'imported') {
73
+ file ??= await pick();
74
+ if (!file) return null;
75
+ const refuse = why => { console.warn(coded('save-import', why)); toast(s.engine, s.engine.t('saves.badFile'), { kind: 'save' }); return null; }; // handled: the player is told, nothing changed
76
+ if (file.size > MAX_BYTES) return refuse(STRINGS.bad.replace('{why}', `${Math.round(file.size / 1e6)} MB`));
77
+ let obj;
78
+ try { obj = JSON.parse(await file.text()); } catch (e) { return refuse(STRINGS.bad.replace('{why}', e.message)); }
79
+ if (obj?.threedog !== 'save') return refuse(STRINGS.bad.replace('{why}', 'no "threedog": "save" marker'));
80
+ if ((obj.format ?? 1) > FILE_FORMAT) return refuse(STRINGS.bad.replace('{why}', `file format ${obj.format}, this build reads up to ${FILE_FORMAT}`));
81
+ const blobs = [];
82
+ for (const [i, p] of (Array.isArray(obj.files) ? obj.files : []).entries()) {
83
+ const blob = typeof p?.group === 'string' && typeof p.id === 'string' ? dataUrlBlob(p.url, p.type) : null;
84
+ if (!blob) return refuse(STRINGS.attachment.replace('{i}', String(i)));
85
+ blobs.push([p, blob]);
86
+ }
87
+ const r = await importData(s, obj.data, slot);
88
+ if (r !== true) return r === 'write' ? null : refuse(STRINGS.bad.replace('{why}', r)); // a failed write already showed its toast
89
+ let ok = true;
90
+ for (const [p, blob] of blobs) {
91
+ try { await s.queue(() => s.store.putBlob(p.group, p.id, blob, p.meta, p.at)); } catch (e) { ok = false; s._fail(e); }
92
+ }
93
+ if (!ok) return null;
94
+ s.engine.events.emit('save:imported', slot);
95
+ toast(s.engine, s.engine.t('saves.imported', { slot }), { kind: 'save' });
96
+ return slot;
97
+ }
98
+
99
+ /**
100
+ * Implementation of saves.import (see its JSDoc).
101
+ * @param {any} s the Saves instance
102
+ * @param {string} text
103
+ * @param {string} slot
104
+ * @returns {Promise<boolean>}
105
+ * @internal
106
+ */
107
+ export async function importText(s, text, slot) {
108
+ let obj;
109
+ try { obj = JSON.parse(decodeURIComponent(escape(atob(String(text).trim())))); } catch (e) { console.warn(coded('save-import', fmt(STRINGS.badText, { why: e.message }))); return false; }
110
+ const r = await importData(s, obj, slot);
111
+ if (r === true) { s.engine.events.emit('save:imported', slot); return true; }
112
+ if (r !== 'write') console.warn(coded('save-import', fmt(STRINGS.badText, { why: r }))); // a failed write already showed its toast
113
+ return false;
114
+ }
115
+ /**
116
+ * Store an imported save object (checked like a load first): true, 'write' (the disk write failed) or the reason it is not a save.
117
+ * @param {any} s the Saves instance
118
+ * @param {any} obj
119
+ * @param {string} slot
120
+ * @returns {Promise<true | string>}
121
+ * @internal
122
+ */
123
+ async function importData(s, obj, slot) {
124
+ const r = readSave(obj, s.providers, slot);
125
+ if (r.reason === 'corrupt' || r.reason === 'missing') return r.dev; // too new / unmigratable saves are kept: a newer build can load them
126
+ const data = parseSave(obj);
127
+ return (await s._put(slot, JSON.stringify(data), data.savedAt ?? 0)) ? true : 'write';
128
+ }
129
+
130
+ /** Open a file picker; null when cancelled */
131
+ function pick() {
132
+ return new Promise(res => {
133
+ const input = document.createElement('input');
134
+ input.type = 'file'; input.accept = '.json,application/json';
135
+ input.onchange = () => res(input.files?.[0] ?? null);
136
+ input.oncancel = () => res(null);
137
+ input.click();
138
+ });
139
+ }
@@ -0,0 +1,53 @@
1
+ // Record ids inside save data, for upgrade steps (saves.register migrate). Shared by the world part and every part that keys data by a record id
2
+ // (containers): when the world part renames ids, those parts must rename the same ones, and core is the one place both may import from.
3
+ // Runtime record ids: world save part version 2 numbered them `<kind>-<n>`, version 3 `<kind>#<n>` (an authored id may not contain `#`,
4
+ // so the two can never collide; modules/content/ids.js).
5
+
6
+ /**
7
+ * Old auto-numbered runtime ids of a world save part (version 1 or 2) -> the version-3 id: `crate-4` -> `crate#4`.
8
+ * Exact rule, because an authored-looking id must never be renamed: only records saved whole (runtime records; authored ones live in changed / removed)
9
+ * whose id is `<its own kind>-<n>`, n a whole number from 1 to the saved counter seq (world.add numbered with ++seq, one counter for every kind, so
10
+ * each n was handed out once). An n claimed by two records means one of them was given that id by hand: both are left alone.
11
+ * Limit: a runtime record given `<kind>-<n>` by hand, with n <= seq and no auto record sharing n, looks exactly like an auto id and is renamed too.
12
+ * @param {any} d world part data, version 1 (records array) or 2 (records keyed by id)
13
+ * @returns {Map<string, string>}
14
+ * @internal
15
+ */
16
+ export function legacyRuntimeIds(d) {
17
+ const seq = Number.isInteger(d?.seq) ? d.seq : 0, recs = d?.records;
18
+ const list = Array.isArray(recs) ? recs.map(r => [r?.id, r]) : Object.entries(recs || {});
19
+ const byN = new Map();
20
+ for (const [id, r] of list) {
21
+ const m = typeof id === 'string' && /^(.+)-([1-9]\d*)$/.exec(id);
22
+ if (!m || m[1] !== r?.kind || Number(m[2]) > seq) continue;
23
+ byN.set(m[2], byN.has(m[2]) ? null : id);
24
+ }
25
+ const out = new Map();
26
+ for (const [n, id] of byN) if (id) out.set(id, `${id.slice(0, -n.length - 1)}#${n}`);
27
+ return out;
28
+ }
29
+
30
+ /** Rename ids inside saved data: string values equal to an old id (a record field that names another record, e.g. owner: 'crate-4'), deep @internal */
31
+ export function renameIdValues(v, map, depth = 0) {
32
+ if (typeof v === 'string') return map.get(v) ?? v;
33
+ if (!v || typeof v !== 'object' || depth > 8) return v;
34
+ if (Array.isArray(v)) return v.map(x => renameIdValues(x, map, depth + 1));
35
+ const out = {};
36
+ for (const k in v) out[k] = renameIdValues(v[k], map, depth + 1);
37
+ return out;
38
+ }
39
+ /** Rename the keys of an id-keyed object (values untouched) @internal */
40
+ export const renameIdKeys = (o, map) => Object.fromEntries(Object.entries(o || {}).map(([k, v]) => [map.get(k) ?? k, v]));
41
+
42
+ /**
43
+ * Migrate step for a part keyed by record id (containers): rename the same runtime ids the world part renames. save is the whole save as read (upgradePart).
44
+ * @param {any} d
45
+ * @param {{ parts?: Record<string, any>, versions?: Record<string, number> }} [save]
46
+ * @internal
47
+ */
48
+ export function followRuntimeIds(d, save) {
49
+ const w = save?.parts?.world;
50
+ if (!w || (save.versions?.world ?? 1) >= 3) return d; // a version-3 world part already uses `#`: nothing to follow
51
+ const map = legacyRuntimeIds(w);
52
+ return map.size ? renameIdKeys(d, map) : d;
53
+ }
@@ -0,0 +1,97 @@
1
+ // Save format and per-part versions. A save is the envelope { format, savedAt, versions: { part: n }, parts: { part: data } }:
2
+ // format is the version of the envelope itself (FORMAT); a save from a newer format is refused as a whole, one without format is format 1.
3
+ // Each saves.register part carries its own version and migrate steps, so one module changing its format never touches the others; a part missing from versions is version 1.
4
+ // Everything here runs before a load touches the game, and on a copy: a refused load leaves the game and the stored save as they were.
5
+ import { codedError } from './errorHints.js';
6
+ import { fmt } from './validate.js';
7
+
8
+ /** Version of the save envelope. Raise it only when the envelope itself changes shape (never for a part's data: that is the part's own version). */
9
+ export const FORMAT = 1;
10
+
11
+ const DEV = {
12
+ badVersion: "saves.register('{k}'): version must be a whole number >= 1 (raise it by 1 whenever this part's saved data changes shape), got {v}",
13
+ badMigrate: "saves.register('{k}'): migrate is { fromVersion: data => newData }, e.g. migrate: { 1: d => ({ ...d, gold: 0 }) }; key {m} is not a version below {v}",
14
+ tooNew: "[saves] not loaded: {list}. The save comes from a newer build of the game, which this build cannot read; nothing was changed and the save is kept. " +
15
+ 'To read it, run the newer build, or raise this part\'s version (with migrate steps) to match.',
16
+ format: 'the save envelope is format {f}, this build reads up to format {max}',
17
+ corrupt: "[saves] not loaded: slot '{slot}' is not a readable save ({why}). Nothing was changed and the stored save is kept as it was.",
18
+ noStep: "save part '{k}' is version {from} but this build is version {to}, and migrate has no step {from}: add migrate: { {from}: data => newData } to saves.register('{k}')",
19
+ };
20
+
21
+ /**
22
+ * Validate a part's version and migrate steps at register time (a typo shows up at once, not when an old save happens to be read).
23
+ * @param {string} key
24
+ * @param {number} version
25
+ * @param {Record<string, Function>} migrate
26
+ * @returns {void}
27
+ * @internal
28
+ */
29
+ export function checkPartVersion(key, version, migrate) {
30
+ if (!Number.isInteger(version) || version < 1) throw codedError('save-version', fmt(DEV.badVersion, { k: key, v: version }));
31
+ for (const [m, fn] of Object.entries(migrate)) {
32
+ if (!(Number(m) >= 1 && Number(m) < version) || typeof fn !== 'function') throw codedError('save-version', fmt(DEV.badMigrate, { k: key, m, v: version }));
33
+ }
34
+ }
35
+
36
+ /** JSON reviver for save data from outside (stored text, imported files): drops "__proto__" keys, which Object.assign would turn into a prototype swap */
37
+ const clean = (k, v) => (k === '__proto__' ? undefined : v);
38
+
39
+ /**
40
+ * Parse save text (or copy a save object) into a fresh, prototype-safe object. Throws on unreadable text.
41
+ * @param {string | object} json
42
+ * @returns {any}
43
+ * @internal
44
+ */
45
+ export function parseSave(json) { return JSON.parse(typeof json === 'string' ? json : JSON.stringify(json), clean); }
46
+
47
+ /**
48
+ * Upgrade one part's data from its saved version to the current one, step by step (on a copy: the caller's save stays as it was).
49
+ * @param {string} key
50
+ * @param {{ version: number, migrate: Record<string, (d: any) => any> }} p
51
+ * Each step gets (data, save): save is { parts, versions } of the whole save as read (before any part was upgraded), read only. It is there because
52
+ * some upgrades depend on another part: the world part renaming runtime ids (`kind-3` -> `kind#3`) means every other part that keys data by a record id
53
+ * (containers) has to rename the same ids, and only the world part's records tell which ids those are.
54
+ * @param {any} data
55
+ * @param {number} from
56
+ * @param {{ parts: Record<string, any>, versions: Record<string, number> }} [save]
57
+ * @returns {any}
58
+ * @internal
59
+ */
60
+ export function upgradePart(key, p, data, from, save = { parts: {}, versions: {} }) {
61
+ if (from >= p.version) return data;
62
+ let d = structuredClone(data);
63
+ for (let v = from; v < p.version; v++) {
64
+ const fn = p.migrate[v];
65
+ if (!fn) throw codedError('save-refused', fmt(DEV.noStep, { k: key, from: v, to: p.version }));
66
+ d = fn(d, save) ?? d;
67
+ }
68
+ return d;
69
+ }
70
+
71
+ /**
72
+ * Everything that can be checked before a load touches the running game: readable JSON, the envelope format, the save shape, no part from a newer build,
73
+ * every migrate step present. Returns the parsed save (prototype-safe), the upgraded registered parts (in load order) and the parts no registered module owns
74
+ * (kept, so a save does not lose them), or the reason the load is refused.
75
+ * @param {string | object | undefined} json the stored save text, or a save object
76
+ * @param {Map<string, { version: number, first: boolean, migrate: Record<string, Function> }>} providers
77
+ * @param {string} slot for the message only
78
+ * @returns {{ data: any, list: [string, any, any][], foreign: { parts: Record<string, any>, versions: Record<string, number>, whole: any } } | { reason: 'missing' | 'corrupt' | 'tooNew' | 'migrate', dev: string }}
79
+ * @internal
80
+ */
81
+ export function readSave(json, providers, slot) {
82
+ if (json == null) return { reason: 'missing', dev: `[saves] slot '${slot}' does not exist` };
83
+ let data;
84
+ try { data = parseSave(json); } catch (e) { return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: e.message }) }; }
85
+ if (!data?.parts || typeof data.parts !== 'object' || Array.isArray(data.parts)) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: 'no parts' }) };
86
+ const format = data.format ?? 1;
87
+ if (!Number.isInteger(format) || format < 1) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `format ${JSON.stringify(data.format)}` }) };
88
+ if (format > FORMAT) return { reason: 'tooNew', dev: fmt(DEV.tooNew, { list: fmt(DEV.format, { f: format, max: FORMAT }) }) };
89
+ const versions = data.versions || {};
90
+ const list = [...providers].filter(([k]) => k in data.parts).sort((a, b) => (b[1].first ? 1 : 0) - (a[1].first ? 1 : 0));
91
+ const newer = list.filter(([k, p]) => (versions[k] ?? 1) > p.version).map(([k, p]) => `part '${k}' is version ${versions[k]}, this build reads up to ${p.version}`);
92
+ if (newer.length) return { reason: 'tooNew', dev: fmt(DEV.tooNew, { list: newer.join('; ') }) };
93
+ // whole: the save as read, for migrate steps that need another part (upgradePart); kept on foreign so a part registered later (adoptPart) sees it too
94
+ const whole = { parts: data.parts, versions }, foreign = { parts: {}, versions: {}, whole };
95
+ for (const k of Object.keys(data.parts)) if (!providers.has(k)) { foreign.parts[k] = data.parts[k]; foreign.versions[k] = versions[k] ?? 1; }
96
+ try { return { data, foreign, list: list.map(([k, p]) => [k, p, upgradePart(k, p, data.parts[k], versions[k] ?? 1, whole)]) }; } catch (e) { return { reason: 'migrate', dev: e.message }; }
97
+ }