agentscape3d-engine 0.0.0-stage → 1.0.0-beta.3

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 (457) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/cli.mjs +53 -0
  4. package/dist/ArticulationVerifier-BfGxXY8V.js +337 -0
  5. package/dist/ArticulationVerifier-BfGxXY8V.js.map +1 -0
  6. package/dist/AssetCompiler-BLj09iu1.js +2424 -0
  7. package/dist/AssetCompiler-BLj09iu1.js.map +1 -0
  8. package/dist/AssetModule-DME-XaFS.js +2637 -0
  9. package/dist/AssetModule-DME-XaFS.js.map +1 -0
  10. package/dist/AssetRecipe-g8dZBhgJ.js +298 -0
  11. package/dist/AssetRecipe-g8dZBhgJ.js.map +1 -0
  12. package/dist/BrowserCodeWorker.js +53856 -0
  13. package/dist/BrowserCodeWorker.js.map +1 -0
  14. package/dist/CarryCapability-CXwHU5ay.js +104 -0
  15. package/dist/CarryCapability-CXwHU5ay.js.map +1 -0
  16. package/dist/KinematicHypothesisScreen-C3TKiuYR.js +241 -0
  17. package/dist/KinematicHypothesisScreen-C3TKiuYR.js.map +1 -0
  18. package/dist/ObjectTransform-BlQUNK7c.js +61 -0
  19. package/dist/ObjectTransform-BlQUNK7c.js.map +1 -0
  20. package/dist/RapierPhysicsBackend-B2wQe_Vl.js +3259 -0
  21. package/dist/RapierPhysicsBackend-B2wQe_Vl.js.map +1 -0
  22. package/dist/RenderingSystem-WIr1ZuGu.js +1042 -0
  23. package/dist/RenderingSystem-WIr1ZuGu.js.map +1 -0
  24. package/dist/ScenePresentation-LsYiDxbm.js +152 -0
  25. package/dist/ScenePresentation-LsYiDxbm.js.map +1 -0
  26. package/dist/SceneProject-K7HH1s8o.js +2687 -0
  27. package/dist/SceneProject-K7HH1s8o.js.map +1 -0
  28. package/dist/SceneSerializer-zOzbX4jZ.js +932 -0
  29. package/dist/SceneSerializer-zOzbX4jZ.js.map +1 -0
  30. package/dist/SimulationProfile-DSYZbBLQ.js +165 -0
  31. package/dist/SimulationProfile-DSYZbBLQ.js.map +1 -0
  32. package/dist/StylePack-DcRa_kU0.js +88 -0
  33. package/dist/StylePack-DcRa_kU0.js.map +1 -0
  34. package/dist/WorldArchive-BiFGLt--.js +451 -0
  35. package/dist/WorldArchive-BiFGLt--.js.map +1 -0
  36. package/dist/WorldCommands-Debj7V4L.js +2207 -0
  37. package/dist/WorldCommands-Debj7V4L.js.map +1 -0
  38. package/dist/WorldIO-Ch8QBfKY.js +151 -0
  39. package/dist/WorldIO-Ch8QBfKY.js.map +1 -0
  40. package/dist/admission-CVEvsrdz.js +121 -0
  41. package/dist/admission-CVEvsrdz.js.map +1 -0
  42. package/dist/blankWorld-B0MW6g7q.js +75 -0
  43. package/dist/blankWorld-B0MW6g7q.js.map +1 -0
  44. package/dist/core.d.ts +68 -0
  45. package/dist/core.js +209 -0
  46. package/dist/core.js.map +1 -0
  47. package/dist/disposeObject3D-DIMzy0FA.js +128 -0
  48. package/dist/disposeObject3D-DIMzy0FA.js.map +1 -0
  49. package/dist/environments-HOe3sJXH.js +567 -0
  50. package/dist/environments-HOe3sJXH.js.map +1 -0
  51. package/dist/gltfIO-BzVKLyaL.js +339 -0
  52. package/dist/gltfIO-BzVKLyaL.js.map +1 -0
  53. package/dist/grandUrbanBlock-DRndRZjF.js +515 -0
  54. package/dist/grandUrbanBlock-DRndRZjF.js.map +1 -0
  55. package/dist/index.d.ts +345 -0
  56. package/dist/index.js +16952 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/magicCabin-CfBZjx2Q.js +11019 -0
  59. package/dist/magicCabin-CfBZjx2Q.js.map +1 -0
  60. package/dist/manifests-D0LwbJ36.js +866 -0
  61. package/dist/manifests-D0LwbJ36.js.map +1 -0
  62. package/dist/mcp.d.ts +2 -0
  63. package/dist/mcp.js +1 -0
  64. package/dist/monumentHall-awZiGtda.js +403 -0
  65. package/dist/monumentHall-awZiGtda.js.map +1 -0
  66. package/dist/node.d.ts +16 -0
  67. package/dist/node.js +26 -0
  68. package/dist/parts-DrEcfJRl.js +37 -0
  69. package/dist/parts-DrEcfJRl.js.map +1 -0
  70. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  71. package/dist/ruinedCourtyard-DuF7NmUU.js +696 -0
  72. package/dist/ruinedCourtyard-DuF7NmUU.js.map +1 -0
  73. package/dist/runtime/application/AgentTools.js +28 -0
  74. package/dist/runtime/application/README.md +14 -0
  75. package/dist/runtime/application/agent/ProgressiveAgentTools.js +92 -0
  76. package/dist/runtime/application/agent/StudioMcpAllowlist.js +10 -0
  77. package/dist/runtime/application/agent/StudioProjectTools.js +18 -0
  78. package/dist/runtime/application/agent/TaskEvidence.js +199 -0
  79. package/dist/runtime/application/buildTaskObservation.js +117 -0
  80. package/dist/runtime/application/code-execution/AuthoringSandboxEntry.js +50 -0
  81. package/dist/runtime/application/code-execution/BrowserCodeExecutor.js +35 -0
  82. package/dist/runtime/application/code-execution/BrowserCodeWorker.js +17 -0
  83. package/dist/runtime/application/code-execution/RemoteAuthoringDocument.js +82 -0
  84. package/dist/runtime/application/createSession.js +66 -0
  85. package/dist/runtime/application/createWorldAuthoringContext.js +400 -0
  86. package/dist/runtime/application/generation/GenerationOrchestrator.js +630 -0
  87. package/dist/runtime/application/generation/GenerationRuntime.js +215 -0
  88. package/dist/runtime/application/generation/PromptHybridWorldOrchestrator.js +289 -0
  89. package/dist/runtime/application/native-scene/CodeProject.js +215 -0
  90. package/dist/runtime/application/native-scene/CodeProjectModules.js +143 -0
  91. package/dist/runtime/application/native-scene/ExampleWorldCatalog.js +35 -0
  92. package/dist/runtime/application/native-scene/NativeArticulation.js +53 -0
  93. package/dist/runtime/application/native-scene/NativeEditableRegistry.js +150 -0
  94. package/dist/runtime/application/native-scene/NativeEnvironmentGeometry.js +85 -0
  95. package/dist/runtime/application/native-scene/NativeLightingInspection.js +33 -0
  96. package/dist/runtime/application/native-scene/NativeMaterialInspection.js +52 -0
  97. package/dist/runtime/application/native-scene/NativeOverlayCheckpoint.js +127 -0
  98. package/dist/runtime/application/native-scene/NativePhysicsGeometry.js +64 -0
  99. package/dist/runtime/application/native-scene/NativeRenderDiscovery.js +51 -0
  100. package/dist/runtime/application/native-scene/NativeSceneHost.js +406 -0
  101. package/dist/runtime/application/native-scene/NativeSceneInspection.js +203 -0
  102. package/dist/runtime/application/native-scene/NativeSceneOverlay.js +116 -0
  103. package/dist/runtime/application/native-scene/NativeSceneQuery.js +123 -0
  104. package/dist/runtime/application/native-scene/NativeSceneReview.js +132 -0
  105. package/dist/runtime/application/native-scene/NativeThreeModule.js +16 -0
  106. package/dist/runtime/application/native-scene/SceneObserver.js +97 -0
  107. package/dist/runtime/application/native-scene/VisualCapturePolicy.js +4 -0
  108. package/dist/runtime/application/object-forge/SceneObjectForge.js +263 -0
  109. package/dist/runtime/application/programmatic-assets/ProgrammaticAssetBuilder.js +59 -0
  110. package/dist/runtime/application/programmatic-assets/ProgrammaticAssetContract.js +22 -0
  111. package/dist/runtime/application/programmatic-assets/ThreeCodeAsset.js +40 -0
  112. package/dist/runtime/application/scene/CapabilityResolver.js +90 -0
  113. package/dist/runtime/application/scene/NativeEditableContracts.js +18 -0
  114. package/dist/runtime/application/scene/RequestWindow.js +54 -0
  115. package/dist/runtime/application/scene/SceneAgentTools.js +21 -0
  116. package/dist/runtime/application/scene/SceneContracts.js +49 -0
  117. package/dist/runtime/application/scene/SceneEditService.js +154 -0
  118. package/dist/runtime/application/scene/SceneFacade.js +356 -0
  119. package/dist/runtime/application/scene/SceneInteractionAdapters.js +41 -0
  120. package/dist/runtime/application/scene/SceneJobController.js +320 -0
  121. package/dist/runtime/application/scene/SceneLifecycle.js +57 -0
  122. package/dist/runtime/application/scene/ScenePackage.js +173 -0
  123. package/dist/runtime/application/scene/ScenePersistence.js +50 -0
  124. package/dist/runtime/application/scene/SceneProject.js +95 -0
  125. package/dist/runtime/application/scene/SceneSkillNames.js +5 -0
  126. package/dist/runtime/application/scene/StarterScene.js +56 -0
  127. package/dist/runtime/application/scene/WorldArchive.js +89 -0
  128. package/dist/runtime/application/scene/WorldDirectory.js +20 -0
  129. package/dist/runtime/application/scene/WorldDocument.js +76 -0
  130. package/dist/runtime/application/scene/WorldIO.js +103 -0
  131. package/dist/runtime/application/scene/WorldStorage.js +155 -0
  132. package/dist/runtime/application/skills/SkillRegistry.js +193 -0
  133. package/dist/runtime/application/skills/packs/acceptanceSkills.js +32 -0
  134. package/dist/runtime/application/skills/packs/affordanceSkills.js +36 -0
  135. package/dist/runtime/application/skills/packs/assetSkills.js +46 -0
  136. package/dist/runtime/application/skills/packs/authoringSkills.js +16 -0
  137. package/dist/runtime/application/skills/packs/batchSkills.js +22 -0
  138. package/dist/runtime/application/skills/packs/codeSkills.js +106 -0
  139. package/dist/runtime/application/skills/packs/generationSkills.js +45 -0
  140. package/dist/runtime/application/skills/packs/interactionSkills.js +46 -0
  141. package/dist/runtime/application/skills/packs/recoverySkills.js +80 -0
  142. package/dist/runtime/application/skills/packs/sceneSkills.js +24 -0
  143. package/dist/runtime/application/skills/packs/spatialSkills.js +35 -0
  144. package/dist/runtime/application/skills/packs/verificationSkills.js +14 -0
  145. package/dist/runtime/application/skills/packs/worldSkills.js +45 -0
  146. package/dist/runtime/application/skills/registerCoreSkills.js +31 -0
  147. package/dist/runtime/application/skills/skillPrimitives.js +4 -0
  148. package/dist/runtime/application/tasks/CabinetCupTask.js +76 -0
  149. package/dist/runtime/application/tasks.jsonl +67 -0
  150. package/dist/runtime/application/world-authoring/AuthoringAssetProducer.js +42 -0
  151. package/dist/runtime/application/world-authoring/AuthoringDiff.js +149 -0
  152. package/dist/runtime/application/world-authoring/AuthoringDocument.js +825 -0
  153. package/dist/runtime/application/world-authoring/AuthoringExecutionHost.js +109 -0
  154. package/dist/runtime/application/world-authoring/AuthoringIdentity.js +17 -0
  155. package/dist/runtime/application/world-authoring/AuthoringModelResolver.js +29 -0
  156. package/dist/runtime/application/world-authoring/AuthoringPatch.js +118 -0
  157. package/dist/runtime/application/world-authoring/AuthoringPromotionController.js +334 -0
  158. package/dist/runtime/application/world-authoring/AuthoringPromotionSource.js +126 -0
  159. package/dist/runtime/application/world-authoring/AuthoringRevisionHistory.js +144 -0
  160. package/dist/runtime/application/world-authoring/HeadlessImageExport.js +92 -0
  161. package/dist/runtime/application/world-authoring/ModelRef.js +62 -0
  162. package/dist/runtime/application/world-authoring/SceneGLBExport.js +88 -0
  163. package/dist/runtime/apps/mcp-server/AUTHORING.md +71 -0
  164. package/dist/runtime/apps/mcp-server/AgentMcpCompat.js +68 -0
  165. package/dist/runtime/apps/mcp-server/AuthoringSandboxEntry.js +1 -0
  166. package/dist/runtime/apps/mcp-server/AuthoringSandboxWorker.mjs +30 -0
  167. package/dist/runtime/apps/mcp-server/BuildEnvironment.js +17 -0
  168. package/dist/runtime/apps/mcp-server/CodeExecutor.js +71 -0
  169. package/dist/runtime/apps/mcp-server/DEPLOYMENT-PC2.md +42 -0
  170. package/dist/runtime/apps/mcp-server/DockerBuildRunner.js +66 -0
  171. package/dist/runtime/apps/mcp-server/FileAssetRepository.js +159 -0
  172. package/dist/runtime/apps/mcp-server/HeadlessAssetIO.js +8 -0
  173. package/dist/runtime/apps/mcp-server/HeadlessGLTFLoader.js +47 -0
  174. package/dist/runtime/apps/mcp-server/HeadlessWorldHost.js +157 -0
  175. package/dist/runtime/apps/mcp-server/IsolatedAuthoringExecutor.js +6 -0
  176. package/dist/runtime/apps/mcp-server/PROGRAMMATIC-ASSETS.md +116 -0
  177. package/dist/runtime/apps/mcp-server/ProgrammaticAssets.js +60 -0
  178. package/dist/runtime/apps/mcp-server/README.md +269 -0
  179. package/dist/runtime/apps/mcp-server/RemoteAuthoringDocument.js +1 -0
  180. package/dist/runtime/apps/mcp-server/SandboxBundle.js +13 -0
  181. package/dist/runtime/apps/mcp-server/SessionManager.js +148 -0
  182. package/dist/runtime/apps/mcp-server/StudioBridgeHttp.js +75 -0
  183. package/dist/runtime/apps/mcp-server/StudioLiveBridge.js +246 -0
  184. package/dist/runtime/apps/mcp-server/StudioProjectToolContracts.js +58 -0
  185. package/dist/runtime/apps/mcp-server/TransferHttp.js +47 -0
  186. package/dist/runtime/apps/mcp-server/TransferLimits.js +6 -0
  187. package/dist/runtime/apps/mcp-server/TransferStore.js +134 -0
  188. package/dist/runtime/apps/mcp-server/TrustedAuthoringWorker.mjs +16 -0
  189. package/dist/runtime/apps/mcp-server/VALIDATION.md +45 -0
  190. package/dist/runtime/apps/mcp-server/acceptance-evidence.json +332 -0
  191. package/dist/runtime/apps/mcp-server/errorDiagnostics.js +32 -0
  192. package/dist/runtime/apps/mcp-server/examples/code-house.js +24 -0
  193. package/dist/runtime/apps/mcp-server/examples/procedural-assets.js +85 -0
  194. package/dist/runtime/apps/mcp-server/main.mjs +82 -0
  195. package/dist/runtime/apps/mcp-server/registerTools.js +274 -0
  196. package/dist/runtime/apps/mcp-server/sandbox/run.mjs +23 -0
  197. package/dist/runtime/apps/mcp-server/security.js +23 -0
  198. package/dist/runtime/apps/mcp-server/tasks.jsonl +9 -0
  199. package/dist/runtime/apps/server/CapabilityAdapterRegistry.js +157 -0
  200. package/dist/runtime/apps/server/README.md +7 -0
  201. package/dist/runtime/apps/server/WorldRepository.js +338 -0
  202. package/dist/runtime/apps/server/WorldRepositoryHttp.js +96 -0
  203. package/dist/runtime/apps/server/openai-compatible-agent-gateway.mjs +278 -0
  204. package/dist/runtime/apps/server/tasks.jsonl +10 -0
  205. package/dist/runtime/apps/shared/node/WorldDiskStorage.js +62 -0
  206. package/dist/runtime/foundation/EventBus.js +26 -0
  207. package/dist/runtime/foundation/JsonGateway.js +47 -0
  208. package/dist/runtime/foundation/PngRgba.js +99 -0
  209. package/dist/runtime/foundation/PolicyEngine.js +21 -0
  210. package/dist/runtime/foundation/README.md +7 -0
  211. package/dist/runtime/foundation/TraceRecorder.js +76 -0
  212. package/dist/runtime/foundation/errors.js +8 -0
  213. package/dist/runtime/foundation/simulation/SimulationProfile.js +143 -0
  214. package/dist/runtime/foundation/version.js +2 -0
  215. package/dist/runtime/modules/agent/README.md +11 -0
  216. package/dist/runtime/modules/agent/ToolCallingAgent.js +19 -0
  217. package/dist/runtime/modules/agent/bootstrapWorld.js +10 -0
  218. package/dist/runtime/modules/agent/buildRecoveryProposals.js +533 -0
  219. package/dist/runtime/modules/agent/execution/AgentExecutionRules.js +128 -0
  220. package/dist/runtime/modules/agent/execution/AgentRunResults.js +55 -0
  221. package/dist/runtime/modules/agent/execution/AgentRunSession.js +393 -0
  222. package/dist/runtime/modules/agent/execution/AgentToolInvoker.js +40 -0
  223. package/dist/runtime/modules/agent/gateway/HttpLLMGateway.js +19 -0
  224. package/dist/runtime/modules/agent/prompt/index.js +52 -0
  225. package/dist/runtime/modules/agent/tasks.jsonl +94 -0
  226. package/dist/runtime/modules/artifact/ArtifactContentGate.js +144 -0
  227. package/dist/runtime/modules/artifact/ArtifactDescriptor.js +280 -0
  228. package/dist/runtime/modules/artifact/ArtifactImporter.js +185 -0
  229. package/dist/runtime/modules/artifact/ArtifactModule.js +111 -0
  230. package/dist/runtime/modules/artifact/ArtifactRegistry.js +197 -0
  231. package/dist/runtime/modules/artifact/IncrementalSha256.js +129 -0
  232. package/dist/runtime/modules/artifact/MemoryArtifactByteStore.js +115 -0
  233. package/dist/runtime/modules/artifact/README.md +7 -0
  234. package/dist/runtime/modules/artifact/storage/IndexedDbArtifactStore.js +67 -0
  235. package/dist/runtime/modules/artifact/tasks.jsonl +31 -0
  236. package/dist/runtime/modules/asset/AssetModule.js +416 -0
  237. package/dist/runtime/modules/asset/README.md +67 -0
  238. package/dist/runtime/modules/asset/loading/AssetLoader.js +157 -0
  239. package/dist/runtime/modules/asset/loading/GltfAssetLoader.js +61 -0
  240. package/dist/runtime/modules/asset/loading/builtins/BuiltinAssets.js +95 -0
  241. package/dist/runtime/modules/asset/loading/builtins/HouseDoor.js +33 -0
  242. package/dist/runtime/modules/asset/loading/builtins/IndustrialCabinet.js +103 -0
  243. package/dist/runtime/modules/asset/model/AssetInputContracts.js +139 -0
  244. package/dist/runtime/modules/asset/model/AssetRef.js +12 -0
  245. package/dist/runtime/modules/asset/model/MechanicalAssetDraft.js +172 -0
  246. package/dist/runtime/modules/asset/model/ProceduralTextureContract.js +24 -0
  247. package/dist/runtime/modules/asset/model/admission.js +117 -0
  248. package/dist/runtime/modules/asset/model/errors.js +6 -0
  249. package/dist/runtime/modules/asset/model/parts.js +27 -0
  250. package/dist/runtime/modules/asset/model/resourceBudget.js +10 -0
  251. package/dist/runtime/modules/asset/model/schema.js +150 -0
  252. package/dist/runtime/modules/asset/persistence/AssetManifestStore.js +78 -0
  253. package/dist/runtime/modules/asset/persistence/CompiledAssetStore.js +84 -0
  254. package/dist/runtime/modules/asset/persistence/LocalAssetLibrary.js +86 -0
  255. package/dist/runtime/modules/asset/persistence/LocalAssetLibraryStore.js +81 -0
  256. package/dist/runtime/modules/asset/production/AssetProductionPipeline.js +272 -0
  257. package/dist/runtime/modules/asset/production/AssetRecipe.js +91 -0
  258. package/dist/runtime/modules/asset/production/ProceduralTexture.js +85 -0
  259. package/dist/runtime/modules/asset/production/adapters/EmbodiedGenAdapter.js +45 -0
  260. package/dist/runtime/modules/asset/production/adapters/EmbodiedGenBundleAdapter.js +590 -0
  261. package/dist/runtime/modules/asset/production/compiler/AssetCompiler.js +173 -0
  262. package/dist/runtime/modules/asset/production/compiler/evidence/AnimationMotionEvidence.js +124 -0
  263. package/dist/runtime/modules/asset/production/compiler/evidence/StaticPanelEvidence.js +56 -0
  264. package/dist/runtime/modules/asset/production/compiler/gltfIO.js +6 -0
  265. package/dist/runtime/modules/asset/production/compiler/partGeometry.js +74 -0
  266. package/dist/runtime/modules/asset/production/compiler/passes/ArticulatedCollisionPass.js +63 -0
  267. package/dist/runtime/modules/asset/production/compiler/passes/ArticulationCandidatePass.js +48 -0
  268. package/dist/runtime/modules/asset/production/compiler/passes/AuthoringIntentPass.js +16 -0
  269. package/dist/runtime/modules/asset/production/compiler/passes/ColliderFallbackPass.js +30 -0
  270. package/dist/runtime/modules/asset/production/compiler/passes/CompileQualityPass.js +75 -0
  271. package/dist/runtime/modules/asset/production/compiler/passes/ExplicitDefinitionPass.js +20 -0
  272. package/dist/runtime/modules/asset/production/compiler/passes/GLTFInspectPass.js +34 -0
  273. package/dist/runtime/modules/asset/production/compiler/passes/GeometryPass.js +32 -0
  274. package/dist/runtime/modules/asset/production/compiler/passes/JointFramePass.js +116 -0
  275. package/dist/runtime/modules/asset/production/compiler/passes/KinematicEvidencePass.js +84 -0
  276. package/dist/runtime/modules/asset/production/compiler/passes/ManifestPass.js +63 -0
  277. package/dist/runtime/modules/asset/production/compiler/passes/NormalizeTransformPass.js +16 -0
  278. package/dist/runtime/modules/asset/production/compiler/passes/OptimizeGLBPass.js +23 -0
  279. package/dist/runtime/modules/asset/production/compiler/passes/PartColliderPass.js +50 -0
  280. package/dist/runtime/modules/asset/production/compiler/passes/PartGeometryEnrichmentPass.js +60 -0
  281. package/dist/runtime/modules/asset/production/compiler/passes/PartProposalPass.js +93 -0
  282. package/dist/runtime/modules/asset/production/compiler/passes/RemoteEnrichmentPass.js +32 -0
  283. package/dist/runtime/modules/asset/production/compiler/passes/ResourceBudgetPass.js +55 -0
  284. package/dist/runtime/modules/asset/production/compiler/passes/SegmentMaterializePass.js +203 -0
  285. package/dist/runtime/modules/asset/production/compiler/passes/SegmentationEvidencePass.js +43 -0
  286. package/dist/runtime/modules/asset/production/compiler/passes/SemanticHeuristicPass.js +33 -0
  287. package/dist/runtime/modules/asset/production/compiler/passes/StructurePass.js +60 -0
  288. package/dist/runtime/modules/asset/production/compiler/providers/HttpCompilerProvider.js +23 -0
  289. package/dist/runtime/modules/asset/production/verification/KinematicHypothesisScreen.js +198 -0
  290. package/dist/runtime/modules/asset/registry/AssetCatalog.js +72 -0
  291. package/dist/runtime/modules/asset/registry/AssetRegistry.js +51 -0
  292. package/dist/runtime/modules/asset/registry/manifests/index.js +173 -0
  293. package/dist/runtime/modules/asset/tasks.jsonl +87 -0
  294. package/dist/runtime/modules/generation/README.md +9 -0
  295. package/dist/runtime/modules/generation/connector/ConnectorArtifactClient.js +45 -0
  296. package/dist/runtime/modules/generation/connector/ConnectorCapabilityAdapter.js +169 -0
  297. package/dist/runtime/modules/generation/connector/ConnectorClient.js +192 -0
  298. package/dist/runtime/modules/generation/connector/ConnectorJobClient.js +167 -0
  299. package/dist/runtime/modules/generation/connector/ConnectorJobEventClient.js +179 -0
  300. package/dist/runtime/modules/generation/connector/ConnectorSession.js +202 -0
  301. package/dist/runtime/modules/generation/jobs/GenerationJobProjection.js +239 -0
  302. package/dist/runtime/modules/generation/jobs/GenerationJobReconciler.js +99 -0
  303. package/dist/runtime/modules/generation/jobs/GenerationJobStore.js +91 -0
  304. package/dist/runtime/modules/generation/jobs/GenerationJobTransportOverlay.js +50 -0
  305. package/dist/runtime/modules/generation/providers/ProviderRegistry.js +304 -0
  306. package/dist/runtime/modules/generation/tasks.jsonl +35 -0
  307. package/dist/runtime/modules/navigation/NavigationBackend.js +17 -0
  308. package/dist/runtime/modules/navigation/RecastNavigationBackend.js +263 -0
  309. package/dist/runtime/modules/physics/JoltPhysicsBackend.js +850 -0
  310. package/dist/runtime/modules/physics/PhysicsApiSurface.js +660 -0
  311. package/dist/runtime/modules/physics/PhysicsBackend.js +88 -0
  312. package/dist/runtime/modules/physics/RapierPhysicsBackend.js +414 -0
  313. package/dist/runtime/modules/rendering/README.md +7 -0
  314. package/dist/runtime/modules/rendering/RendererProbe.js +153 -0
  315. package/dist/runtime/modules/rendering/WebGpuPostFxPipeline.js +140 -0
  316. package/dist/runtime/modules/rendering/captureStill.js +54 -0
  317. package/dist/runtime/modules/rendering/createRenderer.js +76 -0
  318. package/dist/runtime/modules/rendering/disposeObject3D.js +37 -0
  319. package/dist/runtime/modules/rendering/loadGaussianSplatVisual.js +74 -0
  320. package/dist/runtime/modules/rendering/spatial/ThreeBvhRuntime.js +107 -0
  321. package/dist/runtime/modules/rendering/style/StylePack.js +34 -0
  322. package/dist/runtime/modules/rendering/style/StyleSystem.js +173 -0
  323. package/dist/runtime/modules/rendering/tasks.jsonl +7 -0
  324. package/dist/runtime/modules/world/README.md +13 -0
  325. package/dist/runtime/modules/world/build/WorldBuilder.js +170 -0
  326. package/dist/runtime/modules/world/compiler/PipelineEngine.js +32 -0
  327. package/dist/runtime/modules/world/compiler/WorldAdmission.js +43 -0
  328. package/dist/runtime/modules/world/compiler/WorldBehaviorCompiler.js +68 -0
  329. package/dist/runtime/modules/world/compiler/WorldCompilation.js +157 -0
  330. package/dist/runtime/modules/world/compiler/WorldComposer.js +201 -0
  331. package/dist/runtime/modules/world/compiler/WorldPhysicsAdmission.js +76 -0
  332. package/dist/runtime/modules/world/compiler/WorldRecompiler.js +356 -0
  333. package/dist/runtime/modules/world/compiler/WorldRetry.js +75 -0
  334. package/dist/runtime/modules/world/compiler/createWorldPipeline.js +379 -0
  335. package/dist/runtime/modules/world/content/blankWorld.js +35 -0
  336. package/dist/runtime/modules/world/content/environments.js +84 -0
  337. package/dist/runtime/modules/world/content/grandUrbanBlock.js +189 -0
  338. package/dist/runtime/modules/world/content/magic-cabin/README.md +28 -0
  339. package/dist/runtime/modules/world/content/magic-cabin/affordances.js +64 -0
  340. package/dist/runtime/modules/world/content/magic-cabin/cabinContents.js +7078 -0
  341. package/dist/runtime/modules/world/content/magic-cabin/lighting.js +26 -0
  342. package/dist/runtime/modules/world/content/magic-cabin/materials.js +20 -0
  343. package/dist/runtime/modules/world/content/magicCabin.js +190 -0
  344. package/dist/runtime/modules/world/content/monumentHall.js +154 -0
  345. package/dist/runtime/modules/world/content/ruinedCourtyard.js +196 -0
  346. package/dist/runtime/modules/world/content/suzhouGarden/README.md +141 -0
  347. package/dist/runtime/modules/world/content/suzhouGarden/index.js +137 -0
  348. package/dist/runtime/modules/world/content/suzhouGarden/src/arch.js +491 -0
  349. package/dist/runtime/modules/world/content/suzhouGarden/src/buildings.js +670 -0
  350. package/dist/runtime/modules/world/content/suzhouGarden/src/core.js +578 -0
  351. package/dist/runtime/modules/world/content/suzhouGarden/src/lod.js +127 -0
  352. package/dist/runtime/modules/world/content/suzhouGarden/src/main.js +642 -0
  353. package/dist/runtime/modules/world/content/suzhouGarden/src/nature.js +650 -0
  354. package/dist/runtime/modules/world/content/suzhouGarden/src/rockery.js +280 -0
  355. package/dist/runtime/modules/world/content/suzhouGarden/src/sky.js +242 -0
  356. package/dist/runtime/modules/world/content/suzhouGarden/src/water.js +215 -0
  357. package/dist/runtime/modules/world/content/woodlandWorkshop.js +192 -0
  358. package/dist/runtime/modules/world/content/yuanmingyuan/README.md +36 -0
  359. package/dist/runtime/modules/world/content/yuanmingyuan/arch.js +351 -0
  360. package/dist/runtime/modules/world/content/yuanmingyuan/buildings.js +490 -0
  361. package/dist/runtime/modules/world/content/yuanmingyuan/core.js +505 -0
  362. package/dist/runtime/modules/world/content/yuanmingyuan/index.js +101 -0
  363. package/dist/runtime/modules/world/content/yuanmingyuan/nature.js +435 -0
  364. package/dist/runtime/modules/world/content/yuanmingyuan/sky.js +169 -0
  365. package/dist/runtime/modules/world/content/yuanmingyuan/water.js +245 -0
  366. package/dist/runtime/modules/world/errors.js +9 -0
  367. package/dist/runtime/modules/world/generated/GeneratedWorldCoordinates.js +50 -0
  368. package/dist/runtime/modules/world/generated/GeneratedWorldLoader.js +297 -0
  369. package/dist/runtime/modules/world/runtime/CommandHistory.js +111 -0
  370. package/dist/runtime/modules/world/runtime/EntityCapabilityRegistry.js +165 -0
  371. package/dist/runtime/modules/world/runtime/NativeNavigationGeometry.js +84 -0
  372. package/dist/runtime/modules/world/runtime/NativePhysicsSnapshot.js +245 -0
  373. package/dist/runtime/modules/world/runtime/ObjectStore.js +31 -0
  374. package/dist/runtime/modules/world/runtime/ObjectTransform.js +62 -0
  375. package/dist/runtime/modules/world/runtime/ObservedEntity.js +37 -0
  376. package/dist/runtime/modules/world/runtime/ProjectCapabilities.js +240 -0
  377. package/dist/runtime/modules/world/runtime/SceneExtensions.js +36 -0
  378. package/dist/runtime/modules/world/runtime/ScenePresentation.js +101 -0
  379. package/dist/runtime/modules/world/runtime/SceneSerializer.js +281 -0
  380. package/dist/runtime/modules/world/runtime/WorldAuthority.js +41 -0
  381. package/dist/runtime/modules/world/runtime/WorldCollisionSignature.js +14 -0
  382. package/dist/runtime/modules/world/runtime/WorldCommands.js +503 -0
  383. package/dist/runtime/modules/world/runtime/WorldObservation.js +71 -0
  384. package/dist/runtime/modules/world/runtime/WorldQueries.js +340 -0
  385. package/dist/runtime/modules/world/runtime/WorldRecovery.js +78 -0
  386. package/dist/runtime/modules/world/runtime/WorldRuntime.js +806 -0
  387. package/dist/runtime/modules/world/runtime/affordance/ObjectAffordances.js +110 -0
  388. package/dist/runtime/modules/world/runtime/affordance/WorldAffordances.js +130 -0
  389. package/dist/runtime/modules/world/runtime/behavior/BehaviorCompiler.js +79 -0
  390. package/dist/runtime/modules/world/runtime/behavior/ProjectStateMachine.js +195 -0
  391. package/dist/runtime/modules/world/runtime/behavior/RuleGraph.js +70 -0
  392. package/dist/runtime/modules/world/runtime/behavior/RuleRuntime.js +115 -0
  393. package/dist/runtime/modules/world/runtime/graph/SceneGraph.js +390 -0
  394. package/dist/runtime/modules/world/runtime/interaction/ArticulationRuntime.js +214 -0
  395. package/dist/runtime/modules/world/runtime/interaction/CarryCapability.js +65 -0
  396. package/dist/runtime/modules/world/runtime/interaction/CarryRuntime.js +244 -0
  397. package/dist/runtime/modules/world/runtime/interaction/InteractionApproach.js +147 -0
  398. package/dist/runtime/modules/world/runtime/interaction/InteractionContract.js +57 -0
  399. package/dist/runtime/modules/world/runtime/interaction/ManipulationActions.js +7 -0
  400. package/dist/runtime/modules/world/runtime/interaction/NativePhysicalTarget.js +31 -0
  401. package/dist/runtime/modules/world/runtime/interaction/RecoveryRuntime.js +123 -0
  402. package/dist/runtime/modules/world/runtime/interaction/SettleRuntime.js +134 -0
  403. package/dist/runtime/modules/world/runtime/semantic/NativePhysicsState.js +89 -0
  404. package/dist/runtime/modules/world/runtime/semantic/SemanticWorldView.js +129 -0
  405. package/dist/runtime/modules/world/runtime/simulation/SimulationClock.js +89 -0
  406. package/dist/runtime/modules/world/runtime/simulation/SimulationSession.js +104 -0
  407. package/dist/runtime/modules/world/runtime/simulation/ThermalSystem.js +269 -0
  408. package/dist/runtime/modules/world/runtime/simulation/WorldTimeline.js +110 -0
  409. package/dist/runtime/modules/world/runtime/spatial/SpatialSnapshot.js +56 -0
  410. package/dist/runtime/modules/world/runtime/spatial/VisualMeshBounds.js +41 -0
  411. package/dist/runtime/modules/world/runtime/systems/AudioSystem.js +306 -0
  412. package/dist/runtime/modules/world/runtime/systems/Instrument.js +39 -0
  413. package/dist/runtime/modules/world/runtime/systems/InteractionSystem.js +806 -0
  414. package/dist/runtime/modules/world/runtime/systems/LocomotionSystem.js +281 -0
  415. package/dist/runtime/modules/world/runtime/systems/NavigationSystem.js +561 -0
  416. package/dist/runtime/modules/world/runtime/systems/PhysicsSystem.js +1752 -0
  417. package/dist/runtime/modules/world/runtime/systems/RenderingSystem.js +527 -0
  418. package/dist/runtime/modules/world/runtime/systems/SpatialSystem.js +402 -0
  419. package/dist/runtime/modules/world/spec/WorldIR.js +165 -0
  420. package/dist/runtime/modules/world/spec/WorldIRToolSchema.js +86 -0
  421. package/dist/runtime/modules/world/spec/WorldPlannerProposal.js +51 -0
  422. package/dist/runtime/modules/world/spec/WorldRevision.js +231 -0
  423. package/dist/runtime/modules/world/spec/WorldSpec.js +86 -0
  424. package/dist/runtime/modules/world/tasks.jsonl +530 -0
  425. package/dist/runtime/modules/world/verification/ArticulationVerifier.js +254 -0
  426. package/dist/runtime/modules/world/verification/Finding.js +105 -0
  427. package/dist/runtime/modules/world/verification/InteractionEvidence.js +73 -0
  428. package/dist/runtime/modules/world/verification/RepairEngine.js +49 -0
  429. package/dist/runtime/modules/world/verification/VisualLayoutAcceptance.js +58 -0
  430. package/dist/runtime/modules/world/verification/WorldAcceptance.js +176 -0
  431. package/dist/runtime/modules/world/verification/WorldValidator.js +67 -0
  432. package/dist/runtime/package-lock.json +16071 -0
  433. package/dist/runtime/package.json +106 -0
  434. package/dist/runtime/public/assets/cabinet.glb +0 -0
  435. package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_diff_1k.jpg +0 -0
  436. package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_nor_gl_1k.jpg +0 -0
  437. package/dist/runtime/public/assets/grand-urban-block/concrete_pavement_diff_1k.jpg +0 -0
  438. package/dist/runtime/public/assets/grand-urban-block/urban_street_01_1k.hdr +0 -0
  439. package/dist/runtime/public/assets/monument-hall/marble_diff_1k.jpg +0 -0
  440. package/dist/runtime/public/assets/monument-hall/marble_nor_gl_1k.jpg +0 -0
  441. package/dist/runtime/public/assets/monument-hall/marble_rough_1k.jpg +0 -0
  442. package/dist/runtime/public/assets/monument-hall/solitude_interior_1k.hdr +0 -0
  443. package/dist/runtime/public/assets/ruined-courtyard/courtyard_1k.hdr +0 -0
  444. package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_diff_1k.jpg +0 -0
  445. package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_nor_gl_1k.jpg +0 -0
  446. package/dist/runtime/public/assets/ruined-courtyard/mossy_sandstone_diff_1k.jpg +0 -0
  447. package/dist/schema-DT7K9NjP.js +165 -0
  448. package/dist/schema-DT7K9NjP.js.map +1 -0
  449. package/dist/suzhouGarden-Y3hny8j6.js +6150 -0
  450. package/dist/suzhouGarden-Y3hny8j6.js.map +1 -0
  451. package/dist/version-CHc-i8ch.js +5 -0
  452. package/dist/version-CHc-i8ch.js.map +1 -0
  453. package/dist/woodlandWorkshop-DsScU-cx.js +483 -0
  454. package/dist/woodlandWorkshop-DsScU-cx.js.map +1 -0
  455. package/dist/yuanmingyuan-DsFnPzzR.js +4955 -0
  456. package/dist/yuanmingyuan-DsFnPzzR.js.map +1 -0
  457. package/package.json +75 -4
@@ -0,0 +1,806 @@
1
+ import * as THREE from 'three';
2
+ import { ensureBoundsTrees } from '../../rendering/spatial/ThreeBvhRuntime.js';
3
+ import { EventBus } from '../../../foundation/EventBus.js';
4
+ import { ObjectStore } from './ObjectStore.js';
5
+ import { PhysicsSystem } from './systems/PhysicsSystem.js';
6
+ import { RapierPhysicsBackend } from '../../physics/RapierPhysicsBackend.js';
7
+ import { InteractionSystem } from './systems/InteractionSystem.js';
8
+ import { SpatialSystem } from './systems/SpatialSystem.js';
9
+ import { NavigationSystem } from './systems/NavigationSystem.js';
10
+ import { RecastNavigationBackend } from '../../navigation/RecastNavigationBackend.js';
11
+ import { LocomotionSystem } from './systems/LocomotionSystem.js';
12
+ import { SceneSerializer } from './SceneSerializer.js';
13
+ import { ScenePresentation } from './ScenePresentation.js';
14
+ import { nativePhysicsBindings,prepareNativePhysics } from './NativePhysicsSnapshot.js';
15
+ import { CommandHistory } from './CommandHistory.js';
16
+ import { SceneGraph } from './graph/SceneGraph.js';
17
+ import { PolicyEngine } from '../../../foundation/PolicyEngine.js';
18
+ import { TraceRecorder } from '../../../foundation/TraceRecorder.js';
19
+ import { WorldValidator } from '../verification/WorldValidator.js';
20
+ import { RepairEngine } from '../verification/RepairEngine.js';
21
+ import { disposeObject3D } from '../../rendering/disposeObject3D.js';
22
+ import { RuleRuntime } from './behavior/RuleRuntime.js';
23
+ import { clearInteractionEvidenceForTarget } from '../verification/InteractionEvidence.js';
24
+ import { captureWorldAuthority, restoreWorldAuthority } from './WorldAuthority.js';
25
+ import { WorldTimeline } from './simulation/WorldTimeline.js';
26
+ import { SimulationSession } from './simulation/SimulationSession.js';
27
+ import { ThermalSystem } from './simulation/ThermalSystem.js';
28
+ import { WorldAffordances } from './affordance/WorldAffordances.js';
29
+ import { physicsManifestForUniformScale, scalesEqual, uniformScaleValue } from './ObjectTransform.js';
30
+ import { WorldObservation } from './WorldObservation.js';
31
+ import { WorldQueries } from './WorldQueries.js';
32
+ import { WorldCommands } from './WorldCommands.js';
33
+ import { WorldRecovery } from './WorldRecovery.js';
34
+ import { ProjectCapabilities } from './ProjectCapabilities.js';
35
+ import { AudioSystem } from './systems/AudioSystem.js';
36
+ import { SemanticWorldView } from './semantic/SemanticWorldView.js';
37
+ import { EntityCapabilityRegistry } from './EntityCapabilityRegistry.js';
38
+ import { RUNTIME_VERSION } from '../../../foundation/version.js';
39
+
40
+ const mutationResultCommitted=(result)=>!(
41
+ result?.committed===false ||
42
+ result?.rolledBack===true ||
43
+ result?.recompile?.committed===false
44
+ );
45
+
46
+ const sameSnapshot = (left, right) => JSON.stringify(left) === JSON.stringify(right);
47
+
48
+ const batchOwners = new WeakMap();
49
+ const switchOwners = new WeakMap();
50
+
51
+ function assertWorldWritable(runtime, batch) {
52
+ if (runtime.disposed) throw Object.assign(new Error('WORLD_RUNTIME_DISPOSED'),{code:'WORLD_RUNTIME_DISPOSED'});
53
+ if (runtime.writesFrozen || (batchOwners.has(runtime) && runtime.mutationOwner === 'scene:batch' && batchOwners.get(runtime) !== batch)) throw Object.assign(new Error('WORLD_MUTATION_BUSY'), {code:'WORLD_MUTATION_BUSY'});
54
+ if (runtime.faultCode) throw Object.assign(new Error('PROJECT_RUNTIME_QUARANTINED'), { code:'PROJECT_RUNTIME_QUARANTINED', cause:runtime.faultCode });
55
+ }
56
+
57
+ function quarantineWorld(runtime, code) {
58
+ runtime.faultCode ??= code;
59
+ runtime.ready = false;
60
+ runtime.simulation?.pause();
61
+ }
62
+
63
+ function beginWorldWrite(runtime, label, ruleCascadeDepth = 0, batch) {
64
+ assertWorldWritable(runtime, batch);
65
+ const nested = batch && ((batchOwners.get(runtime) === batch && runtime.mutationOwner === 'scene:batch') || (switchOwners.get(runtime) === batch && runtime.mutationOwner === 'world:switch'));
66
+ if ((batch && !nested) || (runtime.mutationOwner && !nested) || runtime.history?.suspended || runtime.history?.pending) {
67
+ const error = new Error(`World mutation already in progress: ${runtime.mutationOwner || 'history'}`);
68
+ error.code = 'WORLD_MUTATION_BUSY';
69
+ throw error;
70
+ }
71
+ runtime.mutationOwner = label;
72
+ runtime.ruleRuntime?.beginTransaction(ruleCascadeDepth);
73
+ }
74
+
75
+ function endWorldWrite(runtime, committed, batch) {
76
+ runtime.mutationOwner = batch ? (switchOwners.get(runtime)===batch ? 'world:switch' : 'scene:batch') : null;
77
+ runtime.ruleRuntime?.endTransaction(committed);
78
+ }
79
+
80
+ async function rollbackMutation(runtime, before, authority, physics) {
81
+ // A failed validation must not destroy an unchanged simulation.
82
+ let changed = true;
83
+ try { changed = !sameSnapshot(runtime.snapshot(), before); } catch { /* Restore an unreadable world. */ }
84
+ if (changed) await runtime.restoreSnapshot(before);
85
+ if (physics && (changed || !sameSnapshot(runtime.physics.captureState(), physics))) {
86
+ runtime.physics.restoreState(physics);
87
+ runtime.sceneGraph?.invalidate();
88
+ }
89
+ if (!sameSnapshot(captureWorldAuthority(runtime), authority)) restoreWorldAuthority(runtime, authority);
90
+ }
91
+
92
+ export class WorldRuntime {
93
+ constructor({ environmentFactory, assetModule, audioListener = null, audioThree = THREE, physicsFactory = () => new PhysicsSystem({ backend:new RapierPhysicsBackend() }), navigationBackendFactory = () => new RecastNavigationBackend() } = {}) {
94
+ const assetMethods=['getManifest','hasAsset','assertCompatibleManifest','instantiate'];
95
+ if (
96
+ !assetModule?.registry || !assetModule?.loader || !assetModule?.catalog || !assetModule?.compiledStore ||
97
+ assetMethods.some((name)=>typeof assetModule[name]!=='function')
98
+ ) {
99
+ throw new TypeError('WorldRuntime requires a complete AssetModule boundary');
100
+ }
101
+ if (typeof physicsFactory !== 'function') throw new TypeError('WorldRuntime physicsFactory must be a function');
102
+ if (typeof navigationBackendFactory !== 'function') throw new TypeError('WorldRuntime navigationBackendFactory must be a function');
103
+ this.version = RUNTIME_VERSION;
104
+ this.revision = 0;
105
+ this.ready = false;
106
+ this.restoring = false;
107
+ this.affordances = new WorldAffordances(this);
108
+ this.environmentFactory = environmentFactory; this.events = new EventBus(); this.mutationOwner = null;
109
+ this.policy = new PolicyEngine(); this.trace = new TraceRecorder({ events: this.events });
110
+ this.assetModule = assetModule;
111
+ this.observation = new WorldObservation(this);
112
+ this.queries = new WorldQueries(this);
113
+ this.commands = new WorldCommands(this);
114
+ this.recovery = new WorldRecovery(this);
115
+ this.physicsFactory = physicsFactory;
116
+ this.navigationBackendFactory = navigationBackendFactory;
117
+ this.scene = new THREE.Scene();
118
+ this.presentation = new ScenePresentation(this.scene,(state,camera)=>{
119
+ this.rendering?.setPresentation?.(state,camera);
120
+ this.events.emit('scene.presentation.changed',{presentation:state});
121
+ });
122
+ this.rendering = null;
123
+ this.ruleRuntime = new RuleRuntime(this); this.serializer = new SceneSerializer(); this.store = new ObjectStore(); this.entities = new EntityCapabilityRegistry({ events:this.events }); this.physics = physicsFactory(); this.navigation = null;
124
+ this.projectCapabilities = new ProjectCapabilities(this);
125
+ this.audio = audioListener ? new AudioSystem({ entities: this.entities, listener: audioListener, three: audioThree }) : null;
126
+ this.semantic = new SemanticWorldView(this);
127
+ this.thermal = new ThermalSystem({physics:this.physics,
128
+ isActive:id=>this.store.has(id) && this.store.get(id).active!==false});
129
+ this.timeline = new WorldTimeline(this);
130
+ this.events.on('simulation.restored',({tick,previousTick})=>this.timeline.rebase(tick-previousTick));
131
+ this.events.on('simulation.reset',()=>this.timeline.reset());
132
+ this.simulation = new SimulationSession({
133
+ fixedDt:1/60,
134
+ executeStep:(dt)=>this.stepSimulation(dt),
135
+ afterStep:({tick})=>this.timeline.advance(tick),
136
+ snapshotWorld:()=>this.snapshot(),
137
+ restoreWorld:(scene)=>this.restore(scene),
138
+ events:this.events
139
+ });
140
+ }
141
+ quarantine(code = 'PROJECT_RUNTIME_QUARANTINED') {
142
+ quarantineWorld(this, code);
143
+ }
144
+
145
+ assertWritable(batch) {
146
+ assertWorldWritable(this, batch);
147
+ }
148
+
149
+ attachRendering(rendering) {
150
+ if (!rendering || typeof rendering.init !== 'function' || typeof rendering.dispose !== 'function') {
151
+ throw new TypeError('WorldRuntime rendering must provide init() and dispose()');
152
+ }
153
+ if (rendering.scene && rendering.scene !== this.scene) {
154
+ throw new TypeError('WorldRuntime rendering must use the Runtime scene');
155
+ }
156
+ if (this.rendering && this.rendering !== rendering) {
157
+ const error = new Error('WorldRuntime rendering is already attached');
158
+ error.code = 'WORLD_RENDERING_ALREADY_ATTACHED';
159
+ throw error;
160
+ }
161
+ this.rendering = rendering;
162
+ return rendering;
163
+ }
164
+ async init() {
165
+ await this.assetModule.hydrate?.();
166
+ this.events.emit('runtime.init.phase',{stage:'assets-ready'});
167
+ await this.physics.init();
168
+ this.events.emit('runtime.init.phase',{stage:'physics-ready'});
169
+ if (this.rendering) {
170
+ await this.rendering.init();
171
+ this.events.emit('runtime.init.phase',{stage:'renderer-ready'});
172
+ if (this.rendering.renderer) this.assetModule.configureRenderer?.(this.rendering.renderer);
173
+ }
174
+ this.spatial = new SpatialSystem({ store:this.store,entities:this.entities,physics:this.physics });
175
+ this.sceneGraph = new SceneGraph({ store: this.store, spatial: this.spatial, events: this.events });
176
+ this.history = new CommandHistory({
177
+ onCommit: () => { this.revision++; },
178
+ apply: (scene, physics) => this.restoreSnapshot(scene, physics),
179
+ runExclusive: (operation) => this.exclusiveMutation('history:restore', operation),
180
+ events: this.events
181
+ });
182
+ this.validator = new WorldValidator(this); this.repair = new RepairEngine(this);
183
+ await this.addEnvironment();
184
+ this.events.emit('runtime.init.phase',{stage:'environment-ready'});
185
+ this.createEnvironmentSystems();
186
+ this.ruleRuntime.start();
187
+ this.ready = true;
188
+ const rendering=this.rendering?.diagnostics?.() || null; this.trace.emit('runtime.ready', { version: this.version, rendering }); this.events.emit('runtime.ready', { rendering }); return this;
189
+ }
190
+ async addEnvironment() {
191
+ if (!this.environmentFactory) throw new Error('WorldRuntime requires an environmentFactory');
192
+ const environment = await this.environmentFactory({ scene:this.scene, renderer:this.rendering?.renderer || null });
193
+ this.installEnvironment(environment);
194
+ return environment;
195
+ }
196
+
197
+ installEnvironment(environment) {
198
+ if (!environment?.root?.isObject3D || !Array.isArray(environment.colliders)) {
199
+ const error=new TypeError('Runtime environment requires root Object3D and colliders');
200
+ error.code='ENVIRONMENT_INVALID';
201
+ throw error;
202
+ }
203
+ this.environment = environment;
204
+ this.environmentFloor = environment.floor || null;
205
+ this.sceneGraph?.setEnvironmentSemantics(environment.id, environment.semantics);
206
+ this.scene.add(environment.root);
207
+ this.rendering?.applyEnvironment(environment);
208
+ this.physics.addEnvironment(environment.colliders,{id:environment.id});
209
+ const characterOptions = environment.physics?.characterController || environment.characterController || null;
210
+ if (characterOptions && typeof this.physics.setCharacterControllerOptions === 'function') {
211
+ this.physics.setCharacterControllerOptions(characterOptions);
212
+ }
213
+ return environment;
214
+ }
215
+
216
+ invalidateNavigationForObject(id, reason = 'object-transformed') {
217
+ if (!this.navigation || !id || !this.store.has(id)) return false;
218
+ const record=this.store.get(id);
219
+ return record.active===false ? false : this.navigation.invalidateIfStatic(record, reason);
220
+ }
221
+
222
+ createEnvironmentSystems() {
223
+ const environmentNavConfig = this.environment?.navigation || this.environment?.navigationConfig || {};
224
+ this.navigation = new NavigationSystem({
225
+ store:this.store,physics:this.physics,environmentRoots:this.environment.navigationColliders!=null?[]:[this.environment.navigationRoot || this.environment.root],
226
+ nativeEnvironmentColliders:this.environment.navigationColliders??null,
227
+ backend:this.navigationBackendFactory(),
228
+ config: environmentNavConfig
229
+ });
230
+ this.locomotion = new LocomotionSystem({ store:this.store, physics:this.physics, navigation:this.navigation, events:this.events,
231
+ nativeHeldBy:actor=>{const id=this.interactions?.heldByAgent(actor);return this.entities.get(id)?.source==='native'?id:null;} });
232
+ this.interactions = new InteractionSystem({
233
+ store:this.store,entities:this.entities,physics:this.physics,spatial:this.spatial,navigation:this.navigation,locomotion:this.locomotion,events:this.events,
234
+ onObjectTransform:(id,reason)=>this.invalidateNavigationForObject(id,reason)
235
+ });
236
+ return this.navigation;
237
+ }
238
+
239
+ teardownEnvironmentSystems(reason='ENVIRONMENT_REPLACED') {
240
+ this.affordances?.cancel(reason);
241
+ this.interactions?.cancelPending(reason);
242
+ this.locomotion?.cancelAll(reason);
243
+ this.navigation?.dispose();
244
+ this.interactions=null;
245
+ this.locomotion=null;
246
+ this.navigation=null;
247
+ }
248
+
249
+ async replaceEnvironment(environment,{disposePrevious=true,reason='environment-replaced',notify=true}={}) {
250
+ assertWorldWritable(this);
251
+ if (this.store.size) {
252
+ const error=new Error('Environment replacement requires an empty ObjectStore');
253
+ error.code='ENVIRONMENT_REPLACE_REQUIRES_EMPTY_WORLD';
254
+ throw error;
255
+ }
256
+ if (!environment?.root?.isObject3D || !Array.isArray(environment.colliders)) {
257
+ const error=new TypeError('Runtime environment requires root Object3D and colliders');
258
+ error.code='ENVIRONMENT_INVALID';
259
+ throw error;
260
+ }
261
+ const previous=this.environment || null;
262
+ if(!this.restoring&&previous!==environment&&nativePhysicsBindings(this).size)throw Object.assign(new Error('NATIVE_PHYSICS_ENVIRONMENT_REPLACE_UNSUPPORTED'),{code:'NATIVE_PHYSICS_ENVIRONMENT_REPLACE_UNSUPPORTED'});
263
+ if (previous===environment) return {status:'environment-ready',environmentId:environment.id || null,previousEnvironmentId:previous?.id || null,reused:true};
264
+ this.teardownEnvironmentSystems('ENVIRONMENT_REPLACED');
265
+ if (previous?.root?.parent===this.scene) this.scene.remove(previous.root);
266
+ this.physics.resetWorld();
267
+ try {
268
+ this.installEnvironment(environment);
269
+ this.createEnvironmentSystems();
270
+ this.sceneGraph?.changed();
271
+ this.timeline.reset();
272
+ this.preservedSceneExtensions={};
273
+ this.audio?.restoreMix({});
274
+ if(notify) this.events?.emit('environment.replaced',{id:environment.id || null,previousId:previous?.id || null,reason},{isolateListeners:true});
275
+ try { if (disposePrevious) previous?.dispose?.(); } catch(error) { console.warn("Previous environment disposal failed",error); }
276
+ return {status:'environment-ready',environmentId:environment.id || null,previousEnvironmentId:previous?.id || null,reused:false};
277
+ } catch (error) {
278
+ let rollbackError=null;
279
+ try {
280
+ if (environment.root?.parent===this.scene) this.scene.remove(environment.root);
281
+ this.teardownEnvironmentSystems('ENVIRONMENT_REPLACE_ROLLBACK');
282
+ this.physics.resetWorld();
283
+ if (previous) {
284
+ this.installEnvironment(previous);
285
+ this.createEnvironmentSystems();
286
+ this.sceneGraph?.changed();
287
+ } else {
288
+ this.environment=null;
289
+ this.environmentFloor=null;
290
+ this.sceneGraph?.setEnvironmentSemantics('environment',null);
291
+ }
292
+ } catch (cause) { rollbackError=cause; }
293
+ if (rollbackError) {
294
+ const failure=new AggregateError([error,rollbackError],'Environment replacement rollback failed',{cause:error});
295
+ failure.code='ENVIRONMENT_REPLACE_ROLLBACK_FAILED';
296
+ quarantineWorld(this, failure.code);
297
+ failure.rollbackError=rollbackError;
298
+ throw failure;
299
+ }
300
+ throw error;
301
+ }
302
+ }
303
+ async spawn(assetId, { position = [0, 0, 0], quaternion = [0, 0, 0, 1], scale = 1, id = `${assetId}_${crypto.randomUUID()}`, initialState = null, active = true, signal } = {}) {
304
+ assertWorldWritable(this);
305
+ if (this.store.has(id)) throw new Error('Duplicate object id: ' + id);
306
+ const uniformScale = uniformScaleValue(scale);
307
+ if (!Array.isArray(position) || position.length !== 3 || !position.every(Number.isFinite)) {
308
+ const error=new TypeError('Object position requires finite vec3'); error.code='OBJECT_POSITION_INVALID'; throw error;
309
+ }
310
+ if (!Array.isArray(quaternion) || quaternion.length !== 4 || !quaternion.every(Number.isFinite)) {
311
+ const error=new TypeError('Object quaternion requires finite vec4'); error.code='OBJECT_ROTATION_INVALID'; throw error;
312
+ }
313
+ const sourceEnvironment=this.environment;
314
+ const { object, manifest } = active ? await this.assetModule.instantiate(assetId, { signal })
315
+ : { object: new THREE.Object3D(), manifest: this.assetModule.getManifest(assetId) };
316
+ let stored = false;
317
+ let entityRegistered = false;
318
+ let attached = false;
319
+ try {
320
+ signal?.throwIfAborted();
321
+ if(this.disposed || sourceEnvironment!==this.environment) throw Object.assign(new Error('WORLD_RUNTIME_CHANGED'),{code:'WORLD_RUNTIME_CHANGED'});
322
+ const physicsManifest = physicsManifestForUniformScale(manifest,uniformScale);
323
+ object.position.fromArray(position);
324
+ object.quaternion.fromArray(quaternion).normalize();
325
+ object.scale.setScalar(uniformScale);
326
+ object.userData.instanceId = id;
327
+ ensureBoundsTrees(object);
328
+ assertWorldWritable(this);
329
+ if (this.store.has(id)) throw new Error('Duplicate object id: ' + id);
330
+ this.scene.add(object);
331
+ this.store.add(id, { id, assetId, object, manifest, state: {}, physicsScale:uniformScale, active });
332
+ stored = true;
333
+ this.entities?.register({ id, object, assetId, manifest, state:this.store.get(id).state,
334
+ source:'runtime', phase:'visual-mounted', transformAuthority:manifest.physics?.body === 'dynamic' ? 'physics' : manifest.physics?.body === 'kinematic' ? 'kinematic' : 'static',
335
+ capabilities:['semantic', ...(manifest.capabilityLevel !== 'visual' ? ['interaction'] : []), ...(manifest.capabilityLevel !== 'visual' && manifest.physics ? ['physics'] : []), ...(manifest.actions?.length ? ['articulation'] : [])] });
336
+ entityRegistered = Boolean(this.entities);
337
+ if (entityRegistered) this.entities.setPhase(id, 'semantic-registered');
338
+ if (active && manifest.capabilityLevel !== 'visual') {
339
+ this.physics.addObject(id, physicsManifest, object);
340
+ attached = true;
341
+ if (entityRegistered) this.entities.setPhase(id, 'physics-registered');
342
+ }
343
+ this.thermal?.register?.(id,manifest.simulation,{scale:uniformScale});
344
+ clearInteractionEvidenceForTarget(this,id);
345
+ if (initialState && Object.keys(initialState).length) this.restoreObjectState(id, initialState);
346
+ this.invalidateNavigationForObject(id, 'object.spawned');
347
+ this.entities?.setPhase(id, active ? 'active' : 'inactive');
348
+ if (active) this.sceneGraph?.changed(); else this.sceneGraph?.invalidate();
349
+ this.events.emit('object.spawned', { id, assetId, position });
350
+ return id;
351
+ } catch (error) {
352
+ // 只撤销本次调用取得的资源:attach 未成功时不得触碰同名旧对象的物理实体。
353
+ if (attached) this.physics.removeObject(id);
354
+ if (stored) this.thermal?.remove?.(id);
355
+ if (stored) this.store.delete(id);
356
+ if (entityRegistered) this.entities.unregister(id, { reason:'spawn-failed' });
357
+ this.scene.remove?.(object);
358
+ disposeObject3D(object);
359
+ throw error;
360
+ }
361
+ }
362
+ async setObjectActive(id, active, { signal } = {}) {
363
+ assertWorldWritable(this);
364
+ const record = this.store.get(id);
365
+ if ((record.active !== false) === active) return;
366
+ if (record.state?.heldBy || this.interactions?.isHeld?.(id)) throw new Error('OBJECT_HELD');
367
+ const old = record.object;
368
+ if (!active) {
369
+ this.audio?.unregisterEmitter(id);
370
+ record.dormantArticulation = this.physics.captureArticulationPose(id);
371
+ this.locomotion?.cancel(id, 'OBJECT_DEACTIVATED');
372
+ this.physics.removeObject(id);
373
+ this.scene.remove(old);
374
+ const placeholder = new THREE.Object3D();
375
+ placeholder.position.copy(old.position); placeholder.quaternion.copy(old.quaternion); placeholder.scale.copy(old.scale);
376
+ record.object = placeholder; record.active = false;
377
+ this.entities?.setObject(id, placeholder);
378
+ disposeObject3D(old);
379
+ } else {
380
+ const { object } = await this.assetModule.instantiate(record.assetId, { signal });
381
+ if(!this.store.has(id) || this.store.get(id)!==record || record.object!==old){
382
+ disposeObject3D(object);
383
+ throw Object.assign(new Error('WORLD_RUNTIME_CHANGED'),{code:'WORLD_RUNTIME_CHANGED'});
384
+ }
385
+ try {
386
+ assertWorldWritable(this);
387
+ if (signal?.aborted) throw new Error('ASSET_CANCELLED');
388
+ object.position.copy(old.position); object.quaternion.copy(old.quaternion); object.scale.copy(old.scale);
389
+ object.userData.instanceId = id; ensureBoundsTrees(object); this.scene.add(object);
390
+ if (record.manifest.capabilityLevel !== 'visual') this.physics.addObject(id, physicsManifestForUniformScale(record.manifest, old.scale.x), object);
391
+ record.object = object; record.active = true;
392
+ this.entities?.setObject(id, object);
393
+ this.restoreObjectState(id, record.state);
394
+ if (record.dormantArticulation?.length) this.physics.restoreArticulationPose(id, record.dormantArticulation);
395
+ this.scene.remove(old);
396
+ } catch (error) {
397
+ this.physics.removeObject(id); this.scene.remove(object); disposeObject3D(object);
398
+ record.object = old; record.active = false; this.entities?.setObject(id, old); throw error;
399
+ }
400
+ }
401
+ // Dynamic/kinematic bodies are synchronized by the query-time obstacle path.
402
+ // A fixed body must invalidate on both activation and deactivation.
403
+ this.navigation?.invalidateIfStatic(record,'entity-activation'); this.sceneGraph?.invalidate();
404
+ this.entities?.setPhase(id,active ? 'active' : 'inactive');
405
+ this.events.emit('object.activation', { id, active });
406
+ }
407
+
408
+ applyObjectTransform(id,{position=null,quaternion=null,rotationDegrees=null,scale=null}={}, {source='runtime'}={}) {
409
+ assertWorldWritable(this);
410
+ const record=this.store.get(id);
411
+ const object=record.object;
412
+ const previous={
413
+ position:object.position.toArray(),
414
+ quaternion:object.quaternion.toArray(),
415
+ scale:uniformScaleValue(object.scale.toArray()),
416
+ physicsScale:Number.isFinite(record.physicsScale)?record.physicsScale:1
417
+ };
418
+ if (position!=null && (!Array.isArray(position) || position.length!==3 || !position.every(Number.isFinite))) {
419
+ const error=new TypeError('Object position requires finite vec3'); error.code='OBJECT_POSITION_INVALID'; throw error;
420
+ }
421
+ const nextPosition=position==null?previous.position:[...position];
422
+ if (quaternion!=null && (!Array.isArray(quaternion) || quaternion.length!==4 || !quaternion.every(Number.isFinite))) {
423
+ const error=new TypeError('Object quaternion requires finite vec4'); error.code='OBJECT_ROTATION_INVALID'; throw error;
424
+ }
425
+ let nextQuaternion=quaternion==null?[...previous.quaternion]:[...quaternion];
426
+ if (rotationDegrees!=null) {
427
+ if (!Array.isArray(rotationDegrees) || rotationDegrees.length!==3 || !rotationDegrees.every(Number.isFinite)) {
428
+ const error=new TypeError('Object rotation requires finite degree vec3'); error.code='OBJECT_ROTATION_INVALID'; throw error;
429
+ }
430
+ const euler=new THREE.Euler(...rotationDegrees.map(THREE.MathUtils.degToRad),'XYZ');
431
+ nextQuaternion=new THREE.Quaternion().setFromEuler(euler).toArray();
432
+ }
433
+ const nextScale=scale==null?previous.scale:uniformScaleValue(scale);
434
+ this.thermal?.assertScale?.(id,nextScale);
435
+ const scaleChanged=record.manifest.capabilityLevel !== 'visual' && !scalesEqual(nextScale,previous.physicsScale);
436
+ if (scaleChanged && record.state?.heldBy) {
437
+ const error=new Error(`Cannot scale held object: ${id}`); error.code='OBJECT_SCALE_HELD_UNSUPPORTED'; throw error;
438
+ }
439
+ const nextPhysicsManifest=scaleChanged?physicsManifestForUniformScale(record.manifest,nextScale):null;
440
+ const previousPhysicsManifest=scaleChanged?physicsManifestForUniformScale(record.manifest,previous.physicsScale):null;
441
+
442
+ object.position.fromArray(nextPosition);
443
+ object.quaternion.fromArray(nextQuaternion).normalize();
444
+ object.scale.setScalar(nextScale);
445
+ object.updateMatrixWorld(true);
446
+ try {
447
+ if (record.active === false) { record.physicsScale = nextScale; }
448
+ else if (scaleChanged) {
449
+ this.physics.removeObject(id);
450
+ this.physics.addObject(id,nextPhysicsManifest,object);
451
+ record.physicsScale=nextScale;
452
+ } else this.physics.syncTransform(id,object);
453
+ } catch (error) {
454
+ object.position.fromArray(previous.position);
455
+ object.quaternion.fromArray(previous.quaternion);
456
+ object.scale.setScalar(previous.scale);
457
+ object.updateMatrixWorld(true);
458
+ if (scaleChanged) {
459
+ try { this.physics.removeObject(id); } catch {}
460
+ this.physics.addObject(id,previousPhysicsManifest,object);
461
+ record.physicsScale=previous.physicsScale;
462
+ } else this.physics.syncTransform(id,object);
463
+ throw error;
464
+ }
465
+ this.thermal?.setScale?.(id,nextScale);
466
+ this.invalidateNavigationForObject(id,'object.transformed');
467
+ this.sceneGraph?.invalidate?.(id);
468
+ this.events.emit('object.transformed',{
469
+ id,source,position:[...nextPosition],quaternion:[...nextQuaternion],scale:nextScale,physicsRebuilt:scaleChanged
470
+ });
471
+ return {status:'object-transformed',id,position:[...nextPosition],quaternion:[...nextQuaternion],scale:nextScale,physicsRebuilt:scaleChanged};
472
+ }
473
+
474
+ snapshot() {
475
+ const scene = this.serialize({ name: 'History Snapshot', includeRelations: false, nativeIdentity:true });
476
+ delete scene.metadata.savedAt;
477
+ return scene;
478
+ }
479
+
480
+ ownsWorldSwitch(token) {
481
+ return token!=null && switchOwners.get(this)===token && this.mutationOwner==='world:switch';
482
+ }
483
+
484
+ async withWorldSwitch(operation) {
485
+ return this.exclusiveMutation('world:switch',async()=>{
486
+ const token={};
487
+ switchOwners.set(this,token);
488
+ try { return await operation(token); }
489
+ finally { switchOwners.delete(this); }
490
+ });
491
+ }
492
+
493
+ async withEditBatch(operation) {
494
+ beginWorldWrite(this,'scene:batch');
495
+ const batch = {};
496
+ batchOwners.set(this,batch);
497
+ try { return await operation(batch); }
498
+ finally {
499
+ batchOwners.delete(this);
500
+ endWorldWrite(this,true);
501
+ }
502
+ }
503
+
504
+ freezeWrites() {
505
+ beginWorldWrite(this,'project:switch');
506
+ this.writesFrozen = true;
507
+ let released = false;
508
+ return () => {
509
+ if (released) return;
510
+ released = true;
511
+ this.writesFrozen = false;
512
+ endWorldWrite(this,false);
513
+ };
514
+ }
515
+
516
+ async exclusiveMutation(label, operation, batch) {
517
+ beginWorldWrite(this, label, 0, batch);
518
+ let committed = false;
519
+ try {
520
+ const result = await operation();
521
+ committed = mutationResultCommitted(result);
522
+ return result;
523
+ } finally { endWorldWrite(this, committed, batch); }
524
+ }
525
+
526
+ async mutate(label, operation, meta = {}, { batch = null, onSnapshot = null, transformOnly = false } = {}) {
527
+ beginWorldWrite(this, label, meta.ruleCascadeDepth, batch);
528
+ let committed = false;
529
+ try {
530
+ const authorityBefore = captureWorldAuthority(this);
531
+ const before = this.snapshot();
532
+ const physicsBefore = this.physics?.captureState?.();
533
+ if (!this.history.begin(label, before, physicsBefore)) {
534
+ const error = new Error('World history transaction unavailable');
535
+ error.code = 'WORLD_MUTATION_BUSY';
536
+ throw error;
537
+ }
538
+ let rollingBack = false;
539
+ try {
540
+ let result;
541
+ await this.sceneGraph.batch(async () => {
542
+ result = await operation();
543
+ if (mutationResultCommitted(result) && !transformOnly) this.sceneGraph.changed();
544
+ });
545
+ if (!mutationResultCommitted(result)) {
546
+ this.history.cancel();
547
+ rollingBack = true;
548
+ await rollbackMutation(this, before, authorityBefore, physicsBefore);
549
+ return result;
550
+ }
551
+ const after = this.snapshot();
552
+ this.history.commit(after, meta, this.physics?.captureState?.());
553
+ committed = true;
554
+ // Cache updates are advisory. Once committed, a cache callback error
555
+ // must never invoke rollback against an already recorded history entry.
556
+ try { onSnapshot?.(after); }
557
+ catch { /* The next mutation will take a fresh snapshot. */ }
558
+ return result;
559
+ } catch (error) {
560
+ this.history.cancel();
561
+ if (this.faultCode) throw error;
562
+ try {
563
+ if (rollingBack) throw error;
564
+ await rollbackMutation(this, before, authorityBefore, physicsBefore);
565
+ } catch (rollbackError) {
566
+ const failure = new AggregateError([error, rollbackError],
567
+ `World mutation rollback failed: ${label}`, { cause:error });
568
+ failure.code = 'WORLD_MUTATION_ROLLBACK_FAILED';
569
+ quarantineWorld(this, failure.code);
570
+ failure.rollbackError = rollbackError;
571
+ throw failure;
572
+ }
573
+ throw error;
574
+ }
575
+ } finally { endWorldWrite(this, committed, batch); }
576
+ }
577
+
578
+ beginMutation(label) {
579
+ if (this.history?.suspended || this.history?.pending || this.mutationOwner) return false;
580
+ beginWorldWrite(this, 'editor');
581
+ try {
582
+ if (this.history.begin(label, this.snapshot(), this.physics?.captureState?.())) return true;
583
+ endWorldWrite(this, false);
584
+ return false;
585
+ } catch (error) {
586
+ endWorldWrite(this, false);
587
+ throw error;
588
+ }
589
+ }
590
+
591
+ cancelEditorMutation() {
592
+ if (this.mutationOwner !== 'editor') return false;
593
+ this.history.cancel();
594
+ endWorldWrite(this, false);
595
+ return true;
596
+ }
597
+
598
+ commitMutation(meta = {}) {
599
+ assertWorldWritable(this);
600
+ if (this.history?.suspended || (this.mutationOwner && this.mutationOwner !== 'editor')) return false;
601
+ let committed = false;
602
+ try {
603
+ this.sceneGraph?.changed();
604
+ if (meta.id) this.invalidateNavigationForObject(meta.id, 'editor.transform');
605
+ const recorded = this.history.commit(this.snapshot(), meta, this.physics?.captureState?.());
606
+ committed = true;
607
+ return recorded;
608
+ } finally {
609
+ if (!committed) this.history.cancel();
610
+ if (this.mutationOwner === 'editor') endWorldWrite(this, committed);
611
+ }
612
+ }
613
+
614
+ async clearObjects({silent=false}={}) {
615
+ assertWorldWritable(this);
616
+ const ids = this.store.list().map(([id]) => id);
617
+ await this.sceneGraph.batch(async () => {
618
+ for (const id of ids) this.remove(id,{silent});
619
+ this.sceneGraph.changed();
620
+ });
621
+ this.timeline.reset();
622
+ if(!silent) this.events.emit('scene.cleared', { count: ids.length });
623
+ }
624
+
625
+ serialize(options) { return this.serializer.serialize(this, options); }
626
+ async installWorld({ snapshot, assetModule, environment }) {
627
+ this.serializer.validate(snapshot,this);
628
+ return this.exclusiveMutation('world:commit', async () => {
629
+ const previous = this.snapshot(), oldAssets = this.assetModule, oldEnvironment = this.environment;
630
+ if(previous.nativePhysics&&environment.id!==oldEnvironment.id)throw Object.assign(new Error('NATIVE_PHYSICS_ENVIRONMENT_MISMATCH'),{code:'NATIVE_PHYSICS_ENVIRONMENT_MISMATCH'});
631
+ if(previous.nativePhysics&&!snapshot.nativePhysics)snapshot={...snapshot,nativePhysics:previous.nativePhysics};
632
+ if(snapshot.nativePhysics)prepareNativePhysics(this,snapshot.nativePhysics,snapshot.objects);
633
+ const authority = captureWorldAuthority(this), physics = this.physics.captureState();
634
+ const running = this.simulation.running;
635
+ this.simulation.pause(); this.restoring = true; this.ruleRuntime.suspendEvents();
636
+ try {
637
+ await this.clearObjects({ silent: true });
638
+ await this.replaceEnvironment(environment, { disposePrevious: false, notify:false });
639
+ this.assetModule = assetModule;
640
+ await this.serializer.applyScene(this, snapshot);
641
+ this.history.clear();
642
+ } catch (error) {
643
+ try {
644
+ await this.clearObjects({ silent: true }); this.assetModule = oldAssets;
645
+ if (this.environment !== oldEnvironment) await this.replaceEnvironment(oldEnvironment, { disposePrevious: false, notify:false });
646
+ await this.serializer.applyScene(this, previous); this.physics.restoreState(physics); restoreWorldAuthority(this, authority);
647
+ } catch (rollbackError) {
648
+ this.quarantine('WORLD_COMMIT_ROLLBACK_FAILED');
649
+ throw Object.assign(new AggregateError([error, rollbackError], 'World commit rollback failed'), { code: 'WORLD_COMMIT_ROLLBACK_FAILED' });
650
+ }
651
+ throw error;
652
+ } finally {
653
+ this.restoring = false; this.ruleRuntime.resumeEvents(); if (running && !this.faultCode) this.simulation.play();
654
+ }
655
+ this.revision++;
656
+ if(oldEnvironment!==environment) {
657
+ this.events.emit('environment.replaced',{id:environment.id,previousId:oldEnvironment?.id,reason:'environment-replaced'},{isolateListeners:true});
658
+ try { oldEnvironment?.dispose?.(); }
659
+ catch(error) { console.warn('Previous environment disposal failed',error); }
660
+ }
661
+ this.events.emit('world.committed', { entities: this.store.size },{isolateListeners:true});
662
+ });
663
+ }
664
+ async restore(scene) {
665
+ return this.exclusiveMutation('scene:restore', async () => {
666
+ const result = await this.restoreSnapshot(scene);
667
+ this.revision++;
668
+ return result;
669
+ });
670
+ }
671
+
672
+ // Trusted rollback/history primitive. External imports must use restore().
673
+ async restoreSnapshot(scene, physics) {
674
+ assertWorldWritable(this);
675
+ if (!this.mutationOwner) return this.restore(scene);
676
+ if (this.restoring) {
677
+ const error = new Error('World restore already in progress');
678
+ error.code = 'WORLD_MUTATION_BUSY';
679
+ throw error;
680
+ }
681
+ const wasRunning = this.simulation?.running;
682
+ this.restoring = true;
683
+ this.simulation?.pause();
684
+ this.ruleRuntime?.suspendEvents();
685
+ try { return await this.serializer.restore(this, scene, physics); }
686
+ finally {
687
+ this.restoring = false;
688
+ this.ruleRuntime?.resumeEvents();
689
+ if (wasRunning && !this.faultCode) this.simulation.play();
690
+ }
691
+ }
692
+
693
+ loadRuleGraph(graph) { assertWorldWritable(this); return this.ruleRuntime.load(graph); }
694
+
695
+ applyStateTransition(id, stateKey, value, meta = {}) {
696
+ assertWorldWritable(this);
697
+ const record=this.store.get(id);
698
+ if(!record) { const error=new Error(`State target not found: ${id}`); error.code='STATE_TARGET_NOT_FOUND'; throw error; }
699
+ const key=String(stateKey||'').trim();
700
+ if(!key || key.includes('.') || key.startsWith('__')) { const error=new Error('Invalid state key'); error.code='STATE_KEY_INVALID'; throw error; }
701
+ if(value!==null && !['string','number','boolean'].includes(typeof value)) { const error=new TypeError('State value must be a JSON scalar'); error.code='STATE_VALUE_INVALID'; throw error; }
702
+ record.state ||= {};
703
+ if (Object.is(record.state[key], value)) {
704
+ return {status:'state-transition-applied',targetId:id,stateKey:key,value,changed:false};
705
+ }
706
+ record.state[key]=value;
707
+ this.sceneGraph?.changed();
708
+ this.events.emit('world.state-transition',{id,stateKey:key,value,meta});
709
+ return {status:'state-transition-applied',targetId:id,stateKey:key,value};
710
+ }
711
+
712
+ restoreObjectState(id, state = {}) {
713
+ assertWorldWritable(this);
714
+ const record = this.store.get(id);
715
+ record.state=structuredClone(state);
716
+ const entity=this.entities?.get(id);
717
+ if (entity) entity.state=record.state;
718
+ if (record.active === false) return;
719
+ if (record.state.navigation?.status === 'moving') record.state.navigation.status = 'interrupted';
720
+ const articulationTargets = Object.keys(state.partTargets || {}).length ? state.partTargets : (state.parts || {});
721
+ for (const [partName, action] of Object.entries(articulationTargets)) {
722
+ if (record.manifest.actions.includes(action)) this.interactions.setArticulationAction(id, action, { partName });
723
+ }
724
+ // 兼容 1.1.8 以前的 cabinet 状态。
725
+ if (state.door === 'open') this.interactions.setArticulationAction(id, 'open');
726
+ else if (state.door === 'closed') this.interactions.setArticulationAction(id, 'close');
727
+ }
728
+
729
+ remove(id,{silent=false,replacing=false}={}) {
730
+ assertWorldWritable(this);
731
+ const record = this.store.get(id);
732
+ this.events.emit('object.removing', { id });
733
+ this.locomotion?.cancel(id, 'OBJECT_REMOVED');
734
+ this.interactions?.beforeRemove(id,{silent});
735
+ this.invalidateNavigationForObject(id, 'object.removed');
736
+ this.audio?.unregisterEmitter(id);
737
+ this.thermal?.remove?.(id);
738
+ this.physics.removeObject(id);
739
+ this.scene.remove(record.object);
740
+ disposeObject3D(record.object);
741
+ this.store.delete(id);
742
+ this.entities?.unregister(id, { reason:'object-removed' });
743
+ clearInteractionEvidenceForTarget(this,id);
744
+ this.sceneGraph?.removeObject(id); this.sceneGraph?.changed();
745
+ if(!silent) this.events.emit('object.removed', { id, assetId: record.assetId, ...(replacing?{replacing:true}:{}) });
746
+ return true;
747
+ }
748
+
749
+ async duplicate(id) {
750
+ const record = this.store.get(id);
751
+ const p = record.object.position;
752
+ const duplicateId = `${record.assetId}_${crypto.randomUUID()}`;
753
+ await this.spawn(record.assetId, {
754
+ position:[p.x + 0.6,p.y,p.z + 0.6],
755
+ quaternion:record.object.quaternion.toArray(),
756
+ scale:uniformScaleValue(record.object.scale.toArray()),
757
+ id:duplicateId
758
+ });
759
+ this.events.emit('object.duplicated', { sourceId: id, id: duplicateId });
760
+ return duplicateId;
761
+ }
762
+
763
+ stepSimulation(dt) {
764
+ if (this.writesFrozen || switchOwners.has(this) || batchOwners.has(this) || this.restoring || this.faultCode) return false;
765
+ this.environment?.step?.(dt,{physics:this.physics,navigation:this.navigation});
766
+ this.affordances?.update(dt);
767
+ this.locomotion?.update(dt);
768
+ if (this.physics.step(dt, this.store)) this.sceneGraph.invalidate();
769
+ this.thermal?.step?.(dt);
770
+ this.interactions?.update(dt);
771
+ }
772
+ dispose() {
773
+ if (this.disposed) return;
774
+ this.disposed=true;
775
+ this.ready = false;
776
+ this.events?.emit?.('world.disposing');
777
+ this.timeline?.reset();
778
+ this.audio?.dispose();
779
+ this.projectCapabilities?.dispose();
780
+ this.thermal?.clear?.();
781
+ this.ruleRuntime?.stop();
782
+ this.affordances?.cancel('RUNTIME_DISPOSED');
783
+ this.interactions?.cancelPending('RUNTIME_DISPOSED');
784
+ for (const [id, record] of this.store.list()) {
785
+ this.physics.removeObject(id);
786
+ this.scene.remove(record.object);
787
+ disposeObject3D(record.object);
788
+ this.store.delete(id);
789
+ this.entities?.unregister(id, { reason:'runtime-disposed' });
790
+ }
791
+ this.sceneGraph.reset();
792
+ this.locomotion?.cancelAll();
793
+ this.locomotion = null;
794
+ this.environment?.dispose();
795
+ this.environment = null;
796
+ this.presentation?.dispose();
797
+ disposeObject3D(this.scene);
798
+ this.navigation?.dispose();
799
+ this.navigation = null;
800
+ this.physics.dispose();
801
+ this.simulation?.pause();
802
+ this.rendering?.dispose?.();
803
+ this.rendering = null;
804
+ this.events.clear();
805
+ }
806
+ }