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

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