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,1752 @@
1
+ import * as THREE from 'three';
2
+ import { orderParts, ROOT_PART } from '../../../asset/model/parts.js';
3
+
4
+ const array3 = (v) => [v.x, v.y, v.z];
5
+ const upright = (q) => {
6
+ const upX = 2 * (q.x * q.y - q.z * q.w);
7
+ const upY = 1 - 2 * (q.x * q.x + q.z * q.z);
8
+ const upZ = 2 * (q.y * q.z + q.x * q.w);
9
+ return upY > 0.999 && Math.abs(upX) < 0.02 && Math.abs(upZ) < 0.02;
10
+ };
11
+ const yaw = (q) => Math.atan2(2 * (q.w * q.y + q.x * q.z), 1 - 2 * (q.y * q.y + q.z * q.z));
12
+ const boxAabbHalfExtents = (half, q) => {
13
+ const xx = 1 - 2 * (q.y * q.y + q.z * q.z), xy = 2 * (q.x * q.y - q.z * q.w), xz = 2 * (q.x * q.z + q.y * q.w);
14
+ const yx = 2 * (q.x * q.y + q.z * q.w), yy = 1 - 2 * (q.x * q.x + q.z * q.z), yz = 2 * (q.y * q.z - q.x * q.w);
15
+ const zx = 2 * (q.x * q.z - q.y * q.w), zy = 2 * (q.y * q.z + q.x * q.w), zz = 1 - 2 * (q.x * q.x + q.y * q.y);
16
+ return [
17
+ Math.abs(xx) * half.x + Math.abs(xy) * half.y + Math.abs(xz) * half.z,
18
+ Math.abs(yx) * half.x + Math.abs(yy) * half.y + Math.abs(yz) * half.z,
19
+ Math.abs(zx) * half.x + Math.abs(zy) * half.y + Math.abs(zz) * half.z
20
+ ];
21
+ };
22
+ const cylinderAabbHalfExtents = (radius, halfHeight, q) => {
23
+ const axis = [2 * (q.x * q.y - q.z * q.w), 1 - 2 * (q.x * q.x + q.z * q.z), 2 * (q.y * q.z + q.x * q.w)];
24
+ return axis.map((component) => radius * Math.sqrt(Math.max(0, 1 - component * component)) + halfHeight * Math.abs(component));
25
+ };
26
+ const capsuleAabbHalfExtents = (radius, halfHeight, q) => {
27
+ const axis = [2 * (q.x * q.y - q.z * q.w), 1 - 2 * (q.x * q.x + q.z * q.z), 2 * (q.y * q.z + q.x * q.w)];
28
+ return axis.map((component) => radius + halfHeight * Math.abs(component));
29
+ };
30
+ const convexAabb = (vertices, position, rotation) => {
31
+ const q = new THREE.Quaternion(rotation.x, rotation.y, rotation.z, rotation.w);
32
+ const v = new THREE.Vector3();
33
+ const min = new THREE.Vector3(Infinity, Infinity, Infinity);
34
+ const max = new THREE.Vector3(-Infinity, -Infinity, -Infinity);
35
+ for (let i = 0; i < vertices.length; i += 3) {
36
+ v.set(vertices[i], vertices[i + 1], vertices[i + 2]).applyQuaternion(q).add(position);
37
+ min.min(v); max.max(v);
38
+ }
39
+ return { position:min.clone().add(max).multiplyScalar(0.5).toArray(), halfExtents:max.clone().sub(min).multiplyScalar(0.5).toArray() };
40
+ };
41
+
42
+ const navigationObstacleDescriptor=(objectId,partName,i,{shape,position,rotation})=>{
43
+ const id=`${objectId}:${partName}:${i}`;
44
+ if(shape.kind==='box') {
45
+ const exact=upright(rotation);
46
+ return ({
47
+ id,objectId,part:partName,collider:i,shape:'box',sourceShape:'box',quality:exact?'exact-yaw':'conservative-aabb',
48
+ position:array3(position),
49
+ halfExtents:exact?array3(shape.halfExtents):boxAabbHalfExtents(shape.halfExtents,rotation),
50
+ angle:exact?yaw(rotation):0
51
+ });
52
+ } else if(shape.kind==='cylinder') {
53
+ if(upright(rotation)) {
54
+ return ({id,objectId,part:partName,collider:i,shape:'cylinder',sourceShape:'cylinder',quality:'exact-upright',position:[position.x,position.y-shape.halfHeight,position.z],radius:shape.radius,height:shape.halfHeight*2});
55
+ } else {
56
+ return ({id,objectId,part:partName,collider:i,shape:'box',sourceShape:'cylinder',quality:'conservative-aabb',position:array3(position),halfExtents:cylinderAabbHalfExtents(shape.radius,shape.halfHeight,rotation),angle:0});
57
+ }
58
+ } else if(shape.kind==='capsule') {
59
+ const extentY=shape.halfHeight+shape.radius;
60
+ if(upright(rotation)) {
61
+ return ({id,objectId,part:partName,collider:i,shape:'cylinder',sourceShape:'capsule',quality:'conservative-upright',position:[position.x,position.y-extentY,position.z],radius:shape.radius,height:extentY*2});
62
+ } else {
63
+ return ({id,objectId,part:partName,collider:i,shape:'box',sourceShape:'capsule',quality:'conservative-aabb',position:array3(position),halfExtents:capsuleAabbHalfExtents(shape.radius,shape.halfHeight,rotation),angle:0});
64
+ }
65
+ } else if(shape.kind==='convexHull' && shape.vertices?.length) {
66
+ const box=convexAabb(shape.vertices,new THREE.Vector3(position.x,position.y,position.z),rotation);
67
+ return ({id,objectId,part:partName,collider:i,shape:'box',sourceShape:'convexHull',quality:'conservative-aabb',...box,angle:0});
68
+ } else {
69
+ return null;
70
+ }
71
+ };
72
+
73
+ export class PhysicsSystem {
74
+ constructor({ backend } = {}) {
75
+ if (!backend) throw new TypeError('PhysicsSystem requires a physics backend');
76
+ this.backend = backend;
77
+ this.solverEnabled = backend.hasCapability?.('rigid-body') === true;
78
+ this.world = null;
79
+ this.entries = new Map();
80
+ this.colliderProvenance = new Map();
81
+ this.colliderHandles = new Map();
82
+ this.colliderRuntime = new Map();
83
+ this.collisionPairs = new Map();
84
+ this.collisionEvents = [];
85
+ this.collisionGroupBits = new Map();
86
+ this.rootRotation = new THREE.Quaternion();
87
+ this.inverseRootRotation = new THREE.Quaternion();
88
+ this.partWorldRotation = new THREE.Quaternion();
89
+ this.partLocalRotation = new THREE.Quaternion();
90
+ this.rootWorldPosition = new THREE.Vector3();
91
+ this.partWorldPosition = new THREE.Vector3();
92
+ this.partLocalPosition = new THREE.Vector3();
93
+ this.characterController = null;
94
+ this.parentWorldPosition = new THREE.Vector3();
95
+ this.parentWorldRotation = new THREE.Quaternion();
96
+ this.inverseParentWorldRotation = new THREE.Quaternion();
97
+ }
98
+
99
+ async init(characterControllerOptions = null) {
100
+ await this.backend.init();
101
+ this.world = this.backend.createWorld();
102
+ this.characterControllerOptions = characterControllerOptions || this.characterControllerOptions || null;
103
+ if (!this.solverEnabled || !this.backend.hasCapability('character-controller')) return this;
104
+ this.characterController=this.backend.createCharacterController(this.world, this.characterControllerOptions || undefined);
105
+ return this;
106
+ }
107
+
108
+ setCharacterControllerOptions(options = null) {
109
+ this.characterControllerOptions = options && typeof options === 'object' ? options : null;
110
+ if (!this.world || !this.solverEnabled || !this.backend.hasCapability?.('character-controller')) return this;
111
+ if (this.characterController && this.backend.removeCharacterController) {
112
+ try { this.backend.removeCharacterController(this.world, this.characterController); } catch {}
113
+ }
114
+ this.characterController = this.backend.createCharacterController(this.world, this.characterControllerOptions || undefined);
115
+ return this;
116
+ }
117
+
118
+ resetWorld() {
119
+ const previousWorld=this.world;
120
+ const previousController=this.characterController;
121
+ this.entries.clear();
122
+ this.colliderProvenance.clear();
123
+ this.colliderHandles.clear();
124
+ this.colliderRuntime.clear();
125
+ this.collisionPairs.clear();
126
+ this.collisionEvents.length=0;
127
+ this.collisionGroupBits.clear();
128
+ this.characterController=null;
129
+ if(previousWorld && previousController) this.backend.removeCharacterController(previousWorld,previousController);
130
+ if(previousWorld) this.backend.dispose(previousWorld);
131
+ this.world=this.backend.createWorld();
132
+ if(this.solverEnabled && this.backend.hasCapability('character-controller')) {
133
+ // Preserve environment KCC options (e.g. cabin autostep); otherwise restore/reset
134
+ // silently reverts to backend defaults and stairs become unwalkable.
135
+ this.characterController=this.backend.createCharacterController(this.world, this.characterControllerOptions || undefined);
136
+ }
137
+ return this;
138
+ }
139
+
140
+ runtimeCapabilities() {
141
+ const capabilities=['transform-state','articulation-pose'];
142
+ if (this.backend.hasCapability('collision') && this.backend.hasCapability('scene-query')) capabilities.push('counterfactual-query','collision-events');
143
+ return capabilities;
144
+ }
145
+
146
+ hasCapability(capability) {
147
+ return this.backend.hasCapability(capability) || this.runtimeCapabilities().includes(capability);
148
+ }
149
+ runtimeExecutionModes() { return ['render-only']; }
150
+ supportsExecutionMode(mode) {
151
+ return this.backend.supportsExecutionMode(mode) || this.runtimeExecutionModes().includes(mode);
152
+ }
153
+ profile() {
154
+ const backendCapabilities=[...this.backend.capabilities];
155
+ const runtimeCapabilities=this.runtimeCapabilities();
156
+ const backendExecutionModes=[...this.backend.executionModes];
157
+ const runtimeExecutionModes=this.runtimeExecutionModes();
158
+ return {
159
+ identity:this.backend.identity,
160
+ backendCapabilities,
161
+ runtimeCapabilities,
162
+ capabilities:[...new Set([...backendCapabilities,...runtimeCapabilities])],
163
+ backendExecutionModes,
164
+ runtimeExecutionModes,
165
+ executionModes:[...new Set([...backendExecutionModes,...runtimeExecutionModes])],
166
+ qualities:{...this.backend.qualities},
167
+ solverEnabled:this.solverEnabled
168
+ };
169
+ }
170
+
171
+ debugSnapshot({ nativeGeometry=true, contacts=true } = {}) {
172
+ const bodies=[];
173
+ const colliders=[];
174
+ const joints=[];
175
+ const contactPairs=[];
176
+ const colliderRefs=[];
177
+ const pushBody=(objectId,partName,body)=>{
178
+ if(!body) return;
179
+ const pose=this.backend.bodyPose(body);
180
+ const motion=this.backend.bodyMotion(body);
181
+ bodies.push({
182
+ objectId,partName,
183
+ bodyType:this.backend.bodyType(body),
184
+ position:pose?.position ? [...pose.position] : null,
185
+ rotation:pose?.rotation ? [...pose.rotation] : null,
186
+ sleeping:motion?.sleeping ?? null,
187
+ linearVelocity:motion?.linearVelocity ? [...motion.linearVelocity] : null,
188
+ angularVelocity:motion?.angularVelocity ? [...motion.angularVelocity] : null,
189
+ linearSpeed:Number.isFinite(motion?.linearSpeed) ? motion.linearSpeed : null,
190
+ angularSpeed:Number.isFinite(motion?.angularSpeed) ? motion.angularSpeed : null
191
+ });
192
+ for(const [colliderIndex,collider] of this.backend.colliders(body).entries()) {
193
+ const snapshot=this.backend.colliderSnapshot(collider);
194
+ if(!snapshot) continue;
195
+ const record={
196
+ objectId,partName,colliderIndex,
197
+ position:[snapshot.position.x,snapshot.position.y,snapshot.position.z],
198
+ rotation:[snapshot.rotation.x,snapshot.rotation.y,snapshot.rotation.z,snapshot.rotation.w],
199
+ shape:structuredClone(snapshot.shape),
200
+ provenance:this.provenanceOfCollider(collider)
201
+ };
202
+ colliders.push(record);
203
+ colliderRefs.push({key:this.backend.colliderKey(collider),collider,record});
204
+ }
205
+ };
206
+ for(const [objectId,entry] of this.entries) {
207
+ pushBody(objectId,ROOT_PART,entry.body);
208
+ for(const [partName,part] of entry.parts) {
209
+ pushBody(objectId,partName,part.body);
210
+ if(part.joint) {
211
+ const articulation=this.getArticulationState(objectId,partName);
212
+ const pose=this.backend.bodyPose(part.body);
213
+ const localAxis=part.spec?.joint?.axis ? [...part.spec.joint.axis] : null;
214
+ const localAnchor=part.spec?.joint?.childAnchor ? [...part.spec.joint.childAnchor] : [0,0,0];
215
+ let worldAxis=null,worldAnchor=null;
216
+ if(pose?.position && pose?.rotation) {
217
+ const rotation=new THREE.Quaternion(...pose.rotation);
218
+ worldAnchor=new THREE.Vector3(...localAnchor).applyQuaternion(rotation).add(new THREE.Vector3(...pose.position)).toArray();
219
+ if(localAxis) worldAxis=new THREE.Vector3(...localAxis).applyQuaternion(rotation).normalize().toArray();
220
+ }
221
+ joints.push({
222
+ objectId,partName,
223
+ jointType:part.spec?.joint?.type || articulation?.jointType || null,
224
+ axis:localAxis,
225
+ limits:part.spec?.joint?.limits ? [...part.spec.joint.limits] : null,
226
+ parentAnchor:part.spec?.joint?.parentAnchor ? [...part.spec.joint.parentAnchor] : null,
227
+ childAnchor:localAnchor,
228
+ worldAxis,worldAnchor,
229
+ coordinate:Number.isFinite(articulation?.coordinate) ? articulation.coordinate : null
230
+ });
231
+ }
232
+ }
233
+ }
234
+ if(contacts && this.world && this.backend.hasCapability("collision")) {
235
+ const seen=new Set();
236
+ for(const source of colliderRefs) {
237
+ for(const pair of this.backend.contactPairs(this.world,source.collider)) {
238
+ const targetKey=this.backend.colliderKey(pair.other);
239
+ const key=[String(source.key),String(targetKey)].sort().join(":");
240
+ if(seen.has(key)) continue;
241
+ seen.add(key);
242
+ const targetSnapshot=this.backend.colliderSnapshot(pair.other);
243
+ if(!targetSnapshot) continue;
244
+ const targetPosition=[targetSnapshot.position.x,targetSnapshot.position.y,targetSnapshot.position.z];
245
+ const anchor=source.record.position.map((value,index)=>(value+targetPosition[index])/2);
246
+ contactPairs.push({
247
+ source:source.record.provenance || {kind:"object",objectId:source.record.objectId,partName:source.record.partName,colliderIndex:source.record.colliderIndex},
248
+ target:this.provenanceOfCollider(pair.other) || {kind:"unknown",colliderIndex:null},
249
+ sourcePosition:[...source.record.position],
250
+ targetPosition,
251
+ anchor,
252
+ anchorKind:"collider-midpoint",
253
+ normal:Array.isArray(pair.normal) ? [...pair.normal] : null,
254
+ minDistance:Number.isFinite(pair.minDistance) ? pair.minDistance : null,
255
+ totalImpulse:Number.isFinite(pair.totalImpulse) ? pair.totalImpulse : null,
256
+ evidenceKind:pair.evidenceKind || "contact",
257
+ impulseAvailable:pair.impulseAvailable===true
258
+ });
259
+ }
260
+ }
261
+ }
262
+ const backend=this.backend.debugSnapshot(this.world,{nativeGeometry}) || {};
263
+ return {
264
+ schemaVersion:1,
265
+ source:"physics",
266
+ backend:this.backend.identity,
267
+ bodies,colliders,joints,contacts:contactPairs,
268
+ nativeGeometry:backend.nativeGeometry || null,
269
+ nativeGeometryAvailable:backend.nativeGeometryAvailable ?? Boolean(backend.nativeGeometry),
270
+ metrics:{...(backend.metrics || {}),bodyCount:bodies.length,colliderCount:colliders.length,jointCount:joints.length,contactPairCount:contactPairs.length}
271
+ };
272
+ }
273
+
274
+ // Narrow-phase contact for each distinct physical part pair, not just objects.
275
+ // Keeps articulated body provenance; does not allocate a full debug snapshot.
276
+ contactPartPairs(objectIds) {
277
+ if(!this.world||!this.backend.hasCapability('collision'))return [];
278
+ const allowed=new Set(objectIds);
279
+ const seen=new Set(),result=[];
280
+ for(const id of allowed) {
281
+ const entry=this.entries.get(id);
282
+ if(!entry)continue;
283
+ for(const body of [entry.body,...[...entry.parts.values()].map(part=>part.body)]) {
284
+ if(!body)continue;
285
+ for(const collider of this.backend.colliders(body)) {
286
+ const source=this.provenanceOfCollider(collider);
287
+ if(source?.kind!=='object')continue;
288
+ for(const pair of this.backend.contactPairs(this.world,collider)) {
289
+ const target=this.provenanceOfCollider(pair.other);
290
+ if(target?.kind!=='object'||source.objectId===target.objectId
291
+ ||!allowed.has(target.objectId))continue;
292
+ const [left,right]=[source,target].sort((a,b)=>
293
+ a.objectId.localeCompare(b.objectId)||a.partName.localeCompare(b.partName));
294
+ const key=[left.objectId,left.partName,right.objectId,right.partName].join('|');
295
+ if(seen.has(key))continue;
296
+ seen.add(key);
297
+ result.push({
298
+ sourceId:left.objectId,sourcePartName:left.partName,
299
+ targetId:right.objectId,targetPartName:right.partName,
300
+ evidenceKind:'physics-contact'
301
+ });
302
+ }
303
+ }
304
+ }
305
+ }
306
+ return result;
307
+ }
308
+
309
+ contactObjectPairs(objectIds) {
310
+ const seen=new Set(),result=[];
311
+ for(const pair of this.contactPartPairs(objectIds)){
312
+ const key=pair.sourceId+'|'+pair.targetId;
313
+ if(seen.has(key))continue;
314
+ seen.add(key);
315
+ result.push({sourceId:pair.sourceId,targetId:pair.targetId,evidenceKind:'physics-contact'});
316
+ }
317
+ return result;
318
+ }
319
+
320
+ addEnvironment(colliders = [], { id = '$environment', collision = null, sensor = false, collisionEvents = false } = {}) {
321
+ if (!this.solverEnabled) return null;
322
+ const body=this.backend.createBody(this.world,{type:'fixed'});
323
+ this.addColliders(body,colliders,{collision,sensor,collisionEvents,provenance:{kind:'environment',environmentId:id}});
324
+ return body;
325
+ }
326
+
327
+ addFloor() {
328
+ return this.addEnvironment([{ shape:'box', halfExtents:[5, 0.1, 4], translation:[0, -0.1, 0] }]);
329
+ }
330
+
331
+ setEnvironmentPose(body, pose) {
332
+ if (!this.solverEnabled || !body) return false;
333
+ this.backend.setBodyPose(body, pose);
334
+ return true;
335
+ }
336
+
337
+ _collisionBit(name) {
338
+ if(this.collisionGroupBits.has(name)) return this.collisionGroupBits.get(name);
339
+ if(this.collisionGroupBits.size>=16) throw new Error('Physics collision groups exceed Rapier-compatible limit of 16');
340
+ const bit=1 << this.collisionGroupBits.size;
341
+ this.collisionGroupBits.set(name,bit);
342
+ return bit;
343
+ }
344
+
345
+ _compileCollisionFilter(collision) {
346
+ if(!collision) return null;
347
+ let membership=0,filter=0;
348
+ for(const name of collision.groups || []) membership|=this._collisionBit(name);
349
+ for(const name of collision.collidesWith || []) filter|=this._collisionBit(name);
350
+ return {membership:membership & 0xffff,filter:filter & 0xffff};
351
+ }
352
+
353
+ _collisionPairAllowed(leftRuntime,rightRuntime) {
354
+ const left=leftRuntime?.collisionFilter || {membership:0xffff,filter:0xffff};
355
+ const right=rightRuntime?.collisionFilter || {membership:0xffff,filter:0xffff};
356
+ return (left.membership & right.filter)!==0 && (right.membership & left.filter)!==0;
357
+ }
358
+
359
+ addColliders(body,colliders=[],{mass,friction,restitution,sensor=false,collisionEvents=false,collision=null,provenance=null}={}) {
360
+ if (!this.solverEnabled || !body || !this.backend.hasCapability('collision')) return [];
361
+ const collisionFilter=this._compileCollisionFilter(collision);
362
+ const created=this.backend.createColliders(this.world,body,colliders,{mass,friction,restitution});
363
+ this.backend.setBodyCollisionFilter(body,collisionFilter);
364
+ created.forEach((collider,colliderIndex)=>{
365
+ const key=this.backend.colliderKey(collider);
366
+ this.colliderHandles.set(key,collider);
367
+ if(provenance) this.colliderProvenance.set(key,{...provenance,colliderIndex});
368
+ this.colliderRuntime.set(key,{sensor:Boolean(sensor),collisionEvents:Boolean(collisionEvents),collisionFilter});
369
+ });
370
+ if(sensor) this.backend.setBodySensor(body,true);
371
+ return created;
372
+ }
373
+
374
+ unregisterBodyColliders(body) {
375
+ if (!body) return;
376
+ for(const collider of this.backend.colliders(body)) {
377
+ const key=this.backend.colliderKey(collider);
378
+ this.colliderProvenance.delete(key);
379
+ this.colliderHandles.delete(key);
380
+ this.colliderRuntime.delete(key);
381
+ }
382
+ }
383
+
384
+ provenanceOfCollider(collider) {
385
+ if (!collider) return null;
386
+ const owner=this.colliderProvenance.get(this.backend.colliderKey(collider));
387
+ return owner ? structuredClone(owner) : null;
388
+ }
389
+
390
+ addObject(id, manifest, object) {
391
+ if (!this.solverEnabled) return this.addTransformState(id, manifest, object);
392
+ const createdBodies = [];
393
+ try {
394
+ const worldPos = new THREE.Vector3();
395
+ const worldRot = new THREE.Quaternion();
396
+ object.getWorldPosition(worldPos);
397
+ object.getWorldQuaternion(worldRot);
398
+ const body=this.backend.createBody(this.world,{
399
+ type:manifest.physics?.body || 'fixed', position:worldPos, rotation:worldRot,
400
+ canSleep:manifest.physics?.canSleep ?? true, lockTranslation:manifest.physics?.lockTranslation, lockRotation:manifest.physics?.lockRotation
401
+ });
402
+ createdBodies.push(body);
403
+ this.addColliders(body,manifest.physics?.colliders,{...manifest.physics,provenance:{kind:'object',objectId:id,partName:ROOT_PART}});
404
+ this.backend.setBodyDynamics(body,manifest.physics || {});
405
+ if(manifest.physics?.ccd != null) this.backend.setBodyCcd(body,manifest.physics.ccd);
406
+
407
+ const entry = { body, root: object, rootSpec:manifest.physics || {}, nativeNavigation:manifest.nativeNavigation===true, nativeArticulation:manifest.nativeArticulation===true, parts: new Map(), lastPosition: worldPos.clone(), lastRotation: worldRot.clone() };
408
+ const bodies = new Map([[ROOT_PART, body]]);
409
+ for (const [partName, part] of orderParts(manifest.parts || {})) {
410
+ if (!part.physics || !part.joint) continue;
411
+ const node = object.getObjectByName(part.node);
412
+ if (!node) continue;
413
+ const parentName = part.parent || ROOT_PART;
414
+ const parentBody = bodies.get(parentName);
415
+ if (!parentBody) throw new Error(`Part parent body not available: ${partName} -> ${parentName}`);
416
+
417
+ const partWorld = new THREE.Vector3();
418
+ const partRotation = new THREE.Quaternion();
419
+ node.getWorldPosition(partWorld);
420
+ node.getWorldQuaternion(partRotation);
421
+ const child=this.backend.createBody(this.world,{
422
+ type:part.physics.body || 'dynamic', position:partWorld, rotation:partRotation,
423
+ canSleep:part.physics?.canSleep ?? true, lockTranslation:part.physics?.lockTranslation, lockRotation:part.physics?.lockRotation
424
+ });
425
+ createdBodies.push(child);
426
+ this.addColliders(child,part.physics.colliders,{...part.physics,provenance:{kind:'object',objectId:id,partName}});
427
+ this.backend.setBodyDynamics(child,part.physics);
428
+ if(part.physics?.ccd != null) this.backend.setBodyCcd(child,part.physics.ccd);
429
+
430
+ const joint=this.backend.createJoint(this.world,part,parentBody,child);
431
+ bodies.set(partName, child);
432
+ entry.parts.set(partName, { body: child, joint, node, spec: part, parentName, restLocalRotation:node.quaternion.clone(), restLocalPosition:node.position.clone(), lastLocalRotation: node.quaternion.clone(), lastLocalPosition: node.position.clone() });
433
+ }
434
+
435
+ this.entries.set(id, entry);
436
+ return entry;
437
+ } catch (error) {
438
+ for (const body of createdBodies.reverse()) {
439
+ try { this.unregisterBodyColliders(body); this.backend.removeBody(this.world,body); } catch {}
440
+ }
441
+ throw error;
442
+ }
443
+ }
444
+
445
+ addTransformState(id, manifest, object) {
446
+ object.updateMatrixWorld(true);
447
+ const worldPos = new THREE.Vector3();
448
+ const worldRot = new THREE.Quaternion();
449
+ object.getWorldPosition(worldPos);
450
+ object.getWorldQuaternion(worldRot);
451
+ const entry = {
452
+ body:null,
453
+ root:object,
454
+ rootSpec:manifest.physics || {},
455
+ parts:new Map(),
456
+ lastPosition:worldPos.clone(),
457
+ lastRotation:worldRot.clone(),
458
+ held:false,
459
+ transformOnly:true
460
+ };
461
+ for (const [partName, part] of orderParts(manifest.parts || {})) {
462
+ if (!part.joint) continue;
463
+ const node = object.getObjectByName(part.node);
464
+ if (!node) continue;
465
+ entry.parts.set(partName, {
466
+ body:null,
467
+ joint:null,
468
+ node,
469
+ spec:part,
470
+ parentName:part.parent || ROOT_PART,
471
+ restLocalRotation:node.quaternion.clone(),
472
+ restLocalPosition:node.position.clone(),
473
+ lastLocalRotation:node.quaternion.clone(),
474
+ lastLocalPosition:node.position.clone()
475
+ });
476
+ }
477
+ this.entries.set(id, entry);
478
+ return entry;
479
+ }
480
+
481
+ setPosition(id, position) {
482
+ const entry = this.entries.get(id);
483
+ if (!entry) return;
484
+ const next = new THREE.Vector3(...position);
485
+ if (!entry.body) {
486
+ if (entry.root.parent) {
487
+ entry.root.parent.updateWorldMatrix(true, false);
488
+ entry.root.position.copy(entry.root.parent.worldToLocal(next.clone()));
489
+ } else entry.root.position.copy(next);
490
+ entry.root.updateMatrixWorld(true);
491
+ entry.lastPosition.copy(next);
492
+ return true;
493
+ }
494
+ const delta = next.clone().sub(entry.lastPosition);
495
+ this.backend.setBodyPose(entry.body,{position});
496
+ this.backend.clearBodyMotion(entry.body,{linear:true,angular:false,wake:true});
497
+ for (const { body } of entry.parts.values()) {
498
+ this.backend.translateBody(body,delta.toArray(),{clearLinearVelocity:true,wake:true});
499
+ }
500
+ entry.lastPosition.copy(next);
501
+ }
502
+
503
+ beginTransform(id) {
504
+ const entry = this.entries.get(id);
505
+ if (!entry) return;
506
+ if (!entry.body) { entry.transforming = true; return true; }
507
+ entry.originalType=this.backend.bodyType(entry.body);
508
+ this.backend.setBodyType(entry.body,'kinematic');
509
+ for (const part of entry.parts.values()) {
510
+ part.originalType=this.backend.bodyType(part.body);
511
+ this.backend.setBodyType(part.body,'kinematic');
512
+ }
513
+ }
514
+
515
+ syncTransform(id, object) {
516
+ const entry = this.entries.get(id);
517
+ if (!entry) return;
518
+ object.updateMatrixWorld(true);
519
+ const p = new THREE.Vector3();
520
+ const q = new THREE.Quaternion();
521
+ object.getWorldPosition(p);
522
+ object.getWorldQuaternion(q);
523
+ if (!entry.body) {
524
+ entry.lastPosition.copy(p);
525
+ entry.lastRotation.copy(q);
526
+ for (const part of entry.parts.values()) {
527
+ part.lastLocalPosition.copy(part.node.position);
528
+ part.lastLocalRotation.copy(part.node.quaternion);
529
+ }
530
+ return true;
531
+ }
532
+ this.backend.setBodyPose(entry.body,{position:p,rotation:q});
533
+ entry.lastPosition.copy(p);
534
+ entry.lastRotation.copy(q);
535
+ for (const part of entry.parts.values()) {
536
+ const pp = new THREE.Vector3();
537
+ const pq = new THREE.Quaternion();
538
+ part.node.getWorldPosition(pp);
539
+ part.node.getWorldQuaternion(pq);
540
+ this.backend.setBodyPose(part.body,{position:pp,rotation:pq});
541
+ }
542
+ }
543
+
544
+ endTransform(id) {
545
+ const entry = this.entries.get(id);
546
+ if (!entry) return;
547
+ if (!entry.body) { delete entry.transforming; return true; }
548
+ if (entry.originalType != null) this.backend.setBodyType(entry.body,entry.originalType);
549
+ delete entry.originalType;
550
+ for (const part of entry.parts.values()) {
551
+ if (part.originalType != null) this.backend.setBodyType(part.body,part.originalType);
552
+ delete part.originalType;
553
+ this.backend.wakeBody(part.body);
554
+ }
555
+ }
556
+
557
+ removeObject(id) {
558
+ const entry = this.entries.get(id);
559
+ if (!entry) return false;
560
+ if (!entry.body) { this.entries.delete(id); return true; }
561
+ for (const part of entry.parts.values()) {
562
+ this.unregisterBodyColliders(part.body);
563
+ this.backend.removeBody(this.world,part.body);
564
+ }
565
+ this.unregisterBodyColliders(entry.body);
566
+ this.backend.removeBody(this.world,entry.body);
567
+ this.entries.delete(id);
568
+ return true;
569
+ }
570
+
571
+ setHeld(id, held) {
572
+ const entry = this.entries.get(id);
573
+ if (!entry) return false;
574
+ if (!entry.body) { entry.held = Boolean(held); return true; }
575
+ if (held) {
576
+ if (entry.heldOriginalType == null) entry.heldOriginalType=this.backend.bodyType(entry.body);
577
+ entry.held=true;
578
+ this.backend.setBodyType(entry.body,'kinematic');
579
+ this.backend.clearBodyMotion(entry.body,{wake:true});
580
+ } else {
581
+ entry.held=false;
582
+ this.backend.setBodyType(entry.body,entry.heldOriginalType ?? 'dynamic');
583
+ this.backend.clearBodyMotion(entry.body,{wake:true});
584
+ delete entry.heldOriginalType;
585
+ }
586
+ return true;
587
+ }
588
+
589
+ setHeldTarget(id, target, rotation = null) {
590
+ const entry = this.entries.get(id);
591
+ const body = entry?.body;
592
+ if (!entry) return false;
593
+ if (!body) return this.setHeldPose(id, target, rotation);
594
+ this.backend.setBodyPose(body,{position:target,rotation,next:true});
595
+ return true;
596
+ }
597
+
598
+ setHeldPose(id, position, rotation = null) {
599
+ const entry = this.entries.get(id);
600
+ if (!entry) return false;
601
+ if (entry.body) {
602
+ this.backend.setBodyPose(entry.body,{position,rotation});
603
+ }
604
+ if (entry.root.parent) {
605
+ entry.root.parent.updateWorldMatrix(true, false);
606
+ entry.root.position.copy(entry.root.parent.worldToLocal(new THREE.Vector3(...position)));
607
+ } else entry.root.position.fromArray(position);
608
+ entry.lastPosition.fromArray(position);
609
+ if (rotation) {
610
+ entry.lastRotation.fromArray(rotation);
611
+ if (entry.root.parent) {
612
+ entry.root.parent.getWorldQuaternion(this.parentWorldRotation);
613
+ entry.root.quaternion.copy(this.parentWorldRotation.invert()).multiply(entry.lastRotation);
614
+ } else {
615
+ entry.root.quaternion.copy(entry.lastRotation);
616
+ }
617
+ }
618
+ entry.root.updateMatrixWorld(true);
619
+ return true;
620
+ }
621
+
622
+ anchorPose(id, anchor, { next = false } = {}) {
623
+ const entry = this.entries.get(id);
624
+ const body = entry?.body;
625
+ if (!entry || !anchor?.translation) return null;
626
+ let position;
627
+ let rotation;
628
+ if (body) {
629
+ const pose=this.backend.bodyPose(body,{next});
630
+ position=new THREE.Vector3(...pose.position);
631
+ rotation=new THREE.Quaternion(...pose.rotation);
632
+ } else {
633
+ entry.root.updateWorldMatrix(true, false);
634
+ position = new THREE.Vector3();
635
+ rotation = new THREE.Quaternion();
636
+ entry.root.getWorldPosition(position);
637
+ entry.root.getWorldQuaternion(rotation);
638
+ }
639
+ const local = new THREE.Vector3(...anchor.translation).applyQuaternion(rotation);
640
+ const anchorPosition = position.clone().add(local);
641
+ const localRotation = new THREE.Quaternion(...(anchor.rotation || [0,0,0,1]));
642
+ const worldRotation = rotation.clone().multiply(localRotation).normalize();
643
+ return { position:anchorPosition.toArray(), rotation:worldRotation.toArray() };
644
+ }
645
+
646
+ checkManifestPose(manifest, targetPosition, { excludeIds = [], quaternion = [0,0,0,1] } = {}) {
647
+ if (!this.backend.hasCapability('collision')) return {checked:false,clear:false,reason:'PHYSICS_CAPABILITY_UNAVAILABLE',capability:'collision'};
648
+ const colliders=manifest?.physics?.colliders || [];
649
+ if (!colliders.length) return {checked:false,clear:false,reason:'ROOT_COLLIDER_UNAVAILABLE'};
650
+ const excluded=new Set(excludeIds);
651
+ const blockedBy=new Set();
652
+ const shapeFor=(spec)=>{
653
+ return this.backend.createQueryShape(spec);
654
+ };
655
+ this.backend.syncSceneQueries(this.world);
656
+ for(let i=0;i<colliders.length;i++) {
657
+ const spec=colliders[i],shape=shapeFor(spec);
658
+ if (!shape) return {checked:false,clear:false,reason:'ROOT_COLLIDER_UNSUPPORTED',collider:i,shape:spec.shape || null};
659
+ const local=spec.translation || [0,0,0];
660
+ const rootRotation=new THREE.Quaternion(...quaternion).normalize();
661
+ const position=new THREE.Vector3(...local).applyQuaternion(rootRotation).add(new THREE.Vector3(...targetPosition));
662
+ const rotation=rootRotation.clone().multiply(new THREE.Quaternion(...(spec.rotation || [0,0,0,1]))).normalize();
663
+ try {
664
+ this.backend.intersectionsWithShape(this.world,position,rotation,shape,(other)=>{
665
+ const provenance=this.provenanceOfCollider(other);
666
+ if (provenance?.kind==='object' && excluded.has(provenance.objectId)) return true;
667
+ blockedBy.add(provenance?.kind==='environment' ? `environment:${provenance.environmentId || '$environment'}`
668
+ : provenance?.kind==='object' ? `object:${provenance.objectId}:${provenance.partName || ROOT_PART}` : '$unknown');
669
+ return false;
670
+ });
671
+ } finally {
672
+ this.backend.disposeQueryShape(shape);
673
+ }
674
+ if (blockedBy.size) return {checked:true,clear:false,blockedBy:[...blockedBy].sort(),coverage:Object.keys(manifest.parts || {}).length?'root-only':'full-root'};
675
+ }
676
+ return {checked:true,clear:true,blockedBy:[],coverage:Object.keys(manifest.parts || {}).length?'root-only':'full-root'};
677
+ }
678
+
679
+ checkBodyPose(id, targetPosition, targetRotation = null, { excludeIds = [] } = {}) {
680
+ if (!this.backend.hasCapability('collision')) return {clear:false,code:'PHYSICS_CAPABILITY_UNAVAILABLE',capability:'collision'};
681
+ const entry = this.entries.get(id);
682
+ if (!entry || entry.parts.size) return { clear:false, code:'CARRY_BODY_UNSUPPORTED' };
683
+ const bodyPose=this.backend.bodyPose(entry.body);
684
+ const bodyRotation=new THREE.Quaternion(...bodyPose.rotation);
685
+ const nextRotation = targetRotation ? new THREE.Quaternion(...targetRotation) : bodyRotation.clone();
686
+ const targetBody = new THREE.Vector3(...targetPosition);
687
+ const excluded = new Set([id, ...excludeIds]);
688
+ const filter=(collider)=>{
689
+ const parent=this.backend.colliderParent(collider);
690
+ const owner=parent ? this.ownerOfBody(parent) : null;
691
+ return !owner || !excluded.has(owner.id);
692
+ };
693
+
694
+ this.backend.syncSceneQueries(this.world);
695
+ const bodyColliders=this.backend.colliders(entry.body);
696
+ for (let i=0;i<bodyColliders.length;i++) {
697
+ const collider=bodyColliders[i];
698
+ const snapshot=this.backend.colliderSnapshot(collider);
699
+ const spec = entry.rootSpec.colliders?.[i] || {};
700
+ if (!['box','cylinder','capsule'].includes(spec.shape)) return { clear:false, code:'CARRY_COLLIDER_UNSUPPORTED', collider:i, shape:spec.shape || null };
701
+ const local = new THREE.Vector3(...(spec.translation || [0,0,0]));
702
+ const targetCenter = local.applyQuaternion(nextRotation).add(targetBody);
703
+ let overlap = null;
704
+ const colliderRotation=nextRotation.clone().multiply(new THREE.Quaternion(...(spec.rotation || [0,0,0,1])));
705
+ this.backend.intersectionsWithShape(this.world,targetCenter,colliderRotation,snapshot.shapeRef,(other)=>{
706
+ const parent=this.backend.colliderParent(other);
707
+ const owner=parent ? this.ownerOfBody(parent) : null;
708
+ if (owner && excluded.has(owner.id)) return true;
709
+ overlap = owner?.id || '$environment';
710
+ return false;
711
+ },{excludeCollider:collider,excludeBody:entry.body,predicate:filter});
712
+ if (overlap) return { clear:false, code:'CARRY_TARGET_BLOCKED', collider:i, blockedBy:[overlap] };
713
+ }
714
+ return { clear:true };
715
+ }
716
+
717
+ checkBodyMotion(id, targetPosition, targetRotation = null, { excludeIds = [] } = {}) {
718
+ if (!this.backend.hasCapability('collision')) return {clear:false,code:'PHYSICS_CAPABILITY_UNAVAILABLE',capability:'collision'};
719
+ const entry = this.entries.get(id);
720
+ if (!entry || entry.parts.size) return { clear:false, code:'CARRY_BODY_UNSUPPORTED' };
721
+ const bodyPose=this.backend.bodyPose(entry.body);
722
+ const bodyRotation=new THREE.Quaternion(...bodyPose.rotation);
723
+ const nextRotation = targetRotation ? new THREE.Quaternion(...targetRotation) : bodyRotation.clone();
724
+ const targetBody = new THREE.Vector3(...targetPosition);
725
+ const blockedBy = new Set();
726
+ const excluded = new Set([id, ...excludeIds]);
727
+ const filter=(collider)=>{
728
+ const parent=this.backend.colliderParent(collider);
729
+ const owner=parent ? this.ownerOfBody(parent) : null;
730
+ return !owner || !excluded.has(owner.id);
731
+ };
732
+
733
+ this.backend.syncSceneQueries(this.world);
734
+ const bodyColliders=this.backend.colliders(entry.body);
735
+ for (let i=0;i<bodyColliders.length;i++) {
736
+ const collider=bodyColliders[i];
737
+ const snapshot=this.backend.colliderSnapshot(collider);
738
+ const spec = entry.rootSpec.colliders?.[i] || {};
739
+ if (!['box','cylinder','capsule'].includes(spec.shape)) return { clear:false, code:'CARRY_COLLIDER_UNSUPPORTED', collider:i, shape:spec.shape || null };
740
+ const local = new THREE.Vector3(...(spec.translation || [0,0,0]));
741
+ const targetCenter = local.applyQuaternion(nextRotation).add(targetBody);
742
+ const delta=targetCenter.clone().sub(new THREE.Vector3(snapshot.position.x,snapshot.position.y,snapshot.position.z));
743
+ if (delta.lengthSq() > 1e-12) {
744
+ const hit=this.backend.castCollider(this.world,collider,delta.toArray(),{
745
+ excludeCollider:collider,excludeBody:entry.body,predicate:filter,
746
+ targetDistance:0,maxToi:1,stopAtPenetration:false
747
+ });
748
+ if(hit) {
749
+ const parent=this.backend.colliderParent(hit.collider);
750
+ const owner=parent ? this.ownerOfBody(parent) : null;
751
+ blockedBy.add(owner?.id || '$environment');
752
+ return {clear:false,code:'CARRY_SWEEP_BLOCKED',collider:i,blockedBy:[...blockedBy],toi:hit.timeOfImpact};
753
+ }
754
+ }
755
+ }
756
+ return this.checkBodyPose(id,targetPosition,targetRotation,{excludeIds});
757
+ }
758
+
759
+ cancelCharacterMovement(id) {
760
+ if (!this.backend.hasCapability('character-controller')) return false;
761
+ const body = this.entries.get(id)?.body;
762
+ if (!body) return false;
763
+ return this.backend.cancelCharacterMovement(body);
764
+ }
765
+
766
+ getPosition(id) {
767
+ const entry = this.entries.get(id);
768
+ const pose=entry?.body ? this.backend.bodyPose(entry.body) : null;
769
+ if (pose) return [...pose.position];
770
+ if (!entry?.root) return null;
771
+ entry.root.updateWorldMatrix(true, false);
772
+ const world = new THREE.Vector3();
773
+ entry.root.getWorldPosition(world);
774
+ return world.toArray();
775
+ }
776
+
777
+ getRotation(id) {
778
+ const entry = this.entries.get(id);
779
+ const pose=entry?.body ? this.backend.bodyPose(entry.body) : null;
780
+ if (pose) return [...pose.rotation];
781
+ if (!entry?.root) return null;
782
+ entry.root.updateWorldMatrix(true, false);
783
+ const world = new THREE.Quaternion();
784
+ entry.root.getWorldQuaternion(world);
785
+ return world.toArray();
786
+ }
787
+
788
+ // Portable body checkpoint, not an exact snapshot of the solver/contact caches.
789
+ captureState() {
790
+ return Array.from(this.entries.keys(), id => this.captureObjectState(id));
791
+ }
792
+
793
+ captureObjectState(id) {
794
+ const entry = this.entries.get(id);
795
+ if (!entry) return null;
796
+ const capture = (body, node) => ({
797
+ position:node.position.toArray(), rotation:node.quaternion.toArray(),
798
+ ...(body ? {
799
+ type:this.backend.bodyType(body),
800
+ pose:this.backend.bodyPose(body),
801
+ motion:this.backend.bodyMotion(body),
802
+ ...(this.backend.bodyType(body) === 'kinematic' ? { nextPose:this.backend.bodyPose(body, { next:true }) } : {})
803
+ } : {})
804
+ });
805
+ return {
806
+ id,
807
+ root:capture(entry.body, entry.root),
808
+ held:entry.held === true,
809
+ heldOriginalType:entry.heldOriginalType ?? null,
810
+ parts:[...entry.parts].map(([name, part]) => ({
811
+ name, ...capture(part.body, part.node), motorTarget:part.motorTarget ?? null
812
+ }))
813
+ };
814
+ }
815
+
816
+ captureArticulationPose(id) {
817
+ const entry = this.entries.get(id);
818
+ return entry ? [...entry.parts].map(([partName,part]) => ({ partName,
819
+ position:part.node.position.toArray(), quaternion:part.node.quaternion.toArray(), motorTarget:part.motorTarget ?? null })) : [];
820
+ }
821
+
822
+ // Save/history restoration only. Live manipulation never calls this method.
823
+ restoreArticulationPose(id, poses) {
824
+ const entry = this.entries.get(id);
825
+ if (!entry) throw new Error('ARTICULATION_PHYSICS_UNAVAILABLE');
826
+ const checkpoint = this.captureObjectState(id);
827
+ for (const pose of poses) {
828
+ const part = entry.parts.get(pose.partName);
829
+ if (!part) throw new Error('ARTICULATION_PART_NOT_FOUND');
830
+ const limits = part.spec.joint.limits;
831
+ if (pose.motorTarget != null && limits && (pose.motorTarget < limits[0] || pose.motorTarget > limits[1])) throw new Error('JOINT_LIMIT_EXCEEDED');
832
+ part.node.position.fromArray(pose.position); part.node.quaternion.fromArray(pose.quaternion);
833
+ }
834
+ entry.root.updateMatrixWorld(true);
835
+ for (const pose of poses) {
836
+ const part = entry.parts.get(pose.partName), value = checkpoint.parts.find(item => item.name === pose.partName);
837
+ value.position = pose.position; value.rotation = pose.quaternion; value.motorTarget = pose.motorTarget;
838
+ if (value.pose) value.pose = { position:part.node.getWorldPosition(new THREE.Vector3()).toArray(), rotation:part.node.getWorldQuaternion(new THREE.Quaternion()).toArray() };
839
+ }
840
+ this.restoreObjectState(id, checkpoint);
841
+ }
842
+
843
+ restoreState(state) {
844
+ for (const item of state) this.restoreObjectState(item.id, item);
845
+ }
846
+
847
+ restoreObjectState(id, item) {
848
+ if (id !== item.id) throw new Error("Physics checkpoint id mismatch");
849
+ const restore = (body, node, value) => {
850
+ node.position.fromArray(value.position);
851
+ node.quaternion.fromArray(value.rotation);
852
+ node.updateMatrixWorld(true);
853
+ if (!body) return;
854
+ if (this.backend.bodyType(body) !== value.type) this.backend.setBodyType(body, value.type);
855
+ this.backend.setBodyPose(body, { ...value.pose, wake:false });
856
+ if (value.nextPose) this.backend.setBodyPose(body, { ...value.nextPose, next:true, wake:false });
857
+ if (value.motion && value.type === 'dynamic') {
858
+ this.backend.setBodyMotion(body, { ...value.motion, wake:false });
859
+ if (value.motion.sleeping) this.backend.sleepBody(body);
860
+ else this.backend.wakeBody(body);
861
+ }
862
+ };
863
+ const entry = this.entries.get(item.id);
864
+ if (!entry) throw new Error(`Physics checkpoint object missing: ${item.id}`);
865
+ entry.held = item.held;
866
+ if (item.heldOriginalType == null) delete entry.heldOriginalType;
867
+ else entry.heldOriginalType = item.heldOriginalType;
868
+ restore(entry.body, entry.root, item.root);
869
+ entry.root.getWorldPosition(entry.lastPosition);
870
+ entry.root.getWorldQuaternion(entry.lastRotation);
871
+ for (const value of item.parts) {
872
+ const part = entry.parts.get(value.name);
873
+ if (!part) throw new Error(`Physics checkpoint part missing: ${item.id}:${value.name}`);
874
+ if (part.joint && part.spec.joint.type !== 'fixed') {
875
+ this.backend.setJointTarget(part.joint, value.motorTarget, part.spec.joint.motor || {});
876
+ }
877
+ part.motorTarget = value.motorTarget;
878
+ restore(part.body, part.node, value);
879
+ part.lastLocalPosition.copy(part.node.position);
880
+ part.lastLocalRotation.copy(part.node.quaternion);
881
+ }
882
+ }
883
+
884
+ getMotion(id, { partName = ROOT_PART } = {}) {
885
+ const entry = this.entries.get(id);
886
+ const body = partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
887
+ if (!entry) return null;
888
+ if (!body) return {
889
+ sleeping:true,
890
+ linearVelocity:[0,0,0],
891
+ angularVelocity:[0,0,0],
892
+ linearSpeed:0,
893
+ angularSpeed:0,
894
+ source:'transform-state'
895
+ };
896
+ return this.backend.bodyMotion(body);
897
+ }
898
+
899
+ /** Solver-space bounds for registered native or managed root colliders. */
900
+ manipulationBounds(id,partName=ROOT_PART) {
901
+ const entry=this.entries.get(id),body=partName===ROOT_PART?entry?.body:entry?.parts.get(partName)?.body;
902
+ if(!body)return null;
903
+ const bounds=new THREE.Box3();
904
+ for(const collider of this.backend.colliders(body)){
905
+ const {shape,position,rotation}=this.backend.colliderSnapshot(collider);
906
+ let half,center=array3(position);
907
+ if(shape.kind==='box')half=boxAabbHalfExtents(shape.halfExtents,rotation);
908
+ else if(shape.kind==='cylinder')half=cylinderAabbHalfExtents(shape.radius,shape.halfHeight,rotation);
909
+ else if(shape.kind==='capsule')half=capsuleAabbHalfExtents(shape.radius,shape.halfHeight,rotation);
910
+ else if(shape.kind==='convexHull'&&shape.vertices?.length){
911
+ const box=convexAabb(shape.vertices,new THREE.Vector3(...center),rotation);
912
+ center=box.position;half=box.halfExtents;
913
+ }else return null;
914
+ if(![...center,...half].every(Number.isFinite))return null;
915
+ bounds.expandByPoint(new THREE.Vector3(...center.map((n,i)=>n-half[i])));
916
+ bounds.expandByPoint(new THREE.Vector3(...center.map((n,i)=>n+half[i])));
917
+ }
918
+ if(bounds.isEmpty())return null;
919
+ return {id,min:bounds.min.toArray(),max:bounds.max.toArray(),
920
+ center:bounds.getCenter(new THREE.Vector3()).toArray(),size:bounds.getSize(new THREE.Vector3()).toArray()};
921
+ }
922
+
923
+ manipulationBody(id, partName = ROOT_PART, { contacts = false } = {}) {
924
+ const entry = this.entries.get(id);
925
+ const part = partName === ROOT_PART ? null : entry?.parts.get(partName);
926
+ const body = part ? part.body : partName === ROOT_PART ? entry?.body : null;
927
+ const spec = part ? part.spec.physics : entry?.rootSpec;
928
+ const colliders = body ? this.backend.colliders(body) : [];
929
+ const contactCandidates = (contacts ? colliders : []).map(collider => {
930
+ const snapshot = this.backend.colliderSnapshot(collider), shape = snapshot.shape;
931
+ let vertexRadius = 0;
932
+ if (shape.vertices) for (let i=0;i<shape.vertices.length;i+=3) vertexRadius = Math.max(vertexRadius,Math.hypot(shape.vertices[i],shape.vertices[i+1],shape.vertices[i+2]));
933
+ const radius = shape.kind === 'box' ? Math.hypot(...array3(shape.halfExtents))
934
+ : shape.kind === 'cylinder' ? Math.hypot(shape.radius,shape.halfHeight)
935
+ : shape.kind === 'capsule' ? shape.radius+shape.halfHeight
936
+ : shape.vertices ? vertexRadius : null;
937
+ return { center:array3(snapshot.position), radius };
938
+ }).filter(candidate => Number.isFinite(candidate.radius) && candidate.radius > 0);
939
+ return { registered: Boolean(body), body: body ? this.backend.bodyType(body) : null,
940
+ joint: Boolean(part?.joint), mass: spec?.mass ?? null,
941
+ colliderCount:colliders.length, contactCandidates,
942
+ lockTranslation:spec?.lockTranslation || [false,false,false], lockRotation:spec?.lockRotation || [false,false,false] };
943
+ }
944
+
945
+ setMotion(id,motion={}, { partName = ROOT_PART } = {}) {
946
+ const entry=this.entries.get(id);
947
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
948
+ return body ? this.backend.setBodyMotion(body,motion) : false;
949
+ }
950
+
951
+ applyImpulse(id,impulse,{ partName = ROOT_PART, point = null, wake = true } = {}) {
952
+ const entry=this.entries.get(id);
953
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
954
+ return body ? this.backend.applyImpulse(body,impulse,{point,wake}) : false;
955
+ }
956
+
957
+ applyForce(id,force,{ partName = ROOT_PART, point = null, wake = true } = {}) {
958
+ const entry=this.entries.get(id);
959
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
960
+ return body ? this.backend.applyForce(body,force,{point,wake}) : false;
961
+ }
962
+
963
+ applyTorque(id,torque,{ partName = ROOT_PART, wake = true } = {}) {
964
+ const entry=this.entries.get(id);
965
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
966
+ return body ? this.backend.applyTorque(body,torque,{wake}) : false;
967
+ }
968
+
969
+ setMaterial(id,material={}, { partName = ROOT_PART } = {}) {
970
+ const entry=this.entries.get(id);
971
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
972
+ return body ? this.backend.setBodyMaterial(body,material) : false;
973
+ }
974
+
975
+ setDynamics(id,dynamics={}, { partName = ROOT_PART } = {}) {
976
+ const entry=this.entries.get(id);
977
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
978
+ return body ? this.backend.setBodyDynamics(body,dynamics) : false;
979
+ }
980
+
981
+ setCcd(id,enabled,{ partName = ROOT_PART } = {}) {
982
+ const entry=this.entries.get(id);
983
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
984
+ return body ? this.backend.setBodyCcd(body,Boolean(enabled)) : false;
985
+ }
986
+
987
+ sleep(id,{ partName = ROOT_PART } = {}) {
988
+ const entry=this.entries.get(id);
989
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
990
+ return body ? this.backend.sleepBody(body) : false;
991
+ }
992
+
993
+ wake(id,{ partName = ROOT_PART } = {}) {
994
+ const entry=this.entries.get(id);
995
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
996
+ return body ? this.backend.wakeBody(body) : false;
997
+ }
998
+
999
+ setSensor(id,enabled,{ partName = ROOT_PART } = {}) {
1000
+ const entry=this.entries.get(id);
1001
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
1002
+ if(!body) return false;
1003
+ const ok=this.backend.setBodySensor(body,Boolean(enabled));
1004
+ if(ok) for(const collider of this.backend.colliders(body)) {
1005
+ const key=this.backend.colliderKey(collider);
1006
+ const runtime=this.colliderRuntime.get(key) || {sensor:false,collisionEvents:false,collisionFilter:null};
1007
+ this.colliderRuntime.set(key,{...runtime,sensor:Boolean(enabled)});
1008
+ }
1009
+ return ok;
1010
+ }
1011
+
1012
+ setCollisionFilter(id,collision,{ partName = ROOT_PART } = {}) {
1013
+ const entry=this.entries.get(id);
1014
+ const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
1015
+ if(!body) return false;
1016
+ const collisionFilter=this._compileCollisionFilter(collision);
1017
+ const ok=this.backend.setBodyCollisionFilter(body,collisionFilter);
1018
+ if(ok) for(const collider of this.backend.colliders(body)) {
1019
+ const key=this.backend.colliderKey(collider);
1020
+ const runtime=this.colliderRuntime.get(key) || {sensor:false,collisionEvents:false,collisionFilter:null};
1021
+ this.colliderRuntime.set(key,{...runtime,collisionFilter});
1022
+ }
1023
+ return ok;
1024
+ }
1025
+
1026
+ getPartRestPose(id, partName) {
1027
+ const part = this.entries.get(id)?.parts.get(partName);
1028
+ if (!part) return null;
1029
+ return { position:part.restLocalPosition.toArray(), rotation:part.restLocalRotation.toArray() };
1030
+ }
1031
+
1032
+ getArticulationState(id, partName, { target = null } = {}) {
1033
+ const entry = this.entries.get(id);
1034
+ const part = entry?.parts.get(partName);
1035
+ if (!entry || !part?.node?.parent || part.spec?.joint?.type === 'fixed') return null;
1036
+ const parentFrame = part.parentName === ROOT_PART ? entry.root : entry.parts.get(part.parentName)?.node;
1037
+ if (!parentFrame) return null;
1038
+ entry.root.updateWorldMatrix(true, true);
1039
+ const parentWorldRotation = new THREE.Quaternion();
1040
+ const nodeParentWorldRotation = new THREE.Quaternion();
1041
+ parentFrame.getWorldQuaternion(parentWorldRotation);
1042
+ part.node.parent.getWorldQuaternion(nodeParentWorldRotation);
1043
+ if(entry.nativeArticulation)return this.#nativeArticulationCoordinate(entry,part,{id,partName,target});
1044
+ const axis = new THREE.Vector3(...(part.spec.joint.axis || [1,0,0])).normalize()
1045
+ .applyQuaternion(parentWorldRotation)
1046
+ .applyQuaternion(nodeParentWorldRotation.invert())
1047
+ .normalize();
1048
+ if (!Number.isFinite(axis.lengthSq()) || axis.lengthSq() < .99) return null;
1049
+
1050
+ let coordinate;
1051
+ if (part.spec.joint.type === 'prismatic') {
1052
+ coordinate = part.node.position.clone().sub(part.restLocalPosition).dot(axis);
1053
+ } else {
1054
+ const delta = part.node.quaternion.clone().multiply(part.restLocalRotation.clone().invert()).normalize();
1055
+ const angle = 2 * Math.atan2(delta.x*axis.x + delta.y*axis.y + delta.z*axis.z, delta.w);
1056
+ coordinate = Math.atan2(Math.sin(angle), Math.cos(angle));
1057
+ }
1058
+ if (!Number.isFinite(coordinate)) return null;
1059
+ const wrap = (value) => part.spec.joint.type === 'revolute' ? Math.atan2(Math.sin(value),Math.cos(value)) : value;
1060
+ const error = Number.isFinite(target) ? Math.abs(wrap(coordinate-target)) : null;
1061
+ return {
1062
+ id,partName,jointType:part.spec.joint.type,
1063
+ coordinate,target:Number.isFinite(target) ? target : null,error,
1064
+ tolerance:part.spec.joint.type === 'prismatic' ? .03 : .08,
1065
+ limits:part.spec.joint.limits ? [...part.spec.joint.limits] : null,
1066
+ localAxis:axis.toArray(),
1067
+ coordinateReference:'rest-zero-pose'
1068
+ };
1069
+ }
1070
+
1071
+ /** Native links retain a direct rigid parent. Read solver poses, not a prior render frame. */
1072
+ #nativeArticulationCoordinate(entry,part,{id,partName,target}){
1073
+ const parent=part.parentName===ROOT_PART?entry.body:entry.parts.get(part.parentName)?.body;
1074
+ const parentPose=this.backend.bodyPose(parent),childPose=this.backend.bodyPose(part.body);
1075
+ if(!parentPose||!childPose)return null;
1076
+ const inverse=new THREE.Quaternion(...parentPose.rotation).invert();
1077
+ const axis=new THREE.Vector3(...part.spec.joint.axis).normalize();
1078
+ const localPosition=new THREE.Vector3(...childPose.position).sub(new THREE.Vector3(...parentPose.position)).applyQuaternion(inverse);
1079
+ const localRotation=inverse.multiply(new THREE.Quaternion(...childPose.rotation));
1080
+ const type=part.spec.joint.type;
1081
+ const delta=localRotation.multiply(part.restLocalRotation.clone().invert()).normalize();
1082
+ const wrap=n=>Math.atan2(Math.sin(n),Math.cos(n));
1083
+ const coordinate=type==='prismatic'?localPosition.sub(part.restLocalPosition).dot(axis):
1084
+ wrap(2*Math.atan2(delta.x*axis.x+delta.y*axis.y+delta.z*axis.z,delta.w));
1085
+ if(!Number.isFinite(coordinate))return null;
1086
+ return {id,partName,jointType:type,coordinate,target:Number.isFinite(target)?target:null,
1087
+ error:Number.isFinite(target)?Math.abs(type==='revolute'?wrap(coordinate-target):coordinate-target):null,
1088
+ tolerance:type==='prismatic'?.03:.08,limits:[...part.spec.joint.limits],
1089
+ localAxis:axis.toArray(),coordinateReference:'rest-zero-pose'};
1090
+ }
1091
+
1092
+ articulationColliderPoses(id, partName, coordinate) {
1093
+ if (!this.backend.hasCapability('collision')) return {checked:false,reason:'PHYSICS_CAPABILITY_UNAVAILABLE',capability:'collision',id,partName,coordinate};
1094
+ const entry=this.entries.get(id);
1095
+ const part=entry?.parts.get(partName);
1096
+ if (!entry || !part?.node?.parent || !Number.isFinite(coordinate)) return {checked:false,reason:'PART_POSE_UNAVAILABLE',id,partName,coordinate};
1097
+ const state=this.getArticulationState(id,partName);
1098
+ if (!state) return {checked:false,reason:'JOINT_COORDINATE_UNAVAILABLE',id,partName,coordinate};
1099
+ const childAnchor=new THREE.Vector3(...(part.spec.joint.childAnchor || [0,0,0]));
1100
+ const parentRotation=new THREE.Quaternion();
1101
+ part.node.parent.updateWorldMatrix(true,false);
1102
+ if(entry.nativeArticulation){
1103
+ const parent=part.parentName===ROOT_PART?entry.body:entry.parts.get(part.parentName)?.body;
1104
+ const parentPose=this.backend.bodyPose(parent);
1105
+ if(!parentPose)return {checked:false,reason:'JOINT_AXIS_UNAVAILABLE',id,partName,coordinate};
1106
+ parentRotation.fromArray(parentPose.rotation);
1107
+ }else part.node.parent.getWorldQuaternion(parentRotation);
1108
+ const worldAxis=new THREE.Vector3(...state.localAxis).applyQuaternion(parentRotation).normalize();
1109
+ if (!Number.isFinite(worldAxis.lengthSq()) || worldAxis.lengthSq()<.99) return {checked:false,reason:'JOINT_AXIS_UNAVAILABLE',id,partName,coordinate};
1110
+
1111
+ const bodyPose=this.backend.bodyPose(part.body);
1112
+ const currentBodyPosition=new THREE.Vector3(...bodyPose.position);
1113
+ const currentBodyRotation=new THREE.Quaternion(...bodyPose.rotation).normalize();
1114
+ const delta=coordinate-state.coordinate;
1115
+ const bodyPosition=currentBodyPosition.clone();
1116
+ const bodyRotation=currentBodyRotation.clone();
1117
+ if (part.spec.joint.type==='prismatic') {
1118
+ bodyPosition.addScaledVector(worldAxis,delta);
1119
+ } else {
1120
+ const pivotWorld=childAnchor.clone().applyQuaternion(currentBodyRotation).add(currentBodyPosition);
1121
+ bodyRotation.premultiply(new THREE.Quaternion().setFromAxisAngle(worldAxis,delta)).normalize();
1122
+ bodyPosition.copy(pivotWorld).sub(childAnchor.clone().applyQuaternion(bodyRotation));
1123
+ }
1124
+
1125
+ const inverseCurrent=currentBodyRotation.clone().invert();
1126
+ const colliders=[];
1127
+ for(const [i,collider] of this.backend.colliders(part.body).entries()) {
1128
+ const snapshot=this.backend.colliderSnapshot(collider);
1129
+ const currentColliderPosition=new THREE.Vector3(snapshot.position.x,snapshot.position.y,snapshot.position.z);
1130
+ const currentColliderRotation=new THREE.Quaternion(snapshot.rotation.x,snapshot.rotation.y,snapshot.rotation.z,snapshot.rotation.w).normalize();
1131
+ const localPosition=currentColliderPosition.clone().sub(currentBodyPosition).applyQuaternion(inverseCurrent);
1132
+ const localRotation=inverseCurrent.clone().multiply(currentColliderRotation).normalize();
1133
+ const position=localPosition.clone().applyQuaternion(bodyRotation).add(bodyPosition);
1134
+ const rotation=bodyRotation.clone().multiply(localRotation).normalize();
1135
+ colliders.push({index:i,shape:snapshot.shape,shapeRef:snapshot.shapeRef,position,rotation});
1136
+ }
1137
+ return {checked:true,id,partName,jointType:state.jointType,currentCoordinate:state.coordinate,coordinate,parentName:part.parentName,frameAssumption:'parent-pose-at-query',colliders};
1138
+ }
1139
+
1140
+ shapeBoundingRadius(shape) {
1141
+ if (!shape) return null;
1142
+ if (shape.halfExtents) {
1143
+ const h=shape.halfExtents;
1144
+ const border=Number(shape.borderRadius) || 0;
1145
+ return Math.hypot(h.x+border,h.y+border,h.z+border);
1146
+ }
1147
+ if (Number.isFinite(shape.halfHeight) && Number.isFinite(shape.radius)) {
1148
+ const border=Number(shape.borderRadius) || 0;
1149
+ return Math.hypot(shape.radius+border,shape.halfHeight+shape.radius+border);
1150
+ }
1151
+ if (Number.isFinite(shape.radius)) return shape.radius;
1152
+ if (shape.vertices?.length) {
1153
+ let radius=0;
1154
+ for(let i=0;i+2<shape.vertices.length;i+=3) radius=Math.max(radius,Math.hypot(shape.vertices[i],shape.vertices[i+1],shape.vertices[i+2]));
1155
+ return radius || null;
1156
+ }
1157
+ if (shape.a && shape.b) return Math.max(Math.hypot(shape.a.x,shape.a.y,shape.a.z),Math.hypot(shape.b.x,shape.b.y,shape.b.z));
1158
+ return null;
1159
+ }
1160
+
1161
+ articulationCounterfactualSampleCount(id, partName, current, target, { minSamples = 5, maxSamples = 33 } = {}) {
1162
+ const entry=this.entries.get(id);
1163
+ const part=entry?.parts.get(partName);
1164
+ if (!part || !Number.isFinite(current) || !Number.isFinite(target)) return {checked:false,reason:'PART_SAMPLE_GEOMETRY_UNAVAILABLE'};
1165
+ const delta=Math.abs(target-current);
1166
+ if (delta<1e-9) return {checked:true,count:minSamples,delta,maxTravel:0,resolution:.08};
1167
+ const bodyPose=this.backend.bodyPose(part.body);
1168
+ const bodyPosition=new THREE.Vector3(...bodyPose.position);
1169
+ const bodyRotation=new THREE.Quaternion(...bodyPose.rotation).normalize();
1170
+ const inverseBody=bodyRotation.clone().invert();
1171
+ const childAnchor=new THREE.Vector3(...(part.spec.joint.childAnchor || [0,0,0]));
1172
+ let minRadius=Infinity,maxLever=0,covered=0;
1173
+ for(const collider of this.backend.colliders(part.body)) {
1174
+ const snapshot=this.backend.colliderSnapshot(collider);
1175
+ const radius=this.shapeBoundingRadius(snapshot.shape);
1176
+ if (!Number.isFinite(radius) || radius<=0) continue;
1177
+ const localCenter=new THREE.Vector3(snapshot.position.x,snapshot.position.y,snapshot.position.z).sub(bodyPosition).applyQuaternion(inverseBody);
1178
+ minRadius=Math.min(minRadius,radius);
1179
+ maxLever=Math.max(maxLever,localCenter.distanceTo(childAnchor)+radius);
1180
+ covered+=1;
1181
+ }
1182
+ if (!covered || !Number.isFinite(minRadius)) return {checked:false,reason:'COLLIDER_EXTENT_UNAVAILABLE'};
1183
+ const maxTravel=part.spec.joint.type==='revolute' ? delta*maxLever : delta;
1184
+ const resolution=THREE.MathUtils.clamp(minRadius*.35,.02,.08);
1185
+ const count=THREE.MathUtils.clamp(Math.ceil(maxTravel/resolution)+1,minSamples,maxSamples);
1186
+ return {checked:true,count,delta,maxTravel,resolution,colliders:covered,minRadius,maxLever:part.spec.joint.type==='revolute'?maxLever:null};
1187
+ }
1188
+
1189
+ articulationPairCounterfactual(originalId, originalPartName, originalTarget, blockerId, blockerPartName, blockerTarget, { samples = null } = {}) {
1190
+ const originalState=this.getArticulationState(originalId,originalPartName,{target:originalTarget});
1191
+ const blockerState=this.getArticulationState(blockerId,blockerPartName,{target:blockerTarget});
1192
+ if (!originalState || !blockerState) return {checked:false,reason:'JOINT_COORDINATE_UNAVAILABLE'};
1193
+ if (!Number.isFinite(originalTarget) || !Number.isFinite(blockerTarget)) return {checked:false,reason:'TARGET_UNAVAILABLE'};
1194
+ const fixedSamples=Number.isFinite(samples) ? Math.max(2,Math.min(33,Math.trunc(samples))) : null;
1195
+ const pairedSamples=samples && typeof samples==='object' ? {
1196
+ original:Math.max(2,Math.min(33,Math.trunc(samples.original) || 2)),
1197
+ blocker:Math.max(2,Math.min(33,Math.trunc(samples.blocker) || 2))
1198
+ } : null;
1199
+ const originalSampling=fixedSamples ? {checked:true,count:fixedSamples,mode:'fixed'}
1200
+ : pairedSamples ? {checked:true,count:pairedSamples.original,mode:'fixed-pair'}
1201
+ : this.articulationCounterfactualSampleCount(originalId,originalPartName,originalState.coordinate,originalTarget);
1202
+ const blockerSampling=fixedSamples ? {checked:true,count:fixedSamples,mode:'fixed'}
1203
+ : pairedSamples ? {checked:true,count:pairedSamples.blocker,mode:'fixed-pair'}
1204
+ : this.articulationCounterfactualSampleCount(blockerId,blockerPartName,blockerState.coordinate,blockerTarget);
1205
+ if (!originalSampling.checked) return {checked:false,reason:originalSampling.reason,source:'original-sampling'};
1206
+ if (!blockerSampling.checked) return {checked:false,reason:blockerSampling.reason,source:'blocker-sampling'};
1207
+
1208
+ const trajectory=(id,partName,current,target,count)=>{
1209
+ const poses=[];
1210
+ for(let i=0;i<count;i++) {
1211
+ const alpha=i/(count-1);
1212
+ const coordinate=current+(target-current)*alpha;
1213
+ const pose=this.articulationColliderPoses(id,partName,coordinate);
1214
+ if (!pose.checked) return pose;
1215
+ poses.push(pose);
1216
+ }
1217
+ return {checked:true,poses};
1218
+ };
1219
+ const original=trajectory(originalId,originalPartName,originalState.coordinate,originalTarget,originalSampling.count);
1220
+ if (!original.checked) return {checked:false,reason:original.reason,source:'original'};
1221
+ const blocker=trajectory(blockerId,blockerPartName,blockerState.coordinate,blockerTarget,blockerSampling.count);
1222
+ if (!blocker.checked) return {checked:false,reason:blocker.reason,source:'blocker'};
1223
+
1224
+ const pairAt=(a,b)=>{
1225
+ let intersections=0;
1226
+ for(const left of a.colliders) for(const right of b.colliders) {
1227
+ if(this.backend.shapesIntersect(
1228
+ left.shapeRef,left.position.toArray(),left.rotation,
1229
+ right.shapeRef,right.position.toArray(),right.rotation
1230
+ )) intersections+=1;
1231
+ }
1232
+ return intersections;
1233
+ };
1234
+ const againstPose=(originalPoses,blockerPose)=>{
1235
+ let conflictSamples=0,pairIntersections=0;
1236
+ for(const originalPose of originalPoses) {
1237
+ const pairs=pairAt(originalPose,blockerPose);
1238
+ if (pairs) conflictSamples+=1;
1239
+ pairIntersections+=pairs;
1240
+ }
1241
+ return {conflictSamples,pairIntersections};
1242
+ };
1243
+ const trajectoryConflict=(originalPoses,blockerPoses)=>{
1244
+ let conflictSamplePairs=0,pairIntersections=0;
1245
+ for(const originalPose of originalPoses) for(const blockerPose of blockerPoses) {
1246
+ const pairs=pairAt(originalPose,blockerPose);
1247
+ if (pairs) conflictSamplePairs+=1;
1248
+ pairIntersections+=pairs;
1249
+ }
1250
+ return {conflictSamplePairs,pairIntersections};
1251
+ };
1252
+ const current=againstPose(original.poses,blocker.poses[0]);
1253
+ const target=againstPose(original.poses,blocker.poses.at(-1));
1254
+ const action=trajectoryConflict(original.poses,blocker.poses);
1255
+ return {
1256
+ checked:true,geometry:this.backend.evidenceGeometry('shape-pairs'),causal:false,frameAssumption:'parent-poses-static-during-hypothesis',
1257
+ samples:{original:originalSampling.count,blocker:blockerSampling.count,mode:fixedSamples?'fixed':pairedSamples?'fixed-pair':'adaptive'},
1258
+ sampling:{original:originalSampling,blocker:blockerSampling},
1259
+ original:{id:originalId,partName:originalPartName,currentCoordinate:originalState.coordinate,target:originalTarget},
1260
+ blocker:{id:blockerId,partName:blockerPartName,currentCoordinate:blockerState.coordinate,target:blockerTarget},
1261
+ current,target,action,
1262
+ targetSweepClear:target.conflictSamples===0,
1263
+ conflictReduction:Math.max(0,current.conflictSamples-target.conflictSamples)
1264
+ };
1265
+ }
1266
+
1267
+ articulationWorldCounterfactual(id, partName, target, { excludeObjectIds = [], excludeParts = [], samples = null } = {}) {
1268
+ const state=this.getArticulationState(id,partName,{target});
1269
+ if (!state || !Number.isFinite(target)) return {checked:false,reason:'JOINT_COORDINATE_UNAVAILABLE',id,partName};
1270
+ const fixedSamples=Number.isFinite(samples) ? Math.max(2,Math.min(33,Math.trunc(samples))) : null;
1271
+ const sampling=fixedSamples ? {checked:true,count:fixedSamples,mode:'fixed'} : this.articulationCounterfactualSampleCount(id,partName,state.coordinate,target);
1272
+ if (!sampling.checked) return {checked:false,reason:sampling.reason,source:'sampling',id,partName};
1273
+ const excluded=new Set([id,...excludeObjectIds]);
1274
+ const excludedParts=new Set(excludeParts.map((item)=>`${item.objectId}:${item.partName || ROOT_PART}`));
1275
+ const keyOf=(provenance,collider)=>{
1276
+ const colliderKey=this.backend.colliderKey(collider);
1277
+ if (provenance?.kind==='environment') return `environment:${provenance.environmentId || '$environment'}:${provenance.colliderIndex ?? colliderKey}`;
1278
+ if (provenance?.kind==='object') return `object:${provenance.objectId}:${provenance.partName || ROOT_PART}:${provenance.colliderIndex ?? colliderKey}`;
1279
+ return `unknown:${colliderKey}`;
1280
+ };
1281
+ const describe=(provenance,collider,key)=>provenance?.kind==='environment'
1282
+ ? {key,kind:'environment',environmentId:provenance.environmentId || '$environment',colliderIndex:provenance.colliderIndex ?? null}
1283
+ : provenance?.kind==='object'
1284
+ ? {key,kind:'object',objectId:provenance.objectId,partName:provenance.partName || ROOT_PART,colliderIndex:provenance.colliderIndex ?? null}
1285
+ : {key,kind:'unknown',colliderHandle:this.backend.colliderKey(collider)};
1286
+ const poseHits=(pose)=>{
1287
+ const hits=new Map();
1288
+ for(const source of pose.colliders) {
1289
+ this.backend.intersectionsWithShape(this.world,source.position.toArray(),source.rotation,source.shapeRef,(other)=>{
1290
+ const provenance=this.provenanceOfCollider(other);
1291
+ if (provenance?.kind==='object' && (excluded.has(provenance.objectId) || excludedParts.has(`${provenance.objectId}:${provenance.partName || ROOT_PART}`))) return true;
1292
+ const key=keyOf(provenance,other);
1293
+ if (!hits.has(key)) hits.set(key,describe(provenance,other,key));
1294
+ return true;
1295
+ });
1296
+ }
1297
+ return hits;
1298
+ };
1299
+ this.backend.syncSceneQueries(this.world);
1300
+ const poses=[];
1301
+ for(let i=0;i<sampling.count;i++) {
1302
+ const alpha=i/(sampling.count-1);
1303
+ const coordinate=state.coordinate+(target-state.coordinate)*alpha;
1304
+ const pose=this.articulationColliderPoses(id,partName,coordinate);
1305
+ if (!pose.checked) return {checked:false,reason:pose.reason,source:'trajectory',id,partName};
1306
+ poses.push(pose);
1307
+ }
1308
+ const currentHits=poseHits(poses[0]);
1309
+ const targetHits=poseHits(poses.at(-1));
1310
+ const actionHits=new Map();
1311
+ const sampleConflicts=[];
1312
+ for(let sampleIndex=0;sampleIndex<poses.length;sampleIndex++) {
1313
+ const hits=poseHits(poses[sampleIndex]);
1314
+ if (hits.size) sampleConflicts.push({sampleIndex,coordinate:poses[sampleIndex].coordinate,blockers:[...hits.keys()]});
1315
+ for(const [key,value] of hits) if (!actionHits.has(key)) actionHits.set(key,value);
1316
+ }
1317
+ const introduced=(hits)=>[...hits.entries()].filter(([key])=>!currentHits.has(key)).map(([,value])=>value);
1318
+ const current=[...currentHits.values()];
1319
+ const targetAll=[...targetHits.values()];
1320
+ const actionAll=[...actionHits.values()];
1321
+ const introducedTarget=introduced(targetHits);
1322
+ const introducedAction=introduced(actionHits);
1323
+ return {
1324
+ checked:true,geometry:this.backend.evidenceGeometry('world-shape-query'),causal:false,
1325
+ frameAssumption:'other-world-colliders-static-during-hypothesis',
1326
+ id,partName,currentCoordinate:state.coordinate,target,
1327
+ excludedObjectIds:[...excluded].sort(),excludedParts:[...excludedParts].sort(),
1328
+ samples:{count:sampling.count,mode:fixedSamples?'fixed':'adaptive'},sampling,
1329
+ current:{blockers:current},targetPose:{blockers:targetAll,introducedBlockers:introducedTarget},
1330
+ actionEnvelope:{blockers:actionAll,introducedBlockers:introducedAction,sampleConflicts},
1331
+ targetIntroducesNoCollision:introducedTarget.length===0,
1332
+ actionIntroducesNoCollision:introducedAction.length===0
1333
+ };
1334
+ }
1335
+
1336
+ articulationPairCounterfactualConvergence(originalId, originalPartName, originalTarget, blockerId, blockerPartName, blockerTarget, { multiplier = 2 } = {}) {
1337
+ const base=this.articulationPairCounterfactual(originalId,originalPartName,originalTarget,blockerId,blockerPartName,blockerTarget);
1338
+ if (!base.checked) return {checked:false,reason:base.reason || 'BASE_COUNTERFACTUAL_UNAVAILABLE',base};
1339
+ const denserCount=(count)=>Math.min(33,Math.max(count+2,Math.ceil(count*Math.max(1.25,multiplier))));
1340
+ const denseSamples={original:denserCount(base.samples.original),blocker:denserCount(base.samples.blocker)};
1341
+ const dense=this.articulationPairCounterfactual(originalId,originalPartName,originalTarget,blockerId,blockerPartName,blockerTarget,{samples:denseSamples});
1342
+ if (!dense.checked) return {checked:false,reason:dense.reason || 'DENSE_COUNTERFACTUAL_UNAVAILABLE',base,dense};
1343
+ const ratio=(value,total)=>total>0?value/total:0;
1344
+ const baseRatios={
1345
+ current:ratio(base.current.conflictSamples,base.samples.original),
1346
+ target:ratio(base.target.conflictSamples,base.samples.original),
1347
+ action:ratio(base.action.conflictSamplePairs,base.samples.original*base.samples.blocker)
1348
+ };
1349
+ const denseRatios={
1350
+ current:ratio(dense.current.conflictSamples,dense.samples.original),
1351
+ target:ratio(dense.target.conflictSamples,dense.samples.original),
1352
+ action:ratio(dense.action.conflictSamplePairs,dense.samples.original*dense.samples.blocker)
1353
+ };
1354
+ const drift={
1355
+ current:Math.abs(baseRatios.current-denseRatios.current),
1356
+ target:Math.abs(baseRatios.target-denseRatios.target),
1357
+ action:Math.abs(baseRatios.action-denseRatios.action)
1358
+ };
1359
+ const qualitative={
1360
+ targetSweepClear:base.targetSweepClear===dense.targetSweepClear,
1361
+ clearanceGain:(base.conflictReduction>0)===(dense.conflictReduction>0)
1362
+ };
1363
+ return {
1364
+ checked:true,causal:false,status:qualitative.targetSweepClear&&qualitative.clearanceGain?'stable':'unstable',
1365
+ base,dense,
1366
+ qualitative,
1367
+ ratios:{base:baseRatios,dense:denseRatios,drift},
1368
+ maxRatioDrift:Math.max(drift.current,drift.target,drift.action)
1369
+ };
1370
+ }
1371
+
1372
+ ownerOfBody(body) {
1373
+ const key=this.backend.bodyKey(body);
1374
+ for (const [id,entry] of this.entries) {
1375
+ if (this.backend.bodyKey(entry.body)===key) return {id,part:'$root'};
1376
+ for (const [part,value] of entry.parts) if (this.backend.bodyKey(value.body)===key) return {id,part};
1377
+ }
1378
+ return null;
1379
+ }
1380
+
1381
+ raycast(origin, target, { excludeId = null, excludeIds = [] } = {}) {
1382
+ if (!this.backend.hasCapability('scene-query')) return null;
1383
+ const direction = [target[0] - origin[0], target[1] - origin[1], target[2] - origin[2]];
1384
+ const distance = Math.hypot(...direction);
1385
+ if (!Number.isFinite(distance) || distance < 1e-8 || !this.world) return null;
1386
+ const normalized = direction.map((value) => value / distance);
1387
+ const excluded = new Set([...(excludeId ? [excludeId] : []), ...excludeIds]);
1388
+ const filter=excluded.size ? (collider)=>{
1389
+ const parent=this.backend.colliderParent(collider);
1390
+ const owner=parent ? this.ownerOfBody(parent) : null;
1391
+ return !owner || !excluded.has(owner.id);
1392
+ } : undefined;
1393
+ const hit=this.backend.raycast(this.world,origin,normalized,distance,{solid:true,predicate:filter});
1394
+ if(!hit) return null;
1395
+ const body=this.backend.colliderParent(hit.collider);
1396
+ const owner=body ? this.ownerOfBody(body) : null;
1397
+ return {
1398
+ id:owner?.id || null,
1399
+ part:owner?.part || null,
1400
+ environment:!owner,
1401
+ provenance:this.provenanceOfCollider(hit.collider),
1402
+ distance:hit.timeOfImpact,
1403
+ point:[
1404
+ origin[0] + normalized[0] * hit.timeOfImpact,
1405
+ origin[1] + normalized[1] * hit.timeOfImpact,
1406
+ origin[2] + normalized[2] * hit.timeOfImpact
1407
+ ]
1408
+ };
1409
+ }
1410
+
1411
+ faceCharacter(id, direction) {
1412
+ const entry = this.entries.get(id);
1413
+ if (!entry) return false;
1414
+ const length = Math.hypot(direction[0], direction[2]);
1415
+ if (length < 1e-8) return false;
1416
+ const yaw = Math.atan2(-direction[0], -direction[2]);
1417
+ if (!entry.body) return this.setCharacterYaw(id, yaw);
1418
+ if (this.backend.bodyType(entry.body)!=='kinematic') return false;
1419
+ this.backend.setBodyPose(entry.body,{rotation:[0,Math.sin(yaw/2),0,Math.cos(yaw/2)],next:true});
1420
+ return true;
1421
+ }
1422
+
1423
+ setCharacterYaw(id, yaw) {
1424
+ const entry = this.entries.get(id);
1425
+ if (!entry || !Number.isFinite(yaw)) return false;
1426
+ const rotation = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0),yaw);
1427
+ if (entry.body) {
1428
+ if (this.backend.bodyType(entry.body)!=='kinematic') return false;
1429
+ this.backend.setBodyPose(entry.body,{rotation});
1430
+ this.backend.setBodyPose(entry.body,{rotation,next:true});
1431
+ }
1432
+ entry.root.quaternion.copy(rotation);
1433
+ entry.lastRotation.copy(rotation);
1434
+ entry.root.updateMatrixWorld(true);
1435
+ return true;
1436
+ }
1437
+
1438
+ moveCharacter(id, desiredTranslation, { ignoreIds = [] } = {}) {
1439
+ if (!this.backend.hasCapability('character-controller')) {
1440
+ return { success:false, code:'PHYSICS_CAPABILITY_UNAVAILABLE', capability:'character-controller', movement:[0,0,0], grounded:false, collisions:[] };
1441
+ }
1442
+ const entry=this.entries.get(id);
1443
+ if(!entry?.body || !this.characterController) {
1444
+ return {success:false,code:'CHARACTER_BODY_UNAVAILABLE',movement:[0,0,0],grounded:false,collisions:[]};
1445
+ }
1446
+ const ignored=new Set(ignoreIds);
1447
+ const result=this.backend.moveCharacter(this.characterController,entry.body,desiredTranslation,{
1448
+ predicate:(other)=>{
1449
+ const parent=this.backend.colliderParent(other);
1450
+ const owner=parent ? this.ownerOfBody(parent) : null;
1451
+ return !owner || !ignored.has(owner.id);
1452
+ }
1453
+ });
1454
+ if(!result.success) return result;
1455
+ return {
1456
+ ...result,
1457
+ collisions:result.collisions.map(({colliderKey,toi,normal})=>({colliderHandle:colliderKey,toi,normal}))
1458
+ };
1459
+ }
1460
+
1461
+ setArticulationTarget(id, partName, target) {
1462
+ const part = this.entries.get(id)?.parts.get(partName);
1463
+ if (!part || !Number.isFinite(target)) return false;
1464
+ if (!part.joint || !part.body) {
1465
+ if (!this.hasCapability('articulation-pose')) return false;
1466
+ const limits = part.spec.joint.limits || [];
1467
+ if (limits.length === 2 && (target < limits[0] || target > limits[1])) return false;
1468
+ const state = this.getArticulationState(id, partName);
1469
+ if (!state) return false;
1470
+ const axis = new THREE.Vector3(...state.localAxis).normalize();
1471
+ if (part.spec.joint.type === 'prismatic') {
1472
+ part.node.position.copy(part.restLocalPosition).addScaledVector(axis, target);
1473
+ } else if (part.spec.joint.type === 'revolute') {
1474
+ const rotation = new THREE.Quaternion().setFromAxisAngle(axis, target);
1475
+ part.node.quaternion.copy(part.restLocalRotation).premultiply(rotation).normalize();
1476
+ } else return false;
1477
+ part.node.updateMatrixWorld(true);
1478
+ part.lastLocalPosition.copy(part.node.position);
1479
+ part.lastLocalRotation.copy(part.node.quaternion);
1480
+ return true;
1481
+ }
1482
+ const motor=part.spec.joint.motor || {};
1483
+ const applied=this.backend.setJointTarget(part.joint,target,motor);
1484
+ if(!applied) return false;
1485
+ part.motorTarget=target;
1486
+ this.backend.wakeBody(part.body);
1487
+ return true;
1488
+ }
1489
+
1490
+ holdArticulationCurrent(id, partName) {
1491
+ const part = this.entries.get(id)?.parts.get(partName);
1492
+ const state = this.getArticulationState(id,partName);
1493
+ if (!part || !state) return false;
1494
+ if (!part.joint || !part.body) return this.hasCapability('articulation-pose');
1495
+ const motor=part.spec.joint.motor || {};
1496
+ const applied=this.backend.setJointTarget(part.joint,state.coordinate,motor);
1497
+ if(!applied) return false;
1498
+ part.motorTarget=state.coordinate;
1499
+ this.backend.wakeBody(part.body);
1500
+ return true;
1501
+ }
1502
+
1503
+ /** Read-only hypothetical collider descriptors, not a solver mutation. */
1504
+ nativeNavigationJointPose(id,partName,target){
1505
+ const entry=this.entries.get(id),part=entry?.parts.get(partName);
1506
+ const limits=part?.spec.joint?.limits;
1507
+ if(!entry?.nativeArticulation||!limits||!Number.isFinite(target)||target<limits[0]||target>limits[1])
1508
+ return {checked:false,reason:'NATIVE_NAVIGATION_JOINT_UNAVAILABLE'};
1509
+ const pose=this.articulationColliderPoses(id,partName,target);
1510
+ if(!pose.checked)return pose;
1511
+ const descriptors=pose.colliders.map(c=>navigationObstacleDescriptor(id,partName,c.index,c));
1512
+ if(!descriptors.length||descriptors.some(c=>!c))return {checked:false,reason:'NATIVE_NAVIGATION_COLLIDER_UNSUPPORTED'};
1513
+ return {checked:true,currentCoordinate:pose.currentCoordinate,descriptors};
1514
+ }
1515
+
1516
+ getNavigationObstacles() {
1517
+ if (!this.backend.hasCapability('collision')) return {items:[],skipped:[{reason:'physics-capability-unavailable',capability:'collision'}]};
1518
+ this.backend.syncSceneQueries(this.world);
1519
+ const items = [];
1520
+ const skipped = [];
1521
+ const addBody=(objectId,partName,body,bodyType,navigationObstacle=true)=>{
1522
+ if(bodyType==='fixed' || navigationObstacle===false) return;
1523
+ for(const [i,collider] of this.backend.colliders(body).entries()) {
1524
+ const snapshot=this.backend.colliderSnapshot(collider);
1525
+ const {shape,position,rotation}=snapshot;
1526
+ const descriptor=navigationObstacleDescriptor(objectId,partName,i,{shape,position,rotation});
1527
+ if(descriptor)items.push(descriptor);
1528
+ else skipped.push({id:objectId+':'+partName+':'+i,objectId,part:partName,collider:i,reason:'unsupported-shape',shapeType:shape.kind});
1529
+ }
1530
+ };
1531
+
1532
+ for (const [id, entry] of this.entries) {
1533
+ if (!entry.held) addBody(id, '$root', entry.body, entry.rootSpec.body || 'fixed', entry.rootSpec.navigationObstacle);
1534
+ for (const [partName, part] of entry.parts) addBody(id, partName, part.body, part.spec.physics?.body || 'dynamic');
1535
+ }
1536
+ return { items, skipped };
1537
+ }
1538
+
1539
+ articulationContacts(id, partName) {
1540
+ if (!this.backend.hasCapability('collision')) return [];
1541
+ const entry=this.entries.get(id);
1542
+ const part=entry?.parts.get(partName);
1543
+ const body = partName === ROOT_PART ? entry?.body : part?.body;
1544
+ if (!entry || !body || !this.world) return [];
1545
+ const contacts=[];
1546
+ for(const [sourceIndex,source] of this.backend.colliders(body).entries()) {
1547
+ const sourceOwner=this.provenanceOfCollider(source) || {kind:'object',objectId:id,partName,colliderIndex:sourceIndex};
1548
+ for(const pair of this.backend.contactPairs(this.world,source)) {
1549
+ const target=this.provenanceOfCollider(pair.other);
1550
+ const external=!target || target.kind==='environment' || target.objectId!==id;
1551
+ contacts.push({
1552
+ source:sourceOwner,
1553
+ target:target || {kind:'unknown',colliderIndex:null},
1554
+ external,
1555
+ manifoldCount:pair.manifoldCount,
1556
+ contactCount:pair.contactCount,
1557
+ activeContactCount:pair.activeContactCount,
1558
+ minDistance:pair.minDistance,
1559
+ totalImpulse:Number.isFinite(pair.totalImpulse)?pair.totalImpulse:null,
1560
+ evidenceKind:pair.evidenceKind || 'contact',
1561
+ impulseAvailable:pair.impulseAvailable===true,
1562
+ normal:pair.normal
1563
+ });
1564
+ }
1565
+ }
1566
+ contacts.sort((a,b)=>{
1567
+ const ak=`${a.target.kind}:${a.target.objectId || a.target.environmentId || ''}:${a.target.partName || ''}:${a.target.colliderIndex ?? -1}:${a.source.colliderIndex}`;
1568
+ const bk=`${b.target.kind}:${b.target.objectId || b.target.environmentId || ''}:${b.target.partName || ''}:${b.target.colliderIndex ?? -1}:${b.source.colliderIndex}`;
1569
+ return ak.localeCompare(bk);
1570
+ });
1571
+ return contacts;
1572
+ }
1573
+
1574
+ articulationPenetrations(id, partName, { refresh = false } = {}) {
1575
+ if (!this.backend.hasCapability('collision')) return [];
1576
+ if(refresh) this.backend.syncSceneQueries(this.world);
1577
+ const entry=this.entries.get(id);
1578
+ const part=entry?.parts.get(partName);
1579
+ if(!entry || !part) return [];
1580
+ const owners=new Map([[this.backend.bodyKey(entry.body),'$root']]);
1581
+ for(const [name,value] of entry.parts) owners.set(this.backend.bodyKey(value.body),name);
1582
+ const hits=new Map();
1583
+
1584
+ for(const [i,source] of this.backend.colliders(part.body).entries()) {
1585
+ for(const penetration of this.backend.penetrations(this.world,source)) {
1586
+ const otherBody=this.backend.colliderParent(penetration.other);
1587
+ if(!otherBody || this.backend.bodyKey(otherBody)===this.backend.bodyKey(part.body)) continue;
1588
+ const targetPart=owners.get(this.backend.bodyKey(otherBody)) || '$external';
1589
+ const targetColliders=this.backend.colliders(otherBody);
1590
+ const otherKey=this.backend.colliderKey(penetration.other);
1591
+ const targetIndex=targetColliders.findIndex((collider)=>this.backend.colliderKey(collider)===otherKey);
1592
+ const key=`${partName}[${i}]->${targetPart}[${targetIndex}]`;
1593
+ const depth=-penetration.distance;
1594
+ const previous=hits.get(key);
1595
+ if(!previous || depth>previous.depth) hits.set(key,{key,depth,sourcePart:partName,sourceCollider:i,targetPart,targetCollider:targetIndex});
1596
+ }
1597
+ }
1598
+ return [...hits.values()];
1599
+ }
1600
+
1601
+ dispose() {
1602
+ this.entries.clear();
1603
+ this.colliderProvenance.clear();
1604
+ this.colliderHandles.clear();
1605
+ this.colliderRuntime.clear();
1606
+ this.collisionPairs.clear();
1607
+ this.collisionEvents.length=0;
1608
+ this.collisionGroupBits.clear();
1609
+ if(this.world && this.characterController) this.backend.removeCharacterController(this.world,this.characterController);
1610
+ this.characterController = null;
1611
+ this.backend.dispose(this.world);
1612
+ this.world = null;
1613
+ }
1614
+
1615
+ step(dt, store) {
1616
+ this.backend.step(this.world, dt);
1617
+ this.updateCollisionEvents();
1618
+ return this.writeback(store);
1619
+ }
1620
+
1621
+ getCollisionEvents({ clear = true } = {}) {
1622
+ const events=this.collisionEvents.map((event)=>structuredClone(event));
1623
+ if(clear) this.collisionEvents.length=0;
1624
+ return events;
1625
+ }
1626
+
1627
+ updateCollisionEvents() {
1628
+ if(!this.world || !this.backend.hasCapability('collision')) return;
1629
+ const watched=[...this.colliderRuntime.entries()].filter(([,runtime])=>runtime.sensor || runtime.collisionEvents);
1630
+ if(!watched.length) { this.collisionPairs.clear(); return; }
1631
+ this.backend.syncSceneQueries(this.world);
1632
+ const current=new Map();
1633
+ const descriptor=(key)=>{
1634
+ const p=this.colliderProvenance.get(key);
1635
+ if(!p) return {kind:'unknown',colliderKey:key};
1636
+ if(p.kind==='environment') return {kind:'environment',environmentId:p.environmentId || '$environment',colliderIndex:p.colliderIndex ?? null};
1637
+ return {kind:'object',objectId:p.objectId,partName:p.partName || ROOT_PART,colliderIndex:p.colliderIndex ?? null};
1638
+ };
1639
+ const addPair=(leftKey,rightKey)=>{
1640
+ if(leftKey==null || rightKey==null || leftKey===rightKey) return;
1641
+ const a=leftKey<rightKey?leftKey:rightKey,b=leftKey<rightKey?rightKey:leftKey,key=String(a)+':'+String(b);
1642
+ if(current.has(key)) return;
1643
+ const ar=this.colliderRuntime.get(a),br=this.colliderRuntime.get(b);
1644
+ if(!this._collisionPairAllowed(ar,br)) return;
1645
+ current.set(key,{key,sensor:Boolean(ar?.sensor || br?.sensor),a:descriptor(a),b:descriptor(b)});
1646
+ };
1647
+ for(const [sourceKey,sourceRuntime] of watched) {
1648
+ const source=this.colliderHandles.get(sourceKey);
1649
+ if(!source) continue;
1650
+ if(sourceRuntime.sensor) {
1651
+ const snapshot=this.backend.colliderSnapshot(source);
1652
+ if(!snapshot) continue;
1653
+ this.backend.intersectionsWithShape(this.world,snapshot.position,snapshot.rotation,snapshot.shapeRef,(other)=>{
1654
+ const otherKey=this.backend.colliderKey(other);
1655
+ const otherBody=this.backend.colliderParent(other),sourceBody=this.backend.colliderParent(source);
1656
+ if(otherKey!==sourceKey && this.backend.bodyKey(otherBody)!==this.backend.bodyKey(sourceBody)) addPair(sourceKey,otherKey);
1657
+ return true;
1658
+ },{excludeCollider:source});
1659
+ } else {
1660
+ for(const pair of this.backend.contactPairs(this.world,source)) addPair(sourceKey,this.backend.colliderKey(pair.other));
1661
+ }
1662
+ }
1663
+ for(const [key,pair] of current) if(!this.collisionPairs.has(key)) this.collisionEvents.push({type:pair.sensor?'sensor-entered':'collision-started',a:pair.a,b:pair.b});
1664
+ for(const [key,pair] of this.collisionPairs) if(!current.has(key)) this.collisionEvents.push({type:pair.sensor?'sensor-exited':'collision-ended',a:pair.a,b:pair.b});
1665
+ this.collisionPairs=current;
1666
+ }
1667
+
1668
+ writeback(store) {
1669
+ let changed = false;
1670
+ if (!this.solverEnabled) {
1671
+ for (const [id, entry] of this.entries) {
1672
+ const record = store.has(id) ? store.get(id) : null;
1673
+ if (!record) continue;
1674
+ record.object.updateMatrixWorld(true);
1675
+ const p = new THREE.Vector3();
1676
+ const q = new THREE.Quaternion();
1677
+ record.object.getWorldPosition(p);
1678
+ record.object.getWorldQuaternion(q);
1679
+ if (p.distanceToSquared(entry.lastPosition) > 1e-10 || 1 - Math.abs(q.dot(entry.lastRotation)) > 1e-10) changed = true;
1680
+ entry.lastPosition.copy(p);
1681
+ entry.lastRotation.copy(q);
1682
+ for (const part of entry.parts.values()) {
1683
+ if (part.node.position.distanceToSquared(part.lastLocalPosition) > 1e-10 || 1 - Math.abs(part.node.quaternion.dot(part.lastLocalRotation)) > 1e-10) changed = true;
1684
+ part.lastLocalPosition.copy(part.node.position);
1685
+ part.lastLocalRotation.copy(part.node.quaternion);
1686
+ }
1687
+ }
1688
+ return changed;
1689
+ }
1690
+
1691
+ for (const [id, entry] of this.entries) {
1692
+ const record = store.has(id) ? store.get(id) : null;
1693
+ if (!record) continue;
1694
+
1695
+ if (this.backend.bodyType(entry.body)!=='fixed') {
1696
+ const pose=this.backend.bodyPose(entry.body);
1697
+ const p={x:pose.position[0],y:pose.position[1],z:pose.position[2]};
1698
+ const q={x:pose.rotation[0],y:pose.rotation[1],z:pose.rotation[2],w:pose.rotation[3]};
1699
+ const dx=p.x-entry.lastPosition.x;
1700
+ const dy=p.y-entry.lastPosition.y;
1701
+ const dz=p.z-entry.lastPosition.z;
1702
+ const rotationDot=Math.abs(
1703
+ entry.lastRotation.x*q.x+entry.lastRotation.y*q.y+
1704
+ entry.lastRotation.z*q.z+entry.lastRotation.w*q.w
1705
+ );
1706
+ if(dx*dx+dy*dy+dz*dz>1e-10 || 1-rotationDot>1e-10) changed=true;
1707
+ const object = record.object;
1708
+ this.rootWorldPosition.set(p.x, p.y, p.z);
1709
+ this.rootRotation.set(q.x, q.y, q.z, q.w);
1710
+ if (object.parent) {
1711
+ object.parent.updateWorldMatrix(true, false);
1712
+ object.position.copy(object.parent.worldToLocal(this.rootWorldPosition));
1713
+ object.parent.getWorldQuaternion(this.parentWorldRotation);
1714
+ object.quaternion.copy(this.parentWorldRotation.invert()).multiply(this.rootRotation);
1715
+ } else {
1716
+ object.position.copy(this.rootWorldPosition);
1717
+ object.quaternion.copy(this.rootRotation);
1718
+ }
1719
+ object.updateMatrixWorld(true);
1720
+ entry.lastPosition.set(p.x,p.y,p.z);
1721
+ entry.lastRotation.set(q.x,q.y,q.z,q.w);
1722
+ }
1723
+
1724
+ for (const part of entry.parts.values()) {
1725
+ const pose=this.backend.bodyPose(part.body);
1726
+ const p={x:pose.position[0],y:pose.position[1],z:pose.position[2]};
1727
+ const q={x:pose.rotation[0],y:pose.rotation[1],z:pose.rotation[2],w:pose.rotation[3]};
1728
+ this.partWorldRotation.set(q.x,q.y,q.z,q.w);
1729
+ this.partWorldPosition.set(p.x,p.y,p.z);
1730
+ const parentNode = part.node.parent;
1731
+ if (parentNode) {
1732
+ parentNode.updateWorldMatrix(true, false);
1733
+ parentNode.getWorldPosition(this.parentWorldPosition);
1734
+ parentNode.getWorldQuaternion(this.parentWorldRotation);
1735
+ this.inverseParentWorldRotation.copy(this.parentWorldRotation).invert();
1736
+ this.partLocalRotation.copy(this.inverseParentWorldRotation).multiply(this.partWorldRotation);
1737
+ this.partLocalPosition.copy(this.partWorldPosition).sub(this.parentWorldPosition).applyQuaternion(this.inverseParentWorldRotation);
1738
+ } else {
1739
+ this.partLocalRotation.copy(this.partWorldRotation);
1740
+ this.partLocalPosition.copy(this.partWorldPosition);
1741
+ }
1742
+ if (1 - Math.abs(part.lastLocalRotation.dot(this.partLocalRotation)) > 1e-10 || part.lastLocalPosition.distanceToSquared(this.partLocalPosition) > 1e-10) changed = true;
1743
+ part.node.quaternion.copy(this.partLocalRotation);
1744
+ part.node.position.copy(this.partLocalPosition);
1745
+ part.node.updateMatrixWorld(false);
1746
+ part.lastLocalRotation.copy(this.partLocalRotation);
1747
+ part.lastLocalPosition.copy(this.partLocalPosition);
1748
+ }
1749
+ }
1750
+ return changed;
1751
+ }
1752
+ }