@hology/core 0.0.212 → 0.0.213

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 (135) hide show
  1. package/dist/effects/sequence/index.d.ts +1 -0
  2. package/dist/effects/sequence/index.js +1 -1
  3. package/dist/effects/sequence/sequence-action.d.ts +5 -0
  4. package/dist/effects/sequence/sequence-actor.d.ts +7 -0
  5. package/dist/effects/sequence/sequence-actor.js +1 -1
  6. package/dist/effects/sequence/sequence-animation-retiming.js +1 -1
  7. package/dist/effects/sequence/sequence-data.d.ts +9 -0
  8. package/dist/effects/sequence/sequence-data.js +1 -1
  9. package/dist/effects/sequence/sequence-player.d.ts +12 -1
  10. package/dist/effects/sequence/sequence-player.js +1 -1
  11. package/dist/effects/sequence/sequence-transform.d.ts +10 -0
  12. package/dist/effects/sequence/sequence-transform.js +4 -0
  13. package/dist/effects/sequence/sequence-value-lane.d.ts +2 -0
  14. package/dist/effects/sequence/sequence-value-lane.js +1 -1
  15. package/dist/effects/vfx/vfx-actor.d.ts +5 -0
  16. package/dist/effects/vfx/vfx-actor.js +1 -1
  17. package/dist/effects/vfx/vfx-asset.d.ts +2 -1
  18. package/dist/effects/vfx/vfx-asset.js +1 -1
  19. package/dist/effects/vfx/vfx-materializer.js +1 -1
  20. package/dist/effects/vfx/vfx-renderers.d.ts +1 -0
  21. package/dist/effects/vfx/vfx-renderers.js +1 -1
  22. package/dist/gameplay/actors/actor.d.ts +3 -5
  23. package/dist/gameplay/actors/actor.js +1 -1
  24. package/dist/gameplay/actors/builtin/components/character/character-animation.d.ts +3 -0
  25. package/dist/gameplay/actors/builtin/components/character/character-animation.js +1 -1
  26. package/dist/gameplay/actors/builtin/components/character/character-movement-like.d.ts +2 -0
  27. package/dist/gameplay/actors/builtin/components/character/character-movement.d.ts +13 -0
  28. package/dist/gameplay/actors/builtin/components/character/character-movement.js +1 -1
  29. package/dist/gameplay/actors/builtin/components/character/net-character-movement-protocol.d.ts +4 -1
  30. package/dist/gameplay/actors/builtin/components/character/net-character-movement-protocol.js +1 -1
  31. package/dist/gameplay/actors/builtin/components/mesh-component.d.ts +1 -0
  32. package/dist/gameplay/actors/builtin/components/mesh-component.js +1 -1
  33. package/dist/gameplay/actors/builtin/components/tween-component.js +1 -1
  34. package/dist/gameplay/actors/builtin/navmesh-actor.d.ts +2 -0
  35. package/dist/gameplay/actors/builtin/navmesh-actor.js +1 -1
  36. package/dist/gameplay/actors/builtin/trigger-volume.d.ts +3 -3
  37. package/dist/gameplay/actors/builtin/trigger-volume.js +1 -1
  38. package/dist/gameplay/actors/camera/camera-component.d.ts +1 -3
  39. package/dist/gameplay/actors/camera/camera-component.js +1 -1
  40. package/dist/gameplay/actors/component.d.ts +3 -0
  41. package/dist/gameplay/actors/component.js +1 -1
  42. package/dist/gameplay/actors/type-registry.d.ts +10 -0
  43. package/dist/gameplay/actors/type-registry.js +4 -0
  44. package/dist/gameplay/animation/retarget.d.ts +50 -0
  45. package/dist/gameplay/animation/retarget.js +4 -0
  46. package/dist/gameplay/animation/root-motion.js +1 -1
  47. package/dist/gameplay/event-graph/actor-transform-properties.d.ts +6 -0
  48. package/dist/gameplay/event-graph/actor-transform-properties.js +4 -0
  49. package/dist/gameplay/event-graph/asset-actor-types.d.ts +3 -0
  50. package/dist/gameplay/event-graph/asset-actor-types.js +4 -0
  51. package/dist/gameplay/event-graph/asset-references.d.ts +12 -0
  52. package/dist/gameplay/event-graph/asset-references.js +4 -0
  53. package/dist/gameplay/event-graph/compiler.d.ts +107 -0
  54. package/dist/gameplay/event-graph/compiler.js +4 -0
  55. package/dist/gameplay/event-graph/decorators.d.ts +74 -0
  56. package/dist/gameplay/event-graph/decorators.js +4 -0
  57. package/dist/gameplay/event-graph/document-compiler.d.ts +107 -0
  58. package/dist/gameplay/event-graph/document-compiler.js +4 -0
  59. package/dist/gameplay/event-graph/event-graph-demo.d.ts +2 -0
  60. package/dist/gameplay/event-graph/event-graph-demo.js +4 -0
  61. package/dist/gameplay/event-graph/graph.d.ts +106 -0
  62. package/dist/gameplay/event-graph/graph.js +4 -0
  63. package/dist/gameplay/event-graph/index.d.ts +13 -0
  64. package/dist/gameplay/event-graph/index.js +4 -0
  65. package/dist/gameplay/event-graph/model.d.ts +71 -0
  66. package/dist/gameplay/event-graph/model.js +4 -0
  67. package/dist/gameplay/event-graph/nodes/execution-nodes.d.ts +115 -0
  68. package/dist/gameplay/event-graph/nodes/execution-nodes.js +4 -0
  69. package/dist/gameplay/event-graph/nodes/gameplay-nodes.d.ts +208 -0
  70. package/dist/gameplay/event-graph/nodes/gameplay-nodes.js +4 -0
  71. package/dist/gameplay/event-graph/nodes/index.d.ts +4 -0
  72. package/dist/gameplay/event-graph/nodes/index.js +4 -0
  73. package/dist/gameplay/event-graph/nodes/value-nodes.d.ts +53 -0
  74. package/dist/gameplay/event-graph/nodes/value-nodes.js +4 -0
  75. package/dist/gameplay/event-graph/registry.d.ts +33 -0
  76. package/dist/gameplay/event-graph/registry.js +4 -0
  77. package/dist/gameplay/event-graph/runtime-assets.d.ts +21 -0
  78. package/dist/gameplay/event-graph/runtime-assets.js +4 -0
  79. package/dist/gameplay/event-graph/runtime.d.ts +160 -0
  80. package/dist/gameplay/event-graph/runtime.js +4 -0
  81. package/dist/gameplay/event-graph/type-inference.d.ts +41 -0
  82. package/dist/gameplay/event-graph/type-inference.js +4 -0
  83. package/dist/gameplay/event-graph/types.d.ts +77 -0
  84. package/dist/gameplay/event-graph/types.js +4 -0
  85. package/dist/gameplay/index.d.ts +15 -2
  86. package/dist/gameplay/index.js +1 -1
  87. package/dist/gameplay/initiate.js +1 -1
  88. package/dist/gameplay/input/input.d.ts +22 -17
  89. package/dist/gameplay/input/input.js +1 -1
  90. package/dist/gameplay/net/service/net-decorator.d.ts +1 -1
  91. package/dist/gameplay/net/service/net-decorator.js +1 -1
  92. package/dist/gameplay/net/service/net-serializer.js +1 -1
  93. package/dist/gameplay/net/service/net-service.d.ts +6 -6
  94. package/dist/gameplay/net/service/net-service.js +1 -1
  95. package/dist/gameplay/net/service/rpc-decorator.js +1 -1
  96. package/dist/gameplay/services/asset-loader.d.ts +7 -0
  97. package/dist/gameplay/services/asset-loader.js +1 -1
  98. package/dist/gameplay/services/physics/physics-system.d.ts +14 -0
  99. package/dist/gameplay/services/physics/physics-system.js +1 -1
  100. package/dist/gameplay/services/world.d.ts +12 -0
  101. package/dist/gameplay/services/world.js +1 -1
  102. package/dist/rendering.js +1 -1
  103. package/dist/scene/asset-resource-loader.d.ts +7 -1
  104. package/dist/scene/asset-resource-loader.js +1 -1
  105. package/dist/scene/custom-param-deserialize.js +1 -1
  106. package/dist/scene/custom-param-runtime-types.js +1 -1
  107. package/dist/scene/materializer.d.ts +25 -0
  108. package/dist/scene/materializer.js +1 -1
  109. package/dist/scene/model.d.ts +114 -2
  110. package/dist/scene/model.js +1 -1
  111. package/dist/scene/objects/prefab.js +1 -1
  112. package/dist/shader/graph/compiler.d.ts +3 -0
  113. package/dist/shader/graph/compiler.js +1 -1
  114. package/dist/shader/graph/model.d.ts +1 -1
  115. package/dist/shader/graph/registry.js +1 -1
  116. package/dist/test/animation-retarget.test.d.ts +2 -0
  117. package/dist/test/animation-retarget.test.js +4 -0
  118. package/dist/test/event-graph-generated-code.test.d.ts +2 -0
  119. package/dist/test/event-graph-generated-code.test.js +4 -0
  120. package/dist/test/event-graph-types.test.d.ts +2 -0
  121. package/dist/test/event-graph-types.test.js +4 -0
  122. package/dist/test/event-graph.test.d.ts +2 -0
  123. package/dist/test/event-graph.test.js +4 -0
  124. package/dist/test/input.test.d.ts +2 -0
  125. package/dist/test/input.test.js +4 -0
  126. package/dist/test/net-character-movement.test.js +1 -1
  127. package/dist/test/prefab-instance-params.test.js +1 -1
  128. package/dist/test/sequence-camera-control.test.js +1 -1
  129. package/dist/test/sequence-scene-binding.test.d.ts +2 -0
  130. package/dist/test/sequence-scene-binding.test.js +4 -0
  131. package/dist/test/sequence-transform.test.d.ts +2 -0
  132. package/dist/test/sequence-transform.test.js +4 -0
  133. package/dist/test/shader-graph.test.js +1 -1
  134. package/package.json +10 -2
  135. package/tsconfig.tsbuildinfo +1 -1
@@ -1,4 +1,4 @@
1
- import { ReplOn } from "./replication";
1
+ import { ReplOn } from "./replication.js";
2
2
  /**
3
3
  * Ensures that this function is only executed if on the server.
4
4
  * This can be used to prevent executing something on the client
@@ -1,4 +1,4 @@
1
- import{BaseActor as t}from"../../actors/actor";import{NetService as e}from"./net-service";import{inject as n}from"../../inject";import{ReplOn as r}from"./replication";import{isSignalLike as i}from"./net-utils";import{ActorComponent as o}from"../../actors/component";export function RunIfServer(){return function(r,i){let o;return i.addInitializer(function(){this instanceof t?o=n(e):console.warn("RunIfServer should not be defined on a non actor")}),function(...t){if(o.isServer)return r.apply(this,t)}}}export function RunIfClient(){return function(r,i){let o;return i.addInitializer(function(){this instanceof t?o=n(e):console.warn("RunIfClient should not be defined on a non actor")}),function(...t){if(!o.isServer)return r.apply(this,t)}}}export function RunIfNotDedicatedServer(){return function(r,i){let o;return i.addInitializer(function(){this instanceof t?o=n(e):console.warn("RunIfClient should not be defined on a non actor")}),function(...t){if(!o.isDedicatedServer)return r.apply(this,t)}}}export function Replicated(s=r.all,c=!0){return function(r,a){let f;a.addInitializer(function(){if(!(this instanceof t||this instanceof o))return void console.warn("RunIfClient should not only be used on actors and actor components");let r,u;if(this instanceof t)r=this;else if(this instanceof o&&(r=this.actor,u=this,null==r))return;f=n(e),f.registerReplicatedProperty(s,c,r,a.name.toString(),this,u);const l=this[a.name];if(i(l)){const t=l.subscribe(t=>{if(f.isServer){if(null==r.__netid)return;f.handlePropertySet(s,c,r,a.name.toString(),t,u)}});return void r.disposed.subscribe(()=>{t()})}let d=l;Object.defineProperty(this,a.name,{set:t=>{f.isServer&&f.handlePropertySet(s,c,r,a.name.toString(),t,u),d=t},get:()=>d})})}}export function makePropertyReplicated(t,e,n,r,i){n.registerReplicatedProperty(i,r,t,e,this,null);let o=t[e];Object.defineProperty(t,e,{set:s=>{n.isServer&&n.handlePropertySet(i,r,t,e,s,null),o=s},get:()=>o})}/*
1
+ import{BaseActor as t}from"../../actors/actor.js";import{NetService as e}from"./net-service.js";import{inject as n}from"../../inject.js";import{ReplOn as r}from"./replication.js";import{isSignalLike as i}from"./net-utils.js";import{ActorComponent as o}from"../../actors/component.js";export function RunIfServer(){return function(r,i){let o;return i.addInitializer(function(){this instanceof t?o=n(e):console.warn("RunIfServer should not be defined on a non actor")}),function(...t){if(o.isServer)return r.apply(this,t)}}}export function RunIfClient(){return function(r,i){let o;return i.addInitializer(function(){this instanceof t?o=n(e):console.warn("RunIfClient should not be defined on a non actor")}),function(...t){if(!o.isServer)return r.apply(this,t)}}}export function RunIfNotDedicatedServer(){return function(r,i){let o;return i.addInitializer(function(){this instanceof t?o=n(e):console.warn("RunIfClient should not be defined on a non actor")}),function(...t){if(!o.isDedicatedServer)return r.apply(this,t)}}}export function Replicated(s=r.all,c=!0){return function(r,a){let f;a.addInitializer(function(){if(!(this instanceof t||this instanceof o))return void console.warn("RunIfClient should not only be used on actors and actor components");let r,u;if(this instanceof t)r=this;else if(this instanceof o&&(r=this.actor,u=this,null==r))return;f=n(e),f.registerReplicatedProperty(s,c,r,a.name.toString(),this,u);const l=this[a.name];if(i(l)){const t=l.subscribe(t=>{if(f.isServer){if(null==r.__netid)return;f.handlePropertySet(s,c,r,a.name.toString(),t,u)}});return void r.disposed.subscribe(()=>{t()})}let d=l;Object.defineProperty(this,a.name,{set:t=>{f.isServer&&f.handlePropertySet(s,c,r,a.name.toString(),t,u),d=t},get:()=>d})})}}export function makePropertyReplicated(t,e,n,r,i){n.registerReplicatedProperty(i,r,t,e,this,null);let o=t[e];Object.defineProperty(t,e,{set:s=>{n.isServer&&n.handlePropertySet(i,r,t,e,s,null),o=s},get:()=>o})}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{__decorate as r}from"tslib";import{World as t}from"../../services/world";import{inject as e}from"../../inject";import{Service as s}from"typedi";import{BaseActor as n}from"../../actors/actor";import{Euler as o,Quaternion as i,Vector2 as a,Vector3 as c,Vector4 as f}from"three";import{DataAssetRef as u}from"../../../scene/objects/data-asset";import{AssetLoader as l}from"../../services/asset-loader";const p="-a",m="-v2",d="-v3",w="-v4",y="-e",A="-q",h="-s",b="-m",j="-dar";export class DecodeResult{constructor(){this.error=!1,this.requiresAssetLookups=!1}reset(){this.error=!1,this.missingActorId=void 0,this.requiresAssetLookups=!1}}let O=class{constructor(){this.world=e(t),this.assetLoader=e(l)}encode(r){return JSON.stringify(this.wrapObject(r))}decode(r,t){t.reset();const e=JSON.parse(r);return this.unwrapObject(e,t)}wrapObject(r){if(null!=r&&"object"==typeof r){if(Array.isArray(r))return r.map(r=>this.wrapObject(r));if(r instanceof n){if(null!=r.__netid)return{[p]:r.__netid};console.warn("Missing netid on actor",r)}else{if(r instanceof a)return{[m]:r.toArray([])};if(r instanceof c)return{[d]:r.toArray([])};if(r instanceof f)return{[w]:r.toArray([])};if(r instanceof o)return{[y]:r.toArray([])};if(r instanceof i)return{[A]:r.toArray([])};if(r instanceof Map)return{[b]:Array.from(r.entries()).map(([r,t])=>[r,this.wrapObject(t)])};if(r instanceof Set)return{[h]:Array.from(r.values()).map(r=>this.wrapObject(r))};if(r instanceof u)return{[j]:r.id}}const t={};for(const e of Object.keys(r))t[e]=this.wrapObject(r[e]);return t}return r}unwrapObject(r,t){if(null!=r&&"object"==typeof r){if(Array.isArray(r))return r.map(r=>this.unwrapObject(r,t));{if(null!=r[p]){const e=r[p],s=this.world.actors.find(r=>r.__netid===e);return null==s&&(t.error=!0,t.missingActorId=e,console.warn(`Failed to find replicated actor with netid "${e}"`)),s}if(null!=r[m]){const t=r[m];return(new a).fromArray(t)}if(null!=r[d]){const t=r[d];return(new c).fromArray(t)}if(null!=r[w]){const t=r[w];return(new f).fromArray(t)}if(null!=r[y]){const t=r[y];return(new o).fromArray(t)}if(null!=r[A]){const t=r[A];return(new i).fromArray(t)}if(null!=r[b]){const e=r[b];return new Map(e.map(([r,e])=>[r,this.unwrapObject(e,t)]))}if(null!=r[h]){const e=r[h];return new Set(e.map(r=>this.unwrapObject(r,t)))}if(null!=r[j])return t.requiresAssetLookups=!0,r;const e={};for(const s of Object.keys(r))e[s]=this.unwrapObject(r[s],t);return e}}return r}async decodeAssets(r){if(null!=r&&"object"==typeof r){if(Array.isArray(r))return await Promise.all(r.map(r=>this.decodeAssets(r)));if(r instanceof Map){const t=await Promise.all(Array.from(r.entries()).map(async([r,t])=>[r,await this.decodeAssets(t)]));r.clear();for(const[e,s]of t)r.set(e,s);return r}if(r instanceof Set){const t=await Promise.all(Array.from(r.values()).map(r=>this.decodeAssets(r)));r.clear();for(const e of t)r.add(e);return r}{const t=r;if(null!=t[j])return await this.assetLoader.getDataAssetById(t[j]);for(const r of Object.keys(t))t[r]=await this.decodeAssets(t[r]);return t}}return r}};O=r([s()],O);export{O as NetSerializer};new a,new c,new f,new o,new i;/*
1
+ import{__decorate as r}from"tslib";import{World as t}from"../../services/world.js";import{inject as e}from"../../inject.js";import{Service as s}from"typedi";import{BaseActor as n}from"../../actors/actor.js";import{Euler as o,Quaternion as i,Vector2 as a,Vector3 as c,Vector4 as f}from"three";import{DataAssetRef as u}from"../../../scene/objects/data-asset.js";import{AssetLoader as l}from"../../services/asset-loader.js";const p="-a",m="-v2",d="-v3",w="-v4",y="-e",A="-q",h="-s",j="-m",b="-dar";export class DecodeResult{constructor(){this.error=!1,this.requiresAssetLookups=!1}reset(){this.error=!1,this.missingActorId=void 0,this.requiresAssetLookups=!1}}let O=class{constructor(){this.world=e(t),this.assetLoader=e(l)}encode(r){return JSON.stringify(this.wrapObject(r))}decode(r,t){t.reset();const e=JSON.parse(r);return this.unwrapObject(e,t)}wrapObject(r){if(null!=r&&"object"==typeof r){if(Array.isArray(r))return r.map(r=>this.wrapObject(r));if(r instanceof n){if(null!=r.__netid)return{[p]:r.__netid};console.warn("Missing netid on actor",r)}else{if(r instanceof a)return{[m]:r.toArray([])};if(r instanceof c)return{[d]:r.toArray([])};if(r instanceof f)return{[w]:r.toArray([])};if(r instanceof o)return{[y]:r.toArray([])};if(r instanceof i)return{[A]:r.toArray([])};if(r instanceof Map)return{[j]:Array.from(r.entries()).map(([r,t])=>[r,this.wrapObject(t)])};if(r instanceof Set)return{[h]:Array.from(r.values()).map(r=>this.wrapObject(r))};if(r instanceof u)return{[b]:r.id}}const t={};for(const e of Object.keys(r))t[e]=this.wrapObject(r[e]);return t}return r}unwrapObject(r,t){if(null!=r&&"object"==typeof r){if(Array.isArray(r))return r.map(r=>this.unwrapObject(r,t));{if(null!=r[p]){const e=r[p],s=this.world.actors.find(r=>r.__netid===e);return null==s&&(t.error=!0,t.missingActorId=e,console.warn(`Failed to find replicated actor with netid "${e}"`)),s}if(null!=r[m]){const t=r[m];return(new a).fromArray(t)}if(null!=r[d]){const t=r[d];return(new c).fromArray(t)}if(null!=r[w]){const t=r[w];return(new f).fromArray(t)}if(null!=r[y]){const t=r[y];return(new o).fromArray(t)}if(null!=r[A]){const t=r[A];return(new i).fromArray(t)}if(null!=r[j]){const e=r[j];return new Map(e.map(([r,e])=>[r,this.unwrapObject(e,t)]))}if(null!=r[h]){const e=r[h];return new Set(e.map(r=>this.unwrapObject(r,t)))}if(null!=r[b])return t.requiresAssetLookups=!0,r;const e={};for(const s of Object.keys(r))e[s]=this.unwrapObject(r[s],t);return e}}return r}async decodeAssets(r){if(null!=r&&"object"==typeof r){if(Array.isArray(r))return await Promise.all(r.map(r=>this.decodeAssets(r)));if(r instanceof Map){const t=await Promise.all(Array.from(r.entries()).map(async([r,t])=>[r,await this.decodeAssets(t)]));r.clear();for(const[e,s]of t)r.set(e,s);return r}if(r instanceof Set){const t=await Promise.all(Array.from(r.values()).map(r=>this.decodeAssets(r)));r.clear();for(const e of t)r.add(e);return r}{const t=r;if(null!=t[b])return await this.assetLoader.getDataAssetById(t[b]);for(const r of Object.keys(t))t[r]=await this.decodeAssets(t[r]);return t}}return r}};O=r([s()],O);export{O as NetSerializer};new a,new c,new f,new o,new i;/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,9 +1,9 @@
1
- import { ActorOptions, BaseActor } from '../../actors/actor';
2
- import { ActorComponent } from '../../actors/component';
3
- import { NetConnection } from '../net-connection';
4
- import { NetMode, NetSession } from '../net-session';
5
- import { ReplOn } from "./replication";
6
- import { RunsOn } from './rpc';
1
+ import { ActorOptions, BaseActor } from '../../actors/actor.js';
2
+ import { ActorComponent } from '../../actors/component.js';
3
+ import { NetConnection } from '../net-connection.js';
4
+ import { NetMode, NetSession } from '../net-session.js';
5
+ import { ReplOn } from "./replication.js";
6
+ import { RunsOn } from './rpc.js';
7
7
  export declare class NetService {
8
8
  session?: NetSession;
9
9
  /**
@@ -1,4 +1,4 @@
1
- import{__decorate as e}from"tslib";import{delay as t,interval as n,Subject as r,takeUntil as s,tap as o}from"rxjs";import{Euler as i,Vector3 as c}from"three";import{Service as a}from"typedi";import{$actorOptions as l,BaseActor as d,getActorClassById as p}from"../../actors/actor";import{ActorComponent as u}from"../../actors/component";import{$actorComponents as f}from"../../actors/internal/component-init";import{inject as h}from"../../inject";import{World as g}from"../../services/world";import{NetMode as y}from"../net-session";import{NetRole as w}from"./net-actor-role";import{DecodeResult as m,NetSerializer as v}from"./net-serializer";import{isSignalLike as A}from"./net-utils";import{ReplOn as b}from"./replication";import{getRpcMethodId as R,getRpcMethodName as _,RunsOn as S}from"./rpc";import{ActorController as U,BasePlayerController as M}from"../../actors/controller/actor-controller";import{makePropertyReplicated as C}from"./net-decorator";var P;!function(e){e[e.rpc=1]="rpc",e[e.prop=2]="prop",e[e.spawn=3]="spawn",e[e.removeActor=4]="removeActor",e[e.rpcComponent=5]="rpcComponent",e[e.propComponent=6]="propComponent",e[e.rpcBinary=21]="rpcBinary",e[e.rpcComponentBinary=25]="rpcComponentBinary",e[e.actorReady=7]="actorReady",e[e.propSnapshot=8]="propSnapshot",e[e.serverTime=100]="serverTime"}(P||(P={}));var $;!function(e){e[e.actor=0]="actor",e[e.component=1]="component"}($||($={}));let L=class{constructor(){this.actorConnection=new Map,this.destroyed=new r,this.world=h(g),this.serializer=h(v),this.serverTimeOffset=0,this.actorPreSpawnMessageBuffer=new Map,this.actorRefMissingMessageQueue=new Map,this.netStartupActorSpawnQueue=new Map,this.spawningActorNetIds=new Set,this.nextNetId=1,this.shouldReplicateMap=new Map,this.replicatedActors=new Map,this.replicatedProperties=new Map,this.replicatedPropertyRegistry=new Map}get mode(){return this.session?.mode??y.none}get isClient(){return this.mode===y.client}get isServer(){return this.mode<y.client}get isDedicatedServer(){return this.mode===y.dedicatedServer}start(){if(this.stop(),this.destroyed=new r,this.isServer)for(const e of this.session.clients)this.sendServerTime(e);n(15).pipe(s(this.destroyed)).subscribe(()=>{this.processMessages()}),this.world.actorAdded.pipe(s(this.destroyed),o(e=>{this.configureMaterializedActorRole(e),this.isServer?this.defineNetId(e):this.processQueuedNetStartupActorSpawns(e)}),t(8)).subscribe(e=>{this.shouldReplicate(e)&&(C(e,"owner",this,!0,b.all),this.sendActorSpawn(e))}),this.world.actorRemoved.pipe(s(this.destroyed),t(10)).subscribe(e=>{this.sendActorRemove(e),this.replicatedActors.delete(e),this.replicatedProperties.delete(e),this.replicatedPropertyRegistry.delete(e),this.actorPreSpawnMessageBuffer.delete(e)}),this.session.playerJoined.pipe(s(this.destroyed)).subscribe(e=>{this.sendServerTime(e),this.isServer&&this.replicatedActors.size>0&&this.spawnOnLateClient(e)})}stop(){this.destroyed.next(null),this.destroyed.complete()}configureMaterializedActorRole(e){null!=e.__netSceneId&&this.mode!==y.none&&(this.shouldReplicate(e)?e.netRole=this.isServer?w.authority:w.simulatedProxy:this.isServer||(e.netRole=w.none))}shouldReplicate(e){const t=this.shouldReplicateMap.get(e);if(null==t){const t=e.constructor[l],n=!0===t?.replicate;return this.shouldReplicateMap.set(e,n),n}return!0===t}setReplicate(e,t){this.shouldReplicateMap.set(e,t)}isRelevant(e,t){const n=this.getRelevancyOptions(e);return!(!0===n?.ownerOnly)||this.resolveActorConnection(e)?.id===t.id}getRelevancyOptions(e){return e.constructor[l].relevancy}spawnOnLateClient(e){const t=[e];for(const e of this.replicatedActors.keys())this.sendActorSpawn(e,t)}async processMessages(){const e=this.session.hasMessage();for(let t=0;t<e;t++){const e=this.session.readMessage();null!=e&&await this.processMessage(e)}}async processMessage(e){try{switch(new DataView(e.buffer).getUint8(0)){case P.rpc:case P.rpcComponent:case P.rpcBinary:case P.rpcComponentBinary:this.processRpc(e.from,e.buffer);break;case P.prop:case P.propComponent:this.processProp(e.from,e.buffer);break;case P.propSnapshot:this.processPropSnapshot(e.from,e.buffer);break;case P.spawn:await this.processSpawn(e.from,e.buffer);break;case P.removeActor:this.processRemoveActor(e.from,e.buffer);break;case P.serverTime:this.processServerTime(e.from,e.buffer);break;case P.actorReady:this.processActorReady(e.from,e.buffer)}}catch(e){console.error("Failed to process message",e)}}processServerTime(e,t){if(this.isServer||this.session.server?.id!==e.id)return;const n=this.parseServerTime(t);this.serverTimeOffset=Date.now()-n}getActorRefMissingMessageQueue(e){let t=this.actorRefMissingMessageQueue.get(e);return null==t&&(t=[],this.actorRefMissingMessageQueue.set(e,t)),t}processRpc(e,t){let n=0;const r=new DataView(t),s=r.getUint8(n);n+=1;const o=r.getUint32(n,!0);n+=4;const i=r.getUint8(n);n+=1;const c=s===P.rpcBinary||s===P.rpcComponentBinary;let a,l,d="";if(c){const e=r.getUint32(n,!0);n+=4,l=new Uint8Array(t,n,e),n+=e}else{const e=r.getUint16(n,!0);n+=2,d=O(t,n,e),n+=e;try{a=this.serializer.decode(d,F)}catch(e){return void console.warn("Failed to parse RPC args JSON",d,e)}}if(!c&&F.error){if(null!=F.missingActorId){const n=this.getActorRefMissingMessageQueue(F.missingActorId);console.debug(`Missing referenced actor ${F.missingActorId}. Queueing message for later`),n.push({from:e,buffer:t})}else console.log("Unknown decode error",d);return}const p=this.world.actors.find(e=>e.__netid===o);if(null==p){return this.getActorRefMissingMessageQueue(o).push({from:e,buffer:t}),void console.debug(`Missing actor ${o}. Queueing message for later`)}let u;if(s===P.rpcComponent||s===P.rpcComponentBinary){const e=r.getUint8(n),t=p[f];if(null!=t&&(u=t.find(t=>t.__netid===e)),null==u)return void console.error(`RPC failed: Failed to find component with netid ${e} on actor with netid ${o}`)}if(this.isServer){if(!this.session.clients.some(t=>t.id==e.id))return void console.warn("Received RCP from non client");const t=this.resolveActorConnection(p);if(null==t)return void console.error("Received server RPC for actor without owner which can't be processed");if(t.id!==e.id)return void console.warn(`Received RPC for actor net id ${p.__netid} from connection ${e.id}, but this connection is not the owner. Can't process.`)}else{if(!(this.session.server?.id===e.id))return void console.warn("Received RCP from non server which is not allowed")}const h=u??p,g=_(h,i);if(null!=g)if("function"==typeof h[g])if(c)h[g](l);else{if(F.requiresAssetLookups)return this.serializer.decodeAssets(a).then(e=>{h[g](...e)}).catch(e=>{console.warn(`Failed to decode asset references for RPC '${g}' on actor net id ${p.__netid}`,e)});h[g](...a)}else console.error(`RPC function '${g}' not found on actor net id ${p.__netid}`+(null!=u?` and component net id ${u.__netid}`:""));else console.error(`RPC method id ${i} not found on actor net id ${p.__netid}`+(null!=u?` and component net id ${u.__netid}`:""))}processProp(e,t){if(this.session.server?.id!==e.id)return void console.warn(`Received property replication from non-server connection (id: ${e.id}), ignoring.`);let n=0;const r=new DataView(t),s=r.getUint8(n);n+=1;const o=r.getUint32(n,!0);n+=4;const i=r.getUint8(n);n+=1;let c="";for(let e=0;e<i;e++)c+=String.fromCharCode(r.getUint8(n+e));n+=i;const a=r.getUint16(n,!0);n+=2;const l=t.slice(n,n+a);n+=a;const d=this.world.actors.find(e=>e.__netid===o);if(!d){return this.getActorRefMissingMessageQueue(o).push({from:e,buffer:t}),void console.error("Failed to process property replication. No actor found with id",o,c)}let p;if(s===P.propComponent){const e=r.getUint8(n),t=d[f];if(null!=t&&(p=t.find(t=>t.__netid===e)),null==p)return void console.error(`Failed to find component with netid ${e} on actor with netid ${o}`)}const u=p??d;try{const n=this.decodeReplicatedValue(l);if(F.error){if(null!=F.missingActorId){let n=this.getActorRefMissingMessageQueue(F.missingActorId);console.debug(`Missing referenced actor ${F.missingActorId}. Queueing message for later`),n.push({from:e,buffer:t})}return}if(F.requiresAssetLookups)return this.serializer.decodeAssets(n).then(e=>{this.applyReplicatedProperty(u,c,e),this.callRepNotify(u,c)}).catch(e=>{console.warn(`Failed to decode asset references for replicated property '${c}' on actor id ${o}`,e)});this.applyReplicatedProperty(u,c,n),this.callRepNotify(u,c)}catch(e){console.warn(`Failed to decode replicated property '${c}' on actor id ${o}`,e)}}processPropSnapshot(e,t){if(this.session.server?.id!==e.id)return void console.warn(`Received property snapshot from non-server connection (id: ${e.id}), ignoring.`);let n=0;const r=new DataView(t);n+=1;const s=r.getUint32(n,!0);n+=4;const o=this.world.actors.find(e=>e.__netid===s);if(null==o){return this.getActorRefMissingMessageQueue(s).push({from:e,buffer:t}),void console.debug(`Missing actor ${s}. Queueing property snapshot for later`)}const i=r.getUint16(n,!0);n+=2;const c=[];for(let a=0;a<i;a++){const i=r.getUint8(n);n+=1;let a=o;if(i===$.component){const e=r.getUint8(n);n+=1;const t=o[f];if(a=t?.find(t=>t.__netid===e),null==a)return void console.error(`Failed to process property snapshot. No component found with netid ${e} on actor with netid ${s}`)}else if(i!==$.actor)return void console.error(`Failed to process property snapshot. Unknown target kind ${i}`);const l=r.getUint8(n);n+=1;let d="";for(let e=0;e<l;e++)d+=String.fromCharCode(r.getUint8(n+e));n+=l;const p=r.getUint32(n,!0);n+=4;const u=t.slice(n,n+p);n+=p;try{const n=this.decodeReplicatedValue(u);if(F.error){if(null!=F.missingActorId){this.getActorRefMissingMessageQueue(F.missingActorId).push({from:e,buffer:t}),console.debug(`Missing referenced actor ${F.missingActorId}. Queueing property snapshot for later`)}else console.warn(`Unknown decode error in property snapshot for actor ${s}`);return}c.push({target:a,property:d,value:n,requiresAssetLookups:F.requiresAssetLookups})}catch(e){return void console.warn(`Failed to decode replicated property snapshot entry '${d}' on actor id ${s}`,e)}}if(c.some(e=>e.requiresAssetLookups))return Promise.all(c.map(async e=>{e.requiresAssetLookups&&(e.value=await this.serializer.decodeAssets(e.value))})).then(()=>{this.applyReplicatedProperties(c)}).catch(e=>{console.warn(`Failed to decode asset references for property snapshot on actor id ${s}`,e)});this.applyReplicatedProperties(c)}applyReplicatedProperties(e){for(const t of e)this.applyReplicatedProperty(t.target,t.property,t.value);for(const t of e)this.callRepNotify(t.target,t.property)}async processSpawn(e,t){if(this.isServer)return;const n=new DataView(t);let r=0;r+=1;const s=n.getUint32(r,!0);r+=4;const o=n.getUint8(r);r+=1;let i="";for(let e=0;e<o;e++)i+=String.fromCharCode(n.getUint8(r+e));r+=o,Q.set(n.getFloat32(r,!0),n.getFloat32(r+4,!0),n.getFloat32(r+8,!0)),r+=12,B.set(n.getFloat32(r,!0),n.getFloat32(r+4,!0),n.getFloat32(r+8,!0)),r+=12;const c=n.getUint8(r);r+=1;const a=n.getUint32(r);r+=4;const l=this.readOptionalSceneId(t,r);console.log("Spawning "+i);const d=p(i);if(!d)return void console.error(`Failed to spawn actor: unknown actor type '${i}'`);const u=this.world.actors.find(e=>e.__netid===s);if(null!=u)return void this.applySpawnNetInfo(u,s,c,a);if(this.spawningActorNetIds.has(s))return void console.log("Actor was already spawned",null!=u);const f=this.findMaterializedNetStartupActor(l,i,s);if(null!=f)return this.applySpawnNetInfo(f,s,c,a),this.processQueuedActorMessages(s),void this.sendActorReady(f);if(null==l){this.spawningActorNetIds.add(s);try{const e=await this.world.spawnActorWithNetInfo(d,s,c,a,Q,B);this.processQueuedActorMessages(s),this.sendActorReady(e)}catch(e){return void console.error("Spawning replicated actor on client failed",e)}finally{this.spawningActorNetIds.delete(s)}}else this.getNetStartupActorSpawnQueue(l).push({from:e,buffer:t})}readOptionalSceneId(e,t){if(t+2>e.byteLength)return;const n=new DataView(e).getUint16(t,!0);return t+=2,0===n||t+n>e.byteLength?void 0:O(e,t,n)}findMaterializedNetStartupActor(e,t,n){if(null!=e)return this.world.actors.find(r=>{if(r.__netSceneId!==e)return!1;if(null!=r.__netid&&r.__netid!==n)return!1;return(r.constructor.__actorId??r.constructor.name)===t})}applySpawnNetInfo(e,t,n,r){if(e.__netid=t,e.netRole=n,0===r)e.owner=void 0;else{const t=this.world.actors.find(e=>e.__netid===r);null!=t&&(e.owner=t)}e instanceof M&&(e.isLocallyControlled=n===w.autonomousProxy)}getNetStartupActorSpawnQueue(e){let t=this.netStartupActorSpawnQueue.get(e);return null==t&&(t=[],this.netStartupActorSpawnQueue.set(e,t)),t}processQueuedNetStartupActorSpawns(e){if(null==e.__netSceneId)return;const t=this.netStartupActorSpawnQueue.get(e.__netSceneId);if(null!=t){this.netStartupActorSpawnQueue.delete(e.__netSceneId);for(const e of t)this.processMessage(e)}}processQueuedActorMessages(e){const t=this.actorRefMissingMessageQueue.get(e);if(null!=t){console.log(`Processing queued messages for actor ${e}`),this.actorRefMissingMessageQueue.delete(e);for(const e of t)this.processMessage(e)}}sendActorReady(e){if(this.mode===y.none)return;if(!e||null==e.__netid)return void console.warn("sendActorReady: actor or actor.__netid is undefined");if(this.isServer)return;const t=new ArrayBuffer(5),n=new DataView(t);let r=0;n.setUint8(r,P.actorReady),r+=1,n.setUint32(r,e.__netid,!0),this.session.server&&this.session.sendMessage(this.session.server,!0,t)}processActorReady(e,t){if(!this.isServer)return;const n=new DataView(t).getUint32(1,!0),r=this.world.actors.find(e=>e.__netid===n);if(!r)return void console.warn(`processActorReady: No actor found with net id ${n}`);const s=this.actorPreSpawnMessageBuffer.get(r),o=this.getConnectionKey(e),i=s?.get(o);if(null!=i){this.sendPropertySnapshot(r,e);const t=i.filter(e=>!this.isPropertyMessage(e.buffer));if(t.length>0){console.log(`Sending ${t.length} queued messages for actor ${r.__netid}`);for(const e of t)this.session.sendMessage(e.connection,e.reliable,e.buffer)}s.delete(o),0===s.size&&this.actorPreSpawnMessageBuffer.delete(r)}}sendRpc(e,t,n,r,s,o){if(this.mode==y.none)return;if(!this.shouldReplicate(n))return;const i=n.__netid;if(null==i)return void console.warn("No __netid defined on actor. Actor must be repliated for RPC");const c=this.resolveActorConnection(n),a=[];if(this.isServer)switch(e){case S.all:a.push(...this.session.clients.filter(e=>this.isRelevant(n,e)));break;case S.client:null!=c&&a.push(c);break;case S.notOwner:a.push(...this.session.clients.filter(e=>e.id!==c?.id&&this.isRelevant(n,e)));case S.server:}else switch(e){case S.all:case S.client:case S.notOwner:break;case S.server:a.push(this.session.server)}if(0==a.length)return;if(null!=o&&null==o.__netid)return void console.warn("No __netid defined on component. Component must be initialized for RPC",o);const l=null!=o,d=o??n,p=R(d,r);if(null==p)return void console.warn(`RPC function '${r}' is not registered on ${d.constructor?.name??"target"}`);const u=1===s.length?function(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if("undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return null}(s[0]):null;if(null!=u){let e=10+u.byteLength;l&&(e+=1);const r=new ArrayBuffer(e),s=new DataView(r);let c=0;s.setUint8(c,l?P.rpcComponentBinary:P.rpcBinary),c+=1,s.setUint32(c,i,!0),c+=4,s.setUint8(c,p),c+=1,s.setUint32(c,u.byteLength,!0),c+=4,D(r,c,u),c+=u.byteLength,l&&(s.setUint8(c,o.__netid),c+=1);for(const e of a)null!=e&&this.sendWithQueue(n,{connection:e,reliable:t,buffer:r});return}const f=this.serializer.encode(s),h=I.encode(f);if(h.byteLength>65535)return void console.warn("RPC arguments are too large to send with the JSON RPC format",r);let g=8+h.byteLength;l&&(g+=1);const w=new ArrayBuffer(g),m=new DataView(w);let v=0;m.setUint8(v,l?P.rpcComponent:P.rpc),v+=1,m.setUint32(v,i,!0),v+=4,m.setUint8(v,p),v+=1,m.setUint16(v,h.byteLength,!0),v+=2,D(w,v,h),v+=h.byteLength,l&&(m.setUint8(v,o.__netid),v+=1);for(const e of a)null!=e&&this.sendWithQueue(n,{connection:e,reliable:t,buffer:w})}sendWithQueue(e,t){if(this.shouldQueueMessageUntilActorReady(e,t.connection)){return void this.getPreSpawnMessageQueue(e,t.connection).push(t)}this.session.sendMessage(t.connection,t.reliable,t.buffer)}findQueuedActorsInData(e,t=[]){if("object"==typeof e){if(Array.isArray(e))for(const t of e)this.findQueuedActorsInData(t);if(e instanceof d){this.actorPreSpawnMessageBuffer.get(e)}}}handlePropertySet(e,t,n,r,s,o){if(this.mode==y.none)return;if(!this.isServer)return;if(!this.shouldReplicate(n))return;let i=this.replicatedProperties.get(n);null==i&&(i={},this.replicatedProperties.set(n,i));const c=this.serializer.encode(s),a=I.encode(c),l=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);i[this.getReplicatedPropertyKey(r,o)]={property:r,replOn:e,reliable:t,buffer:l,component:o},this.sendProperty(e,t,n,r,l,o)}sendProperty(e,t,n,r,s,o){if(!this.isServer)return;const i=[],c=this.resolveActorConnection(n);switch(e){case b.all:i.push(...this.session.clients);break;case b.owner:null!=c&&i.push(c);break;case b.notOwner:null==c?i.push(...this.session.clients):i.push(...this.session.clients.filter(e=>e.id!==c.id))}const a=null!=o&&null!=o.__netid;let l=6+r.length+2+s.byteLength;a&&(l+=1);const d=new ArrayBuffer(l),p=new DataView(d);let u=0;p.setUint8(u,a?P.propComponent:P.prop),u+=1,p.setUint32(u,n.__netid,!0),u+=4,p.setUint8(u,r.length),u+=1;for(let e=0;e<r.length;e++)p.setUint8(u++,r.charCodeAt(e));p.setUint16(u,s.byteLength,!0),u+=2,new Uint8Array(d,u,s.byteLength).set(new Uint8Array(s)),u+=s.byteLength,a&&(p.setUint8(u,o.__netid),u+=1);for(const e of i)null!=e&&this.isRelevant(n,e)&&this.sendWithQueue(n,{connection:e,reliable:t,buffer:d})}defineNetId(e){null==e.__netid&&(e.__netid=this.nextNetId++)}registerReplicatedProperty(e,t,n,r,s,o){if(null==n||null==r||null==s)return;let i=this.replicatedPropertyRegistry.get(n);null==i&&(i=[],this.replicatedPropertyRegistry.set(n,i));const c=o??(s instanceof u?s:void 0),a=i.find(e=>e.target===s&&e.property===r);if(null!=a)return a.replOn=e,a.reliable=t,void(a.component=c);i.push({property:r,replOn:e,reliable:t,target:s,component:c})}sendActorSpawn(e,t=this.session.clients){if(!this.isServer)return;const n=t.filter(t=>this.isRelevant(e,t));this.defineNetId(e);const r=e.__netid;let s=e.constructor.__actorId??e.constructor.name;const o=I.encode(s);let i;null!=e.__netSceneId&&(i=I.encode(e.__netSceneId),i.byteLength>65535&&(console.warn(`Scene actor id is too long to replicate as a startup actor: ${e.__netSceneId}`),i=void 0));const c=i?.byteLength??0,a=6+o.length+12+12+1+4+2+c,l=new ArrayBuffer(a),d=new DataView(l);let p=0;d.setUint8(p,P.spawn),p+=1,d.setUint32(p,r,!0),p+=4,d.setUint8(p,o.length),p+=1,new Uint8Array(l).set(o,p),p+=o.length,d.setFloat32(p,e.position.x,!0),p+=4,d.setFloat32(p,e.position.y,!0),p+=4,d.setFloat32(p,e.position.z,!0),p+=4,d.setFloat32(p,e.rotation.x,!0),p+=4,d.setFloat32(p,e.rotation.y,!0),p+=4,d.setFloat32(p,e.rotation.z,!0),p+=4;let u=p;p+=1,d.setUint32(p,e.owner?.__netid??0),p+=4,d.setUint16(p,c,!0),p+=2,null!=i&&(D(l,p,i),p+=i.byteLength);let f=this.replicatedActors.get(e);null==f&&(f={spawnedAt:Date.now(),connections:[]},this.replicatedActors.set(e,f));for(const t of n){const n=l.slice(0),r=new DataView(n),s=this.resolveActorConnection(e)?.id===t.id?w.autonomousProxy:w.simulatedProxy;r.setUint8(u,s),this.getPreSpawnMessageQueue(e,t),this.session.sendMessage(t,!0,n),f.connections.some(e=>e.id===t.id)||f.connections.push(t)}}sendActorRemove(e){if(!this.isServer)return;const t=new ArrayBuffer(5),n=new DataView(t);let r=0;n.setUint8(r,P.removeActor),r+=1,n.setUint32(r,e.__netid,!0);for(const e of this.session.clients)this.session.sendMessage(e,!0,t)}processRemoveActor(e,t){if(this.isServer||this.session.server?.id!==e.id)return;const n=new DataView(t).getUint32(1,!0),r=this.world.actors.find(e=>e.__netid===n);r&&(this.world.removeActor(r),this.replicatedActors?.delete?.(r),this.replicatedProperties?.delete?.(r))}setOwningConnection(e,t){this.actorConnection.set(e.id,t)}getOwningConnection(e){return this.actorConnection.get(e.id)}getActorsByOwningConnection(e){const t=[];return this.actorConnection.forEach((n,r)=>{if(n.id===e.id){const e=this.world.actors.find(e=>e.id===r);null!=e&&t.push(e)}}),t}resolveActorConnection(e){let t;for(;null==t&&null!=e;)t=this.actorConnection.get(e.id),null==t&&(e=e.owner);return t}isLocallyControlled(e){let t=e;for(;null!=t;){if(t.netRole===w.autonomousProxy)return!0;if(t instanceof U)return t.isLocallyControlled;t=e.owner}return!1}isLocalOwner(e){return this.isLocallyControlled(e)}sendServerTime(e){const t=new ArrayBuffer(9),n=new DataView(t);n.setUint8(0,P.serverTime),n.setBigUint64(1,BigInt(Date.now()),!0),this.session.sendMessage(e,!0,t)}parseServerTime(e){const t=new DataView(e).getBigUint64(1,!0);return Number(t)}getConnectionKey(e){return e.id.toString()}getPreSpawnMessageQueue(e,t){let n=this.actorPreSpawnMessageBuffer.get(e);null==n&&(n=new Map,this.actorPreSpawnMessageBuffer.set(e,n));const r=this.getConnectionKey(t);let s=n.get(r);return null==s&&(s=[],n.set(r,s)),s}shouldQueueMessageUntilActorReady(e,t){const n=this.actorPreSpawnMessageBuffer.get(e);return!!n?.has(this.getConnectionKey(t))||this.isServer&&!this.replicatedActors.has(e)&&this.shouldReplicate(e)}isPropertyMessage(e){const t=new DataView(e).getUint8(0);return t===P.prop||t===P.propComponent}getReplicatedPropertyKey(e,t){return null!=t?.__netid?`component:${t.__netid}:${e}`:`actor:${e}`}sendPropertySnapshot(e,t){const n=this.buildPropertySnapshotEntries(e,t);if(0===n.length)return;const r=this.createPropertySnapshotBuffer(e,n);this.session.sendMessage(t,!0,r)}buildPropertySnapshotEntries(e,t){if(!this.isRelevant(e,t))return[];const n=this.replicatedPropertyRegistry.get(e);if(null==n)return[];const r=[];for(const s of n){if(!this.shouldReplicatePropertyToConnection(e,s.replOn,t))continue;if(null!=s.component&&null==s.component.__netid)continue;const n=this.readReplicatedPropertyValue(s),o=this.serializer.encode(n),i=I.encode(o),c=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);r.push({property:s.property,component:s.component,buffer:c})}return r}shouldReplicatePropertyToConnection(e,t,n){const r=this.resolveActorConnection(e);switch(t){case b.all:return!0;case b.owner:return r?.id===n.id;case b.notOwner:return null==r||r.id!==n.id}}readReplicatedPropertyValue(e){const t=e.target[e.property];return A(t)?t.value:t}createPropertySnapshotBuffer(e,t){let n=7;const r=t.map(e=>I.encode(e.property));for(let e=0;e<t.length;e++){const s=t[e];n+=1,null!=s.component&&(n+=1),n+=1+r[e].byteLength+4+s.buffer.byteLength}const s=new ArrayBuffer(n),o=new DataView(s);let i=0;o.setUint8(i,P.propSnapshot),i+=1,o.setUint32(i,e.__netid,!0),i+=4,o.setUint16(i,t.length,!0),i+=2;for(let e=0;e<t.length;e++){const n=t[e],c=r[e],a=null!=n.component;o.setUint8(i,a?$.component:$.actor),i+=1,a&&(o.setUint8(i,n.component.__netid),i+=1),o.setUint8(i,c.byteLength),i+=1,new Uint8Array(s,i,c.byteLength).set(c),i+=c.byteLength,o.setUint32(i,n.buffer.byteLength,!0),i+=4,new Uint8Array(s,i,n.buffer.byteLength).set(new Uint8Array(n.buffer)),i+=n.buffer.byteLength}return s}decodeReplicatedValue(e){let t;if(null!=N)t=N.decode(e);else{t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[e])}return this.serializer.decode(t,F)}applyReplicatedProperty(e,t,n){A(e[t])?e[t].value=n:e[t]=n}callRepNotify(e,t){const n=e[`onRep_${t}`];"function"==typeof n&&n.call(e)}};L=e([a()],L);export{L as NetService};const Q=new c,B=new i,I=new TextEncoder,N="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function O(e,t,n){const r=new Uint8Array(e,t,n);if(null!=N)return N.decode(r);let s="";for(let e=0;e<r.length;e++)s+=String.fromCharCode(r[e]);return s}function D(e,t,n){new Uint8Array(e,t,n.byteLength).set(n)}const F=new m;/*
1
+ import{__decorate as e}from"tslib";import{delay as t,interval as n,Subject as r,takeUntil as s,tap as o}from"rxjs";import{Euler as i,Vector3 as c}from"three";import{Service as a}from"typedi";import{$actorOptions as l,BaseActor as d,getActorClassById as p}from"../../actors/actor.js";import{ActorComponent as u}from"../../actors/component.js";import{$actorComponents as f}from"../../actors/internal/component-init.js";import{inject as h}from"../../inject.js";import{World as g}from"../../services/world.js";import{NetMode as y}from"../net-session.js";import{NetRole as w}from"./net-actor-role.js";import{DecodeResult as m,NetSerializer as v}from"./net-serializer.js";import{isSignalLike as A}from"./net-utils.js";import{ReplOn as b}from"./replication.js";import{getRpcMethodId as R,getRpcMethodName as _,RunsOn as S}from"./rpc.js";import{ActorController as U,BasePlayerController as M}from"../../actors/controller/actor-controller.js";import{makePropertyReplicated as C}from"./net-decorator.js";var P;!function(e){e[e.rpc=1]="rpc",e[e.prop=2]="prop",e[e.spawn=3]="spawn",e[e.removeActor=4]="removeActor",e[e.rpcComponent=5]="rpcComponent",e[e.propComponent=6]="propComponent",e[e.rpcBinary=21]="rpcBinary",e[e.rpcComponentBinary=25]="rpcComponentBinary",e[e.actorReady=7]="actorReady",e[e.propSnapshot=8]="propSnapshot",e[e.serverTime=100]="serverTime"}(P||(P={}));var $;!function(e){e[e.actor=0]="actor",e[e.component=1]="component"}($||($={}));let L=class{constructor(){this.actorConnection=new Map,this.destroyed=new r,this.world=h(g),this.serializer=h(v),this.serverTimeOffset=0,this.actorPreSpawnMessageBuffer=new Map,this.actorRefMissingMessageQueue=new Map,this.netStartupActorSpawnQueue=new Map,this.spawningActorNetIds=new Set,this.nextNetId=1,this.shouldReplicateMap=new Map,this.replicatedActors=new Map,this.replicatedProperties=new Map,this.replicatedPropertyRegistry=new Map}get mode(){return this.session?.mode??y.none}get isClient(){return this.mode===y.client}get isServer(){return this.mode<y.client}get isDedicatedServer(){return this.mode===y.dedicatedServer}start(){if(this.stop(),this.destroyed=new r,this.isServer)for(const e of this.session.clients)this.sendServerTime(e);n(15).pipe(s(this.destroyed)).subscribe(()=>{this.processMessages()}),this.world.actorAdded.pipe(s(this.destroyed),o(e=>{this.configureMaterializedActorRole(e),this.isServer?this.defineNetId(e):this.processQueuedNetStartupActorSpawns(e)}),t(8)).subscribe(e=>{this.shouldReplicate(e)&&(C(e,"owner",this,!0,b.all),this.sendActorSpawn(e))}),this.world.actorRemoved.pipe(s(this.destroyed),t(10)).subscribe(e=>{this.sendActorRemove(e),this.replicatedActors.delete(e),this.replicatedProperties.delete(e),this.replicatedPropertyRegistry.delete(e),this.actorPreSpawnMessageBuffer.delete(e)}),this.session.playerJoined.pipe(s(this.destroyed)).subscribe(e=>{this.sendServerTime(e),this.isServer&&this.replicatedActors.size>0&&this.spawnOnLateClient(e)})}stop(){this.destroyed.next(null),this.destroyed.complete()}configureMaterializedActorRole(e){null!=e.__netSceneId&&this.mode!==y.none&&(this.shouldReplicate(e)?e.netRole=this.isServer?w.authority:w.simulatedProxy:this.isServer||(e.netRole=w.none))}shouldReplicate(e){const t=this.shouldReplicateMap.get(e);if(null==t){const t=e.constructor[l],n=!0===t?.replicate;return this.shouldReplicateMap.set(e,n),n}return!0===t}setReplicate(e,t){this.shouldReplicateMap.set(e,t)}isRelevant(e,t){const n=this.getRelevancyOptions(e);return!(!0===n?.ownerOnly)||this.resolveActorConnection(e)?.id===t.id}getRelevancyOptions(e){return e.constructor[l].relevancy}spawnOnLateClient(e){const t=[e];for(const e of this.replicatedActors.keys())this.sendActorSpawn(e,t)}async processMessages(){const e=this.session.hasMessage();for(let t=0;t<e;t++){const e=this.session.readMessage();null!=e&&await this.processMessage(e)}}async processMessage(e){try{switch(new DataView(e.buffer).getUint8(0)){case P.rpc:case P.rpcComponent:case P.rpcBinary:case P.rpcComponentBinary:this.processRpc(e.from,e.buffer);break;case P.prop:case P.propComponent:this.processProp(e.from,e.buffer);break;case P.propSnapshot:this.processPropSnapshot(e.from,e.buffer);break;case P.spawn:await this.processSpawn(e.from,e.buffer);break;case P.removeActor:this.processRemoveActor(e.from,e.buffer);break;case P.serverTime:this.processServerTime(e.from,e.buffer);break;case P.actorReady:this.processActorReady(e.from,e.buffer)}}catch(e){console.error("Failed to process message",e)}}processServerTime(e,t){if(this.isServer||this.session.server?.id!==e.id)return;const n=this.parseServerTime(t);this.serverTimeOffset=Date.now()-n}getActorRefMissingMessageQueue(e){let t=this.actorRefMissingMessageQueue.get(e);return null==t&&(t=[],this.actorRefMissingMessageQueue.set(e,t)),t}processRpc(e,t){let n=0;const r=new DataView(t),s=r.getUint8(n);n+=1;const o=r.getUint32(n,!0);n+=4;const i=r.getUint8(n);n+=1;const c=s===P.rpcBinary||s===P.rpcComponentBinary;let a,l,d="";if(c){const e=r.getUint32(n,!0);n+=4,l=new Uint8Array(t,n,e),n+=e}else{const e=r.getUint16(n,!0);n+=2,d=O(t,n,e),n+=e;try{a=this.serializer.decode(d,F)}catch(e){return void console.warn("Failed to parse RPC args JSON",d,e)}}if(!c&&F.error){if(null!=F.missingActorId){const n=this.getActorRefMissingMessageQueue(F.missingActorId);console.debug(`Missing referenced actor ${F.missingActorId}. Queueing message for later`),n.push({from:e,buffer:t})}else console.log("Unknown decode error",d);return}const p=this.world.actors.find(e=>e.__netid===o);if(null==p){return this.getActorRefMissingMessageQueue(o).push({from:e,buffer:t}),void console.debug(`Missing actor ${o}. Queueing message for later`)}let u;if(s===P.rpcComponent||s===P.rpcComponentBinary){const e=r.getUint8(n),t=p[f];if(null!=t&&(u=t.find(t=>t.__netid===e)),null==u)return void console.error(`RPC failed: Failed to find component with netid ${e} on actor with netid ${o}`)}if(this.isServer){if(!this.session.clients.some(t=>t.id==e.id))return void console.warn("Received RCP from non client");const t=this.resolveActorConnection(p);if(null==t)return void console.error("Received server RPC for actor without owner which can't be processed");if(t.id!==e.id)return void console.warn(`Received RPC for actor net id ${p.__netid} from connection ${e.id}, but this connection is not the owner. Can't process.`)}else{if(!(this.session.server?.id===e.id))return void console.warn("Received RCP from non server which is not allowed")}const h=u??p,g=_(h,i);if(null!=g)if("function"==typeof h[g])if(c)h[g](l);else{if(F.requiresAssetLookups)return this.serializer.decodeAssets(a).then(e=>{h[g](...e)}).catch(e=>{console.warn(`Failed to decode asset references for RPC '${g}' on actor net id ${p.__netid}`,e)});h[g](...a)}else console.error(`RPC function '${g}' not found on actor net id ${p.__netid}`+(null!=u?` and component net id ${u.__netid}`:""));else console.error(`RPC method id ${i} not found on actor net id ${p.__netid}`+(null!=u?` and component net id ${u.__netid}`:""))}processProp(e,t){if(this.session.server?.id!==e.id)return void console.warn(`Received property replication from non-server connection (id: ${e.id}), ignoring.`);let n=0;const r=new DataView(t),s=r.getUint8(n);n+=1;const o=r.getUint32(n,!0);n+=4;const i=r.getUint8(n);n+=1;let c="";for(let e=0;e<i;e++)c+=String.fromCharCode(r.getUint8(n+e));n+=i;const a=r.getUint16(n,!0);n+=2;const l=t.slice(n,n+a);n+=a;const d=this.world.actors.find(e=>e.__netid===o);if(!d){return this.getActorRefMissingMessageQueue(o).push({from:e,buffer:t}),void console.error("Failed to process property replication. No actor found with id",o,c)}let p;if(s===P.propComponent){const e=r.getUint8(n),t=d[f];if(null!=t&&(p=t.find(t=>t.__netid===e)),null==p)return void console.error(`Failed to find component with netid ${e} on actor with netid ${o}`)}const u=p??d;try{const n=this.decodeReplicatedValue(l);if(F.error){if(null!=F.missingActorId){let n=this.getActorRefMissingMessageQueue(F.missingActorId);console.debug(`Missing referenced actor ${F.missingActorId}. Queueing message for later`),n.push({from:e,buffer:t})}return}if(F.requiresAssetLookups)return this.serializer.decodeAssets(n).then(e=>{this.applyReplicatedProperty(u,c,e),this.callRepNotify(u,c)}).catch(e=>{console.warn(`Failed to decode asset references for replicated property '${c}' on actor id ${o}`,e)});this.applyReplicatedProperty(u,c,n),this.callRepNotify(u,c)}catch(e){console.warn(`Failed to decode replicated property '${c}' on actor id ${o}`,e)}}processPropSnapshot(e,t){if(this.session.server?.id!==e.id)return void console.warn(`Received property snapshot from non-server connection (id: ${e.id}), ignoring.`);let n=0;const r=new DataView(t);n+=1;const s=r.getUint32(n,!0);n+=4;const o=this.world.actors.find(e=>e.__netid===s);if(null==o){return this.getActorRefMissingMessageQueue(s).push({from:e,buffer:t}),void console.debug(`Missing actor ${s}. Queueing property snapshot for later`)}const i=r.getUint16(n,!0);n+=2;const c=[];for(let a=0;a<i;a++){const i=r.getUint8(n);n+=1;let a=o;if(i===$.component){const e=r.getUint8(n);n+=1;const t=o[f];if(a=t?.find(t=>t.__netid===e),null==a)return void console.error(`Failed to process property snapshot. No component found with netid ${e} on actor with netid ${s}`)}else if(i!==$.actor)return void console.error(`Failed to process property snapshot. Unknown target kind ${i}`);const l=r.getUint8(n);n+=1;let d="";for(let e=0;e<l;e++)d+=String.fromCharCode(r.getUint8(n+e));n+=l;const p=r.getUint32(n,!0);n+=4;const u=t.slice(n,n+p);n+=p;try{const n=this.decodeReplicatedValue(u);if(F.error){if(null!=F.missingActorId){this.getActorRefMissingMessageQueue(F.missingActorId).push({from:e,buffer:t}),console.debug(`Missing referenced actor ${F.missingActorId}. Queueing property snapshot for later`)}else console.warn(`Unknown decode error in property snapshot for actor ${s}`);return}c.push({target:a,property:d,value:n,requiresAssetLookups:F.requiresAssetLookups})}catch(e){return void console.warn(`Failed to decode replicated property snapshot entry '${d}' on actor id ${s}`,e)}}if(c.some(e=>e.requiresAssetLookups))return Promise.all(c.map(async e=>{e.requiresAssetLookups&&(e.value=await this.serializer.decodeAssets(e.value))})).then(()=>{this.applyReplicatedProperties(c)}).catch(e=>{console.warn(`Failed to decode asset references for property snapshot on actor id ${s}`,e)});this.applyReplicatedProperties(c)}applyReplicatedProperties(e){for(const t of e)this.applyReplicatedProperty(t.target,t.property,t.value);for(const t of e)this.callRepNotify(t.target,t.property)}async processSpawn(e,t){if(this.isServer)return;const n=new DataView(t);let r=0;r+=1;const s=n.getUint32(r,!0);r+=4;const o=n.getUint8(r);r+=1;let i="";for(let e=0;e<o;e++)i+=String.fromCharCode(n.getUint8(r+e));r+=o,Q.set(n.getFloat32(r,!0),n.getFloat32(r+4,!0),n.getFloat32(r+8,!0)),r+=12,B.set(n.getFloat32(r,!0),n.getFloat32(r+4,!0),n.getFloat32(r+8,!0)),r+=12;const c=n.getUint8(r);r+=1;const a=n.getUint32(r);r+=4;const l=this.readOptionalSceneId(t,r);console.log("Spawning "+i);const d=p(i);if(!d)return void console.error(`Failed to spawn actor: unknown actor type '${i}'`);const u=this.world.actors.find(e=>e.__netid===s);if(null!=u)return void this.applySpawnNetInfo(u,s,c,a);if(this.spawningActorNetIds.has(s))return void console.log("Actor was already spawned",null!=u);const f=this.findMaterializedNetStartupActor(l,i,s);if(null!=f)return this.applySpawnNetInfo(f,s,c,a),this.processQueuedActorMessages(s),void this.sendActorReady(f);if(null==l){this.spawningActorNetIds.add(s);try{const e=await this.world.spawnActorWithNetInfo(d,s,c,a,Q,B);this.processQueuedActorMessages(s),this.sendActorReady(e)}catch(e){return void console.error("Spawning replicated actor on client failed",e)}finally{this.spawningActorNetIds.delete(s)}}else this.getNetStartupActorSpawnQueue(l).push({from:e,buffer:t})}readOptionalSceneId(e,t){if(t+2>e.byteLength)return;const n=new DataView(e).getUint16(t,!0);return t+=2,0===n||t+n>e.byteLength?void 0:O(e,t,n)}findMaterializedNetStartupActor(e,t,n){if(null!=e)return this.world.actors.find(r=>{if(r.__netSceneId!==e)return!1;if(null!=r.__netid&&r.__netid!==n)return!1;return(r.constructor.__actorId??r.constructor.name)===t})}applySpawnNetInfo(e,t,n,r){if(e.__netid=t,e.netRole=n,0===r)e.owner=void 0;else{const t=this.world.actors.find(e=>e.__netid===r);null!=t&&(e.owner=t)}e instanceof M&&(e.isLocallyControlled=n===w.autonomousProxy)}getNetStartupActorSpawnQueue(e){let t=this.netStartupActorSpawnQueue.get(e);return null==t&&(t=[],this.netStartupActorSpawnQueue.set(e,t)),t}processQueuedNetStartupActorSpawns(e){if(null==e.__netSceneId)return;const t=this.netStartupActorSpawnQueue.get(e.__netSceneId);if(null!=t){this.netStartupActorSpawnQueue.delete(e.__netSceneId);for(const e of t)this.processMessage(e)}}processQueuedActorMessages(e){const t=this.actorRefMissingMessageQueue.get(e);if(null!=t){console.log(`Processing queued messages for actor ${e}`),this.actorRefMissingMessageQueue.delete(e);for(const e of t)this.processMessage(e)}}sendActorReady(e){if(this.mode===y.none)return;if(!e||null==e.__netid)return void console.warn("sendActorReady: actor or actor.__netid is undefined");if(this.isServer)return;const t=new ArrayBuffer(5),n=new DataView(t);let r=0;n.setUint8(r,P.actorReady),r+=1,n.setUint32(r,e.__netid,!0),this.session.server&&this.session.sendMessage(this.session.server,!0,t)}processActorReady(e,t){if(!this.isServer)return;const n=new DataView(t).getUint32(1,!0),r=this.world.actors.find(e=>e.__netid===n);if(!r)return void console.warn(`processActorReady: No actor found with net id ${n}`);const s=this.actorPreSpawnMessageBuffer.get(r),o=this.getConnectionKey(e),i=s?.get(o);if(null!=i){this.sendPropertySnapshot(r,e);const t=i.filter(e=>!this.isPropertyMessage(e.buffer));if(t.length>0){console.log(`Sending ${t.length} queued messages for actor ${r.__netid}`);for(const e of t)this.session.sendMessage(e.connection,e.reliable,e.buffer)}s.delete(o),0===s.size&&this.actorPreSpawnMessageBuffer.delete(r)}}sendRpc(e,t,n,r,s,o){if(this.mode==y.none)return;if(!this.shouldReplicate(n))return;const i=n.__netid;if(null==i)return void console.warn("No __netid defined on actor. Actor must be repliated for RPC");const c=this.resolveActorConnection(n),a=[];if(this.isServer)switch(e){case S.all:a.push(...this.session.clients.filter(e=>this.isRelevant(n,e)));break;case S.client:null!=c&&a.push(c);break;case S.notOwner:a.push(...this.session.clients.filter(e=>e.id!==c?.id&&this.isRelevant(n,e)));case S.server:}else switch(e){case S.all:case S.client:case S.notOwner:break;case S.server:a.push(this.session.server)}if(0==a.length)return;if(null!=o&&null==o.__netid)return void console.warn("No __netid defined on component. Component must be initialized for RPC",o);const l=null!=o,d=o??n,p=R(d,r);if(null==p)return void console.warn(`RPC function '${r}' is not registered on ${d.constructor?.name??"target"}`);const u=1===s.length?function(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if("undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return null}(s[0]):null;if(null!=u){let e=10+u.byteLength;l&&(e+=1);const r=new ArrayBuffer(e),s=new DataView(r);let c=0;s.setUint8(c,l?P.rpcComponentBinary:P.rpcBinary),c+=1,s.setUint32(c,i,!0),c+=4,s.setUint8(c,p),c+=1,s.setUint32(c,u.byteLength,!0),c+=4,D(r,c,u),c+=u.byteLength,l&&(s.setUint8(c,o.__netid),c+=1);for(const e of a)null!=e&&this.sendWithQueue(n,{connection:e,reliable:t,buffer:r});return}const f=this.serializer.encode(s),h=I.encode(f);if(h.byteLength>65535)return void console.warn("RPC arguments are too large to send with the JSON RPC format",r);let g=8+h.byteLength;l&&(g+=1);const w=new ArrayBuffer(g),m=new DataView(w);let v=0;m.setUint8(v,l?P.rpcComponent:P.rpc),v+=1,m.setUint32(v,i,!0),v+=4,m.setUint8(v,p),v+=1,m.setUint16(v,h.byteLength,!0),v+=2,D(w,v,h),v+=h.byteLength,l&&(m.setUint8(v,o.__netid),v+=1);for(const e of a)null!=e&&this.sendWithQueue(n,{connection:e,reliable:t,buffer:w})}sendWithQueue(e,t){if(this.shouldQueueMessageUntilActorReady(e,t.connection)){return void this.getPreSpawnMessageQueue(e,t.connection).push(t)}this.session.sendMessage(t.connection,t.reliable,t.buffer)}findQueuedActorsInData(e,t=[]){if("object"==typeof e){if(Array.isArray(e))for(const t of e)this.findQueuedActorsInData(t);if(e instanceof d){this.actorPreSpawnMessageBuffer.get(e)}}}handlePropertySet(e,t,n,r,s,o){if(this.mode==y.none)return;if(!this.isServer)return;if(!this.shouldReplicate(n))return;let i=this.replicatedProperties.get(n);null==i&&(i={},this.replicatedProperties.set(n,i));const c=this.serializer.encode(s),a=I.encode(c),l=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);i[this.getReplicatedPropertyKey(r,o)]={property:r,replOn:e,reliable:t,buffer:l,component:o},this.sendProperty(e,t,n,r,l,o)}sendProperty(e,t,n,r,s,o){if(!this.isServer)return;const i=[],c=this.resolveActorConnection(n);switch(e){case b.all:i.push(...this.session.clients);break;case b.owner:null!=c&&i.push(c);break;case b.notOwner:null==c?i.push(...this.session.clients):i.push(...this.session.clients.filter(e=>e.id!==c.id))}const a=null!=o&&null!=o.__netid;let l=6+r.length+2+s.byteLength;a&&(l+=1);const d=new ArrayBuffer(l),p=new DataView(d);let u=0;p.setUint8(u,a?P.propComponent:P.prop),u+=1,p.setUint32(u,n.__netid,!0),u+=4,p.setUint8(u,r.length),u+=1;for(let e=0;e<r.length;e++)p.setUint8(u++,r.charCodeAt(e));p.setUint16(u,s.byteLength,!0),u+=2,new Uint8Array(d,u,s.byteLength).set(new Uint8Array(s)),u+=s.byteLength,a&&(p.setUint8(u,o.__netid),u+=1);for(const e of i)null!=e&&this.isRelevant(n,e)&&this.sendWithQueue(n,{connection:e,reliable:t,buffer:d})}defineNetId(e){null==e.__netid&&(e.__netid=this.nextNetId++)}registerReplicatedProperty(e,t,n,r,s,o){if(null==n||null==r||null==s)return;let i=this.replicatedPropertyRegistry.get(n);null==i&&(i=[],this.replicatedPropertyRegistry.set(n,i));const c=o??(s instanceof u?s:void 0),a=i.find(e=>e.target===s&&e.property===r);if(null!=a)return a.replOn=e,a.reliable=t,void(a.component=c);i.push({property:r,replOn:e,reliable:t,target:s,component:c})}sendActorSpawn(e,t=this.session.clients){if(!this.isServer)return;const n=t.filter(t=>this.isRelevant(e,t));this.defineNetId(e);const r=e.__netid;let s=e.constructor.__actorId??e.constructor.name;const o=I.encode(s);let i;null!=e.__netSceneId&&(i=I.encode(e.__netSceneId),i.byteLength>65535&&(console.warn(`Scene actor id is too long to replicate as a startup actor: ${e.__netSceneId}`),i=void 0));const c=i?.byteLength??0,a=6+o.length+12+12+1+4+2+c,l=new ArrayBuffer(a),d=new DataView(l);let p=0;d.setUint8(p,P.spawn),p+=1,d.setUint32(p,r,!0),p+=4,d.setUint8(p,o.length),p+=1,new Uint8Array(l).set(o,p),p+=o.length,d.setFloat32(p,e.position.x,!0),p+=4,d.setFloat32(p,e.position.y,!0),p+=4,d.setFloat32(p,e.position.z,!0),p+=4,d.setFloat32(p,e.rotation.x,!0),p+=4,d.setFloat32(p,e.rotation.y,!0),p+=4,d.setFloat32(p,e.rotation.z,!0),p+=4;let u=p;p+=1,d.setUint32(p,e.owner?.__netid??0),p+=4,d.setUint16(p,c,!0),p+=2,null!=i&&(D(l,p,i),p+=i.byteLength);let f=this.replicatedActors.get(e);null==f&&(f={spawnedAt:Date.now(),connections:[]},this.replicatedActors.set(e,f));for(const t of n){const n=l.slice(0),r=new DataView(n),s=this.resolveActorConnection(e)?.id===t.id?w.autonomousProxy:w.simulatedProxy;r.setUint8(u,s),this.getPreSpawnMessageQueue(e,t),this.session.sendMessage(t,!0,n),f.connections.some(e=>e.id===t.id)||f.connections.push(t)}}sendActorRemove(e){if(!this.isServer)return;const t=new ArrayBuffer(5),n=new DataView(t);let r=0;n.setUint8(r,P.removeActor),r+=1,n.setUint32(r,e.__netid,!0);for(const e of this.session.clients)this.session.sendMessage(e,!0,t)}processRemoveActor(e,t){if(this.isServer||this.session.server?.id!==e.id)return;const n=new DataView(t).getUint32(1,!0),r=this.world.actors.find(e=>e.__netid===n);r&&(this.world.removeActor(r),this.replicatedActors?.delete?.(r),this.replicatedProperties?.delete?.(r))}setOwningConnection(e,t){this.actorConnection.set(e.id,t)}getOwningConnection(e){return this.actorConnection.get(e.id)}getActorsByOwningConnection(e){const t=[];return this.actorConnection.forEach((n,r)=>{if(n.id===e.id){const e=this.world.actors.find(e=>e.id===r);null!=e&&t.push(e)}}),t}resolveActorConnection(e){let t;for(;null==t&&null!=e;)t=this.actorConnection.get(e.id),null==t&&(e=e.owner);return t}isLocallyControlled(e){let t=e;for(;null!=t;){if(t.netRole===w.autonomousProxy)return!0;if(t instanceof U)return t.isLocallyControlled;t=e.owner}return!1}isLocalOwner(e){return this.isLocallyControlled(e)}sendServerTime(e){const t=new ArrayBuffer(9),n=new DataView(t);n.setUint8(0,P.serverTime),n.setBigUint64(1,BigInt(Date.now()),!0),this.session.sendMessage(e,!0,t)}parseServerTime(e){const t=new DataView(e).getBigUint64(1,!0);return Number(t)}getConnectionKey(e){return e.id.toString()}getPreSpawnMessageQueue(e,t){let n=this.actorPreSpawnMessageBuffer.get(e);null==n&&(n=new Map,this.actorPreSpawnMessageBuffer.set(e,n));const r=this.getConnectionKey(t);let s=n.get(r);return null==s&&(s=[],n.set(r,s)),s}shouldQueueMessageUntilActorReady(e,t){const n=this.actorPreSpawnMessageBuffer.get(e);return!!n?.has(this.getConnectionKey(t))||this.isServer&&!this.replicatedActors.has(e)&&this.shouldReplicate(e)}isPropertyMessage(e){const t=new DataView(e).getUint8(0);return t===P.prop||t===P.propComponent}getReplicatedPropertyKey(e,t){return null!=t?.__netid?`component:${t.__netid}:${e}`:`actor:${e}`}sendPropertySnapshot(e,t){const n=this.buildPropertySnapshotEntries(e,t);if(0===n.length)return;const r=this.createPropertySnapshotBuffer(e,n);this.session.sendMessage(t,!0,r)}buildPropertySnapshotEntries(e,t){if(!this.isRelevant(e,t))return[];const n=this.replicatedPropertyRegistry.get(e);if(null==n)return[];const r=[];for(const s of n){if(!this.shouldReplicatePropertyToConnection(e,s.replOn,t))continue;if(null!=s.component&&null==s.component.__netid)continue;const n=this.readReplicatedPropertyValue(s),o=this.serializer.encode(n),i=I.encode(o),c=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);r.push({property:s.property,component:s.component,buffer:c})}return r}shouldReplicatePropertyToConnection(e,t,n){const r=this.resolveActorConnection(e);switch(t){case b.all:return!0;case b.owner:return r?.id===n.id;case b.notOwner:return null==r||r.id!==n.id}}readReplicatedPropertyValue(e){const t=e.target[e.property];return A(t)?t.value:t}createPropertySnapshotBuffer(e,t){let n=7;const r=t.map(e=>I.encode(e.property));for(let e=0;e<t.length;e++){const s=t[e];n+=1,null!=s.component&&(n+=1),n+=1+r[e].byteLength+4+s.buffer.byteLength}const s=new ArrayBuffer(n),o=new DataView(s);let i=0;o.setUint8(i,P.propSnapshot),i+=1,o.setUint32(i,e.__netid,!0),i+=4,o.setUint16(i,t.length,!0),i+=2;for(let e=0;e<t.length;e++){const n=t[e],c=r[e],a=null!=n.component;o.setUint8(i,a?$.component:$.actor),i+=1,a&&(o.setUint8(i,n.component.__netid),i+=1),o.setUint8(i,c.byteLength),i+=1,new Uint8Array(s,i,c.byteLength).set(c),i+=c.byteLength,o.setUint32(i,n.buffer.byteLength,!0),i+=4,new Uint8Array(s,i,n.buffer.byteLength).set(new Uint8Array(n.buffer)),i+=n.buffer.byteLength}return s}decodeReplicatedValue(e){let t;if(null!=N)t=N.decode(e);else{t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[e])}return this.serializer.decode(t,F)}applyReplicatedProperty(e,t,n){A(e[t])?e[t].value=n:e[t]=n}callRepNotify(e,t){const n=e[`onRep_${t}`];"function"==typeof n&&n.call(e)}};L=e([a()],L);export{L as NetService};const Q=new c,B=new i,I=new TextEncoder,N="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function O(e,t,n){const r=new Uint8Array(e,t,n);if(null!=N)return N.decode(r);let s="";for(let e=0;e<r.length;e++)s+=String.fromCharCode(r[e]);return s}function D(e,t,n){new Uint8Array(e,t,n.byteLength).set(n)}const F=new m;/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{inject as n}from"../../inject";import{NetService as t}from"./net-service";import{registerRpcMethod as e,RunsOn as r}from"./rpc";import{BaseActor as o}from"../../actors/actor";import{NetMode as i}from"../net-session";import{ActorComponent as c}from"../../actors/component";export function RunOnServer(n=!0){return s(r.server,n)}export function RunOnClient(n=!0){return s(r.client,n)}export function RunOnNotOwner(n=!0){return s(r.notOwner,n)}export function RunOnAll(n=!0){return s(r.all,n)}function s(r,o=!0){return function(...i){if(i.length>=3){const[c,s,u]=i,a=u.value,f=s.toString();let p;return e(c,f),u.value=l(a,f,r,o,()=>(p??(p=n(t)),p)),u}const[c,s]=i,u=s.name.toString();let a;return s.addInitializer(function(){e(Object.getPrototypeOf(this),u),a=n(t)}),l(c,u,r,o,()=>(a??(a=n(t)),a))}}function l(n,t,e,s,l){return function(...u){const a=l();if(!(this instanceof o||this instanceof c))return void console.warn("RPC is defined on a non actor");let f,p;if(this instanceof o)f=this;else if(f=this.actor,p=this,null==f)return void console.warn("Can't call RPC on component before actor is set");let m,v=!1;return a.isServer&&(e===r.all||e===r.server||e===r.notOwner&&!a.isLocalOwner(f)&&a.mode===i.listenServer||e===r.client&&!a.isDedicatedServer&&a.isLocalOwner(f))?v=!0:a.isServer||e!==r.all&&e!==r.client&&e!==r.notOwner||(v=!0),v&&(m=n.apply(this,u)),a&&"function"==typeof a.sendRpc?a.sendRpc(e,s,f,t,u,p):console.warn("Net service is not set up",{netService:a}),m}}/*
1
+ import{inject as n}from"../../inject.js";import{NetService as t}from"./net-service.js";import{registerRpcMethod as e,RunsOn as r}from"./rpc.js";import{BaseActor as o}from"../../actors/actor.js";import{NetMode as i}from"../net-session.js";import{ActorComponent as s}from"../../actors/component.js";export function RunOnServer(n=!0){return c(r.server,n)}export function RunOnClient(n=!0){return c(r.client,n)}export function RunOnNotOwner(n=!0){return c(r.notOwner,n)}export function RunOnAll(n=!0){return c(r.all,n)}function c(r,o=!0){return function(...i){if(i.length>=3){const[s,c,u]=i,a=u.value,f=c.toString();let p;return e(s,f),u.value=l(a,f,r,o,()=>(p??(p=n(t)),p)),u}const[s,c]=i,u=c.name.toString();let a;return c.addInitializer(function(){e(Object.getPrototypeOf(this),u),a=n(t)}),l(s,u,r,o,()=>(a??(a=n(t)),a))}}function l(n,t,e,c,l){return function(...u){const a=l();if(!(this instanceof o||this instanceof s))return void console.warn("RPC is defined on a non actor");let f,p;if(this instanceof o)f=this;else if(f=this.actor,p=this,null==f)return void console.warn("Can't call RPC on component before actor is set");let m,v=!1;return a.isServer&&(e===r.all||e===r.server||e===r.notOwner&&!a.isLocalOwner(f)&&a.mode===i.listenServer||e===r.client&&!a.isDedicatedServer&&a.isLocalOwner(f))?v=!0:a.isServer||e!==r.all&&e!==r.client&&e!==r.notOwner||(v=!0),v&&(m=n.apply(this,u)),a&&"function"==typeof a.sendRpc?a.sendRpc(e,c,f,t,u,p):console.warn("Net service is not set up",{netService:a}),m}}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -25,6 +25,7 @@ export declare class AssetLoader {
25
25
  private ktx2Loader;
26
26
  private textureLoader;
27
27
  private audioLoader;
28
+ private animationVariantIds;
28
29
  constructor(assetResourceLoader: AssetResourceLoader, assetService: AssetsProvider, shaders: ShaderImpl[]);
29
30
  /**
30
31
  * @param filePath
@@ -45,6 +46,12 @@ export declare class AssetLoader {
45
46
  getModelByAssetName(name: string): Promise<LoadedMesh>;
46
47
  getModelByAssetId(id: AssetId): Promise<LoadedMesh>;
47
48
  getAnimationClipByAssetId(id: AssetId): Promise<THREE.AnimationClip | null>;
49
+ /**
50
+ * Resolve an animation reference for a concrete target rig without running a
51
+ * retarget solver. A mismatched source clip must already have a generated
52
+ * output recorded by an Animation Retargeter asset.
53
+ */
54
+ getAnimationClipForTargetByAssetId(id: AssetId, targetRigId?: AssetId): Promise<THREE.AnimationClip | null>;
48
55
  getAnimationClipByAssetName(name: string): Promise<THREE.AnimationClip | null>;
49
56
  getTextureByAssetName(name: string): Promise<THREE.Texture>;
50
57
  getTextureByAssetId(id: AssetId): Promise<THREE.Texture>;
@@ -1,4 +1,4 @@
1
- import{__decorate as e,__metadata as t}from"tslib";import{AudioLoader as s,LoadingManager as a,TextureLoader as r}from"three";import{FBXLoader as i,GLTFLoader as o,MTLLoader as n,OBJLoader as h,TGALoader as d}from"three-stdlib";import{KTX2Loader as c}from"three/examples/jsm/Addons.js";import{Service as l}from"typedi";import{AssetResourceLoader as u}from"../../scene/asset-resource-loader.js";import{applyMaterial as w}from"../../scene/materializer";import{materialFromAsset as g,materializeDataAssetRef as f,prepareShaderGraphParameters as m}from"../../scene/materializer.js";import{Prefab as y}from"../../scene/objects/prefab.js";import{pathJoin as A}from"../../utils/files.js";import{Sequence as p}from"../../effects/sequence/sequence-data.js";let b=class{constructor(e,t,l){this.assetResourceLoader=e,this.assetService=t,this.shaders=l,this.baseUrl="",this.urlSuffix="",this.loadingManager=new a,this.glbLoader=new o(this.loadingManager),this.fbxLoader=new i(this.loadingManager),this.objLoader=new h(this.loadingManager),this.mtlLoader=new n(this.loadingManager),this.tgaLoader=new d(this.loadingManager),this.ktx2Loader=new c(this.loadingManager),this.textureLoader=new r(this.loadingManager),this.audioLoader=new s(this.loadingManager),this.assetResourceLoader.materialProvider=e=>this.getMaterialByAssetId(e)}resolvePath(e){return A(this.baseUrl,e)+this.urlSuffix}getAudioAtPath(e){const t=this.resolvePath(e);return this.audioLoader.loadAsync(t)}async getAudioByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No audio could be found with asset id ${e}`);return this.assetResourceLoader.getAudio(t)}async getAudioByAssetName(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No audio could be found with asset name ${e}`);return this.assetResourceLoader.getAudio(t)}async getModelAtPath(e){const t=this.resolvePath(e);switch(e.split(".").pop().toLowerCase()){case"glb":case"gltf":return(await this.glbLoader.loadAsync(t)).scene;case"fbx":return this.fbxLoader.loadAsync(t);case"obj":return this.objLoader.loadAsync(t);default:throw new Error(`File suffix is not supperted in file ${e}`)}}async getGltfAtPath(e){const t=this.resolvePath(e);return this.glbLoader.loadAsync(t)}async getModelByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No model could be found with asset name ${e}`);return this.assetResourceLoader.getMesh(t,{applyMaterials:!0,materialResolver:e=>this.getMaterialByAssetId(e)})}async getModelByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No model could be found with asset id ${e}`);return this.assetResourceLoader.getMesh(t,{applyMaterials:!0,materialResolver:e=>this.getMaterialByAssetId(e)})}async getAnimationClipByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No animation clip could be found with asset id ${e}`);return this.assetResourceLoader.getAnimationClip(t)}async getAnimationClipByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No animation clip could be found with asset name ${e}`);return this.assetResourceLoader.getAnimationClip(t)}async applyMaterials(e,t){for(const s of e.materialAssignments??[])await w(t,s,async e=>this.getMaterialByAssetId(e))}async getTextureByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No texture could be found with asset name ${e}`);return this.assetResourceLoader.getTexture(t)}async getTextureByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No texture could be found with asset id ${e}`);return this.assetResourceLoader.getTexture(t)}async getSequenceById(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No sequence could be found with asset id ${e}`);if(null==t.sequence)throw new Error(`Missing sequence data in asset ${e}`);return new p(t.sequence)}async getSequenceByName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No sequence could be found with asset name ${e}`);if(null==t.sequence)throw new Error(`Missing sequence data in asset ${e}`);return new p(t.sequence)}async getDataAssetById(e,t){const s=await f(e,this.assetService,this.assetResourceLoader,void 0,void 0,this.shaders);if(null!=t&&null!=s&&!(s.value instanceof t))throw new Error(`Invalid type. Expecting asset with id ${e} to be of type ${t.name} but got:`+s.value);return s}async getDataAssetByName(e,t){const s=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==s)throw new Error(`No data asset could be found with name ${e}`);return this.getDataAssetById(s.id,t)}async getShaderGraphByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No shader graph could be found with asset id ${e}`);if("shaderGraph"!==t.type||null==t.shaderGraph)throw new Error(`Missing shader graph data in asset ${e}`);return t.shaderGraph}async prepareShaderGraphParameters(e,t={}){return m(t,e,this.assetService,this.assetResourceLoader,void 0,this.shaders)}async getMaterialByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No material could be found with asset id ${e}`);return g(t,null,this.assetService,this.assetResourceLoader,this.shaders,!1)}async getAsset(e){return this.assetService.getAsset(e)}async getPrefabByName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if("prefab"!==t.type)throw`Asset with name ${e} is not a prefab`;return new y(t)}async getPrefabById(e){const t=await this.getAsset(e);if("prefab"!==t.type)throw`Asset with name ${name} is not a prefab`;return new y(t)}clearCache(e){this.assetResourceLoader.clearCache(e)}clearCacheById(e){this.assetResourceLoader.clearCacheById(e)}};b=e([l(),t("design:paramtypes",[u,Function,Array])],b);export{b as AssetLoader};/*
1
+ import{__decorate as e,__metadata as t}from"tslib";import{AudioLoader as s,LoadingManager as a,TextureLoader as r}from"three";import{FBXLoader as i,GLTFLoader as n,MTLLoader as o,OBJLoader as h,TGALoader as d}from"three-stdlib";import{KTX2Loader as c}from"three/examples/jsm/Addons.js";import{Service as l}from"typedi";import{AssetResourceLoader as u}from"../../scene/asset-resource-loader.js";import{applyMaterial as w}from"../../scene/materializer";import{materialFromAsset as g,materializeDataAssetRef as f,prepareShaderGraphParameters as m}from"../../scene/materializer.js";import{Prefab as y}from"../../scene/objects/prefab.js";import{pathJoin as A}from"../../utils/files.js";import{Sequence as p}from"../../effects/sequence/sequence-data.js";import{resolveAnimationClipAssetForTarget as b}from"../animation/retarget.js";let v=class{constructor(e,t,l){this.assetResourceLoader=e,this.assetService=t,this.shaders=l,this.baseUrl="",this.urlSuffix="",this.loadingManager=new a,this.glbLoader=new n(this.loadingManager),this.fbxLoader=new i(this.loadingManager),this.objLoader=new h(this.loadingManager),this.mtlLoader=new o(this.loadingManager),this.tgaLoader=new d(this.loadingManager),this.ktx2Loader=new c(this.loadingManager),this.textureLoader=new r(this.loadingManager),this.audioLoader=new s(this.loadingManager),this.animationVariantIds=new Map,this.assetResourceLoader.materialProvider=e=>this.getMaterialByAssetId(e),this.assetResourceLoader.animationRigProvider=async e=>(await this.assetService.getAsset(e))?.animationRig}resolvePath(e){return A(this.baseUrl,e)+this.urlSuffix}getAudioAtPath(e){const t=this.resolvePath(e);return this.audioLoader.loadAsync(t)}async getAudioByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No audio could be found with asset id ${e}`);return this.assetResourceLoader.getAudio(t)}async getAudioByAssetName(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No audio could be found with asset name ${e}`);return this.assetResourceLoader.getAudio(t)}async getModelAtPath(e){const t=this.resolvePath(e);switch(e.split(".").pop().toLowerCase()){case"glb":case"gltf":return(await this.glbLoader.loadAsync(t)).scene;case"fbx":return this.fbxLoader.loadAsync(t);case"obj":return this.objLoader.loadAsync(t);default:throw new Error(`File suffix is not supperted in file ${e}`)}}async getGltfAtPath(e){const t=this.resolvePath(e);return this.glbLoader.loadAsync(t)}async getModelByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No model could be found with asset name ${e}`);return this.assetResourceLoader.getMesh(t,{applyMaterials:!0,materialResolver:e=>this.getMaterialByAssetId(e)})}async getModelByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No model could be found with asset id ${e}`);return this.assetResourceLoader.getMesh(t,{applyMaterials:!0,materialResolver:e=>this.getMaterialByAssetId(e)})}async getAnimationClipByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No animation clip could be found with asset id ${e}`);return this.assetResourceLoader.getAnimationClip(t)}async getAnimationClipForTargetByAssetId(e,t){const s=await this.assetService.getAsset(e);if(null==s)throw new Error(`No animation clip could be found with asset id ${e}`);let a=s;if(null!=t&&s.anim?.rigId!==t){const r=`${e}|${t}`,i=this.animationVariantIds.get(r);null!=i?a=await this.assetService.getAsset(i):(a=b(s,await this.assetService.getAssets(),t),this.animationVariantIds.set(r,a.id))}return this.assetResourceLoader.getAnimationClip(a)}async getAnimationClipByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No animation clip could be found with asset name ${e}`);return this.assetResourceLoader.getAnimationClip(t)}async applyMaterials(e,t){for(const s of e.materialAssignments??[])await w(t,s,async e=>this.getMaterialByAssetId(e))}async getTextureByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No texture could be found with asset name ${e}`);return this.assetResourceLoader.getTexture(t)}async getTextureByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No texture could be found with asset id ${e}`);return this.assetResourceLoader.getTexture(t)}async getSequenceById(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No sequence could be found with asset id ${e}`);if(null==t.sequence)throw new Error(`Missing sequence data in asset ${e}`);return new p(t.sequence)}async getSequenceByName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No sequence could be found with asset name ${e}`);if(null==t.sequence)throw new Error(`Missing sequence data in asset ${e}`);return new p(t.sequence)}async getDataAssetById(e,t){const s=await f(e,this.assetService,this.assetResourceLoader,void 0,void 0,this.shaders);if(null!=t&&null!=s&&!(s.value instanceof t))throw new Error(`Invalid type. Expecting asset with id ${e} to be of type ${t.name} but got:`+s.value);return s}async getDataAssetByName(e,t){const s=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==s)throw new Error(`No data asset could be found with name ${e}`);return this.getDataAssetById(s.id,t)}async getShaderGraphByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No shader graph could be found with asset id ${e}`);if("shaderGraph"!==t.type||null==t.shaderGraph)throw new Error(`Missing shader graph data in asset ${e}`);return t.shaderGraph}async prepareShaderGraphParameters(e,t={}){return m(t,e,this.assetService,this.assetResourceLoader,void 0,this.shaders)}async getMaterialByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No material could be found with asset id ${e}`);return g(t,null,this.assetService,this.assetResourceLoader,this.shaders,!1)}async getAsset(e){return this.assetService.getAsset(e)}async getPrefabByName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if("prefab"!==t.type)throw`Asset with name ${e} is not a prefab`;return new y(t)}async getPrefabById(e){const t=await this.getAsset(e);if("prefab"!==t.type)throw`Asset with name ${name} is not a prefab`;return new y(t)}clearCache(e){this.animationVariantIds.clear(),this.assetResourceLoader.clearCache(e)}clearCacheById(e){this.animationVariantIds.clear(),this.assetResourceLoader.clearCacheById(e)}};v=e([l(),t("design:paramtypes",[u,Function,Array])],v);export{v as AssetLoader};/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -237,6 +237,8 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
237
237
  * @returns The corrected movement vector accounting for collisions
238
238
  */
239
239
  getActorComputedMovement(actor: BaseActor, cc: KinematicCharacterController, desiredTranslation: Vector3, collisionGroup?: number): Vector3;
240
+ setActorCapsuleCollider(actor: BaseActor, length: number, radius: number, offsetY: number): boolean;
241
+ hasActorCapsuleIntersection(actor: BaseActor, position: Vector3, length: number, radius: number, offsetY: number, collisionFilter?: InteractionGroups): boolean;
240
242
  /**
241
243
  * Creates a collider from a given collision shape.
242
244
  * This method adds a collision shape to the physics world as a collider,
@@ -517,6 +519,18 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
517
519
  * @returns Observable boolean indicating contact state
518
520
  */
519
521
  onHasContactChanged(self: BaseActor): Observable<boolean>;
522
+ /**
523
+ * Gets an observable for when an actor begins overlapping any other actor.
524
+ * @param self - The actor to observe overlaps for
525
+ * @returns Observable of overlapping actors
526
+ */
527
+ onBeginOverlap<T extends BaseActor>(self: T): Observable<BaseActor>;
528
+ /**
529
+ * Gets an observable for when an actor ends overlapping any other actor.
530
+ * @param self - The actor to observe overlaps for
531
+ * @returns Observable of overlapping actors
532
+ */
533
+ onEndOverlap<T extends BaseActor>(self: T): Observable<BaseActor>;
520
534
  /**
521
535
  * Gets an observable for when an actor begins overlapping with actors of a specific type.
522
536
  * @param self - The actor to observe overlaps for
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as e}from"tslib";import*as i from"@dimforge/rapier3d-simd-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-simd-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as l,takeUntil as c}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as y,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as x,Scene as B,Vector3 as b}from"three";import*as v from"three/examples/jsm/utils/BufferGeometryUtils.js";import{Service as C}from"typedi";import{ActorComponent as S,Component as A}from"../../../gameplay/actors/component.js";import{inject as R}from"../../../gameplay/inject.js";import{BoxCollisionShape as D,CapsuleCollisionShape as T,ConeCollisionShape as z,ConvexPolyhedronCollisionShape as M,CylinderCollisionShape as E,PhysicalShapeMesh as P,PlaneCollisionShape as _,SphereCollisionShape as F,toInstancedCollisionShape as I,TrimeshCollisionShape as V}from"../../../index.js";import{AssetMeshInstance as k}from"../../../scene/asset-resource-loader.js";import{LandscapeGroup as j}from"../../../scene/landscape/landscape.js";import{calculateEffectiveScale as N}from"../../../utils/three/traverse.js";import{ViewController as W}from"../render.js";import{World as L}from"../world.js";import{AbstractPhysicsSystem as O}from"./abstract-physics-system.js";import{NetRole as G}from"../../net/index.js";export{ActorComponent,attach,Attach,Component}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.hitNormal=new b}}export class ShapeCastResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.normal=new b}reset(){this.actor=void 0,this.hasHit=!1,this.distance=0,this.hitPoint.set(0,0,0),this.normal.set(0,0,0)}}ShapeCastResult.shared=new ShapeCastResult;export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));const K=new b,U=new b,q=new w,H=new w,Q=(new w,[]);let $=class extends O{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(){super(),this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.colliders=new Map,this.collisionEvents=new l,this.beforeStep=new l,this.afterStep=new l,this.shouldRenderDebug=!1,this.viewController=R(W),this.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new x,this._reusableResult=new RayTestResult,this._raytestDiff=new b,this._raytestDirection=new b,this.controlledActors=new Set,this._isStopped=!1,this.ready=this.setup()}getBallShape(t){let e=this.shapeCacheBall.get(t);return null==e&&(e=new this.rapier.Ball(t),this.shapeCacheBall.set(t,e)),e}getBoxShape(t,e,i){const s=t+1e6*e+1e12*i;let o=this.shapeCacheBox.get(s);return null==o&&(o=new this.rapier.Cuboid(t,e,i),this.shapeCacheBox.set(s,o)),o}hasBoxIntersection(t){const e=t.getCenter(K),i=t.getSize(U),s=this.getBoxShape(i.x/2,i.y/2,i.z/2);return null!=this.world.intersectionWithShape(e,q,s)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,q,e)}findActorsInRadius(t,e,i){const s=this.getBallShape(e),o=[];for(const[e,n]of this.bodyActors)if(n instanceof i||null==i)for(let i=0,r=e.numColliders();i<r;i++){e.collider(i).intersectsShape(s,t,q)&&o.push(n)}return o}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.handleCollisionEvents(),this.ready}handleCollisionEvents(){this.collisionSub=this.collisionEvents.subscribe(t=>{const e=this.colliders.get(t.handle1);if(null==e)return;const i=this.world.getCollider(t.handle2);if(null==i||null==i.parent())return;const s=this.bodyActors.get(i.parent());null!=s&&(t.started?e.onBeginOverlapActor.next({actor:s}):e.onEndOverlapActor.next({actor:s}))})}renderDebug(){if(null==this.scene)return;null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.scene?.add(this.debugMesh));const t=this.world.debugRender().vertices,e=this.debugMesh.geometry,i=e.getAttribute("position");null==i||(i.array.length,t.length);{const i=new u(t,3);i.setUsage(d.DynamicDrawUsage),e.setAttribute("position",i)}e.setDrawRange(0,t.length/3)}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await ct(),this.eventQueue=new this.rapier.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe(t=>{this._isStopped||(t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach(t=>{if(t.isFixed())return;let e,i=this.staticMeshes.get(t);if(null==i&&(e=this.bodyActors.get(t),null!=e)){if(e.netRole===G.simulatedProxy)return;i=e.object}null!=i&&i.parent instanceof B&&(ut(i.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&yt(i.quaternion,t.rotation()),i.matrixWorldNeedsUpdate=!0)}),this.afterStep.next(t))})}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this._isStopped||(this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents((t,e,i)=>{this.collisionEvents.next({handle1:t,handle2:e,started:i}),this.collisionEvents.next({handle1:e,handle2:t,started:i})}))}rayTestFromCamera(t,e,i){this._raycaster.setFromCamera(nt,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(s);return this.rayTest(s,o,e,i)}rayTest(t,e,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),i;null==xt&&(xt=new this.rapier.Ray(new this.rapier.Vector3(0,0,0),new this.rapier.Vector3(0,1,0))),dt(xt.origin,t),dt(xt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(xt,r,!1,void 0,s?.collisionFilter,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?t=>!t.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const e=xt.pointAt(a.timeOfImpact);if(i._internal=a,ut(i.hitNormal,a.normal),ut(i.hitPoint,e),i.distance=gt.subVectors(i.hitPoint,t).length(),!1!==s?.resolveActor){const t=this.world.bodies.getAll().find(t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,t=>t===a.collider));i.actor=null!=t?this.bodyActors.get(t):null}}if(this.showDebug){let e;Q.length>0?(e=Q.pop(),e.setDirection(n),e.position.copy(t),e.setLength(r,.2,.1),e.setColor(s?.debugColor??255)):e=new h(n,t,r,s?.debugColor??255),this.scene?.add(e),setTimeout(()=>{this.scene?.remove(e),Q.push(e)},s?.debugLifetime??200)}return i}setGravity(t,e,i){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=i}getGravity(){return J.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())pt(t,t=>t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof P&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof k){const e=!1!==t.userData?.src?.collisionDetection;if(t.children[0]&&(t.children[0].instanceMatrix&&e||t.children[0].isBatchedMesh))this.createForInstancedMesh(t.children[0],t.collisionShapes);else if(e&&t.children.length>0){const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}}else t instanceof j?this.addLandscapeGroup(t):(t instanceof p||t instanceof B)&&t.children.forEach(t=>this.addRecursively(t))}createForInstancedMesh(t,e){const i=new m;if(t instanceof d.BatchedMesh){const e=t._instanceInfo??t._drawInfo,s=new Map;for(let o=0;o<e.length;o++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[o])continue;const e=t.userData.collisionShapes;let n=e?.[o];if(null==n&&null==e&&t.parent instanceof k&&(n=t.parent.collisionShapes),null==n)continue;let r=s.get(n);null==r&&(r=this.instancedShapeReset(n),s.set(n,r));const a=new f;a.matrix.identity(),t.getMatrixAt(o,i),a.applyMatrix4(i);this.createStaticBody(a,r)}}else{const s=this.instancedShapeReset(e);for(let e=0;e<t.count;e++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[e])continue;const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*e),o.applyMatrix4(i);this.createStaticBody(o,s)}}}instancedShapeReset(t){return t.filter(t=>null!=t).map(t=>I(t))}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,i,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,o,ft);const a=e.computedMovement();return ut(mt,a),mt}createCollider(t,e){const i=this.addShape(e?.body,t),s=new PhysicsCollider(i,this.world);return this.colliders.set(i.handle,s),s.disposed.subscribe(()=>{this.colliders.delete(i.handle)}),s}createBody(t=PhysicsBodyType.dynamic,e={}){const i=(()=>{switch(t){case PhysicsBodyType.dynamic:return this.rapier.RigidBodyDesc.dynamic();case PhysicsBodyType.static:return this.rapier.RigidBodyDesc.fixed();case PhysicsBodyType.kinematic:return this.rapier.RigidBodyDesc.kinematicPositionBased();case PhysicsBodyType.kinematicVelocityBased:return this.rapier.RigidBodyDesc.kinematicVelocityBased();default:return this.rapier.RigidBodyDesc.dynamic()}})();e.position&&i.setTranslation(e.position.x,e.position.y,e.position.z),e.rotation&&i.setRotation({x:e.rotation.x,y:e.rotation.y,z:e.rotation.z,w:e.rotation.w}),"boolean"==typeof e.canSleep&&i.setCanSleep(e.canSleep),"boolean"==typeof e.ccdEnabled&&i.setCcdEnabled(e.ccdEnabled),"number"==typeof e.gravityScale&&i.setGravityScale(e.gravityScale),"number"==typeof e.mass&&i.setAdditionalMass(e.mass),void 0!==e.userData&&(i.userData=e.userData);const s=this.world.createRigidBody(i);return new PhysicsBody(s,this.world)}getCharacterComputedMovement(t,e,i,o=null){const n=t.collider;e.computeColliderMovement(n,i,s.EXCLUDE_SENSORS,o,ft);const r=e.computedMovement();return ut(mt,r),mt}setNextKinematicTranslation(t,e){const i=this.actorBodies.get(t.id),s=i.translation();s.x+=e.x,s.y+=e.y,s.z+=e.z,i?.setNextKinematicTranslation(s)}setNextKinematicPosition(t,e){this.actorBodies.get(t.id).setNextKinematicTranslation(e)}setNextKinematicRotation(t,e){this.actorBodies.get(t.id).setNextKinematicRotation(e)}setNextKinematicTransform(t){!function(t,e){const i=e.getWorldPosition(X),s=e.getWorldQuaternion(Y);t.setNextKinematicTranslation(rt(i)),t.setNextKinematicRotation(at(s))}(this.actorBodies.get(t.id),t.object)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);it.x=e.x,it.y=e.y,it.z=e.z,i?.setAngvel(it,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);it.x=e.x,it.y=e.y,it.z=e.z,i?.setLinvel(it,!0)}getLinearVelocity(t,e=new b){const i=this.actorBodies.get(t.id).linvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}getAngularVelocity(t,e=new b){const i=this.actorBodies.get(t.id).angvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}setLinearDamping(t,e){const i=this.actorBodies.get(t.id);i?.setLinearDamping(e)}getLienarDamping(t){const e=this.actorBodies.get(t.id);return e?.linearDamping()??0}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}getAngularDamping(t){const e=this.actorBodies.get(t.id);e?.angularDamping()}setPosition(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(rt(e),!1)}getPosition(t,e=new b){const i=this.actorBodies.get(t.id);i&&ut(e,i.translation())}setRotation(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(at(e),!1)}getRotation(t,e=new w){const i=this.actorBodies.get(t.id);i&&yt(e,i.rotation())}lockTranslations(t,e){const i=this.actorBodies.get(t.id);i?.lockTranslations(e,!1)}lockRotations(t,e){const i=this.actorBodies.get(t.id);i?.lockRotations(e,!1)}setEnabledTranslations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledTranslations(e,i,s,!1)}setEnabledRotations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledRotations(e,i,s,!1)}addLandscapeGroup(t){const e=t.userData.src,s=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new b);if(e.landscape.holes&&e.landscape.holes.some(t=>t.m===n.name&&0!==t.w[0])){const t=n.geometry.clone(),i=n.scale,s=n.geometry.getAttribute("hole"),r=new Float32Array(t.getAttribute("position").array);for(let t=0;t<r.length;t+=3)r[t]*=i.x,r[t+1]*=i.y,r[t+2]*=i.z;const a=t.index;for(let t=0;t<a.count;t+=3){const e=s.getX(a.getX(t)),i=s.getX(a.getY(t)),o=s.getX(a.getZ(t));(e>.5||i>.5||o>.5)&&(a.setX(t,0),a.setY(t,0),a.setZ(t,0))}const l=this.rapier.ColliderDesc.trimesh(r,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(this.rapier.RigidBodyDesc.fixed()),e=new this.rapier.Vector3(0,0,0);dt(e,o),t.setTranslation(e,!1),this.world.createCollider(l,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const l=s.find(t=>t.x===n.x&&t.y==n.y);if(null!=l)for(const e of l.points){if(null==a[e.i%t])continue;const i=t-1-Math.floor(e.i/t);i in a[e.i%t]?a[e.i%t][i]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:i,heightMap:l})}const c=e.landscape.options.density,d=a.flatMap(t=>t.reverse()),h=i.ColliderDesc.heightfield(c,c,new Float32Array(d),new this.rapier.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(this.rapier.RigidBodyDesc.fixed()),e=new this.rapier.Vector3(0,0,0);dt(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const i=this.actorBodies.get(t.id);i?.setEnabled(e)}addActor(t,e,i={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const s=t.object;let o;switch(i.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:o=this.rapier.RigidBodyDesc.dynamic(),o.mass=i.mass??1;break;case PhysicsBodyType.kinematic:o=this.rapier.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:o=this.rapier.RigidBodyDesc.kinematicVelocityBased();break;default:o=i.isTrigger?this.rapier.RigidBodyDesc.kinematicVelocityBased():this.rapier.RigidBodyDesc.fixed()}const n=this.world.createRigidBody(o);n.enableCcd(1==i.continousCollisionDetection);for(const t of e)this.addShape(n,t,s);return pt(n,t=>{null!=i.isTrigger&&(t.setSensor(i.isTrigger),t.setActiveCollisionTypes(this.rapier.ActiveCollisionTypes.ALL),t.setActiveEvents(this.rapier.ActiveEvents.COLLISION_EVENTS)),null!=i.friction&&t.setFriction(i.friction),null!=i.density&&t.setDensity(i.density),null!=i.mass&&t.setMass(i.mass),null!=i.restitution&&t.setRestitution(i.restitution)}),Z(n,s),!0===i.ignoreForNavMesh&&(n.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,n),this.bodyActors.set(n,t),new PhysicsBody(n,this.world)}applyTorque(t,e){const i=this.actorBodies.get(t.id);it.x=e.x,it.y=e.y,it.z=e.z,i?.addTorque(it,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);it.x=e.x,it.y=e.y,it.z=e.z,i?.applyTorqueImpulse(it,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const i=this.actorBodies.get(t.id);it.x=e.x,it.y=e.y,it.z=e.z,i?.addForce(it,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);it.x=e.x,it.y=e.y,it.z=e.z,i?.applyImpulse(it,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);dt(it,e),null==i?s?.addForce(it,!0):(dt(st,i),s?.addForceAtPoint(it,st,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);dt(it,e),null==i?s.applyImpulse(it,!0):(dt(st,i),s.applyImpulseAtPoint(it,st,!0))}applyRadiusImpulse(t,e,s){this.world.bodies.forEach(o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const n=ot;ut(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);it.x=a.x,it.y=a.y,it.z=a.z,o.applyImpulse(it,!0)})}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){if(null==t)return;const e=new Set;t.traverse(t=>{e.add(t.uuid)});for(const[t,i]of this.staticBodies.entries())e.has(t.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(i))}removeSceneObject(t){if(t instanceof j){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,i){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(({started:t})=>t===i),a(({handle1:t,handle2:e,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:i})),r(({a1:i,a2:s})=>null!=i&&null!=s&&i.id===t.id&&e(i,s)),a(({a2:t})=>t))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(t=>t.started),r(({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id}),a(t=>t.handle2))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(t=>!t.started),r(({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id}),a(t=>t.handle2))}onHasContactChanged(t){const e=new Set,i=new o(!1);return this.onBeginContact(t).subscribe(t=>{e.add(t),i.next(e.size>0)}),this.onEndContact(t).subscribe(t=>{e.delete(t),i.next(e.size>0)}),i.pipe(n())}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>i instanceof e,!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>i instanceof e,!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>e.id===i.id,!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>e.id===i.id,!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e&&Z(e,t.object)}flushModifiedBodyPositionsToColliders(){this.world.propagateModifiedBodyPositionsToColliders()}setupWorld(){const t=new this.rapier.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,i,s,o=ShapeCastResult.shared,n){o.reset();const r=this.getBallShape(e);this.shapeCacheBall.get;const a={x:t.x,y:t.y,z:t.z},l={x:i.x,y:i.y,z:i.z},c=n?.excludeActor?this.actorBodies.get(n.excludeActor.id):null,d=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n?.collisionFilter??void 0,null,c,n?.excludeTriggers?t=>!t.isSensor():void 0);if(null!=d){ut(o.hitPoint,d.witness1),o.normal.set(d.normal1.x,d.normal1.y,d.normal1.z),o.distance=d.time_of_impact,o.hasHit=!0;const t=d.collider.parent();if(t){const e=this.bodyActors.get(t);e&&(o.actor=e)}}return o}castActorShape(t,e,i,s=ShapeCastResult.shared,o=void 0){s.reset();const n=this.actorBodies.get(t.id);if(n&&n.numColliders()>0){for(let t=0;t<n.numColliders();t++){const r=n.collider(t);let a=r.shape,l=r.translation(),c=r.rotation(),d=e,h=i;const u=this.world.castShape(l,c,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=u){u.collider;const t=r;return ut(s.hitPoint,u.witness1),bt(t.rotation(),u.normal1,s.normal,H),s.distance=u.time_of_impact,s.actor=this.bodyActors.get(u.collider.parent()),s.hasHit=!0,s}}return s}return console.warn("Actor is not added to the physics system"),s}stop(){if(!this._isStopped){this._isStopped=!0,this.bodyActors.clear(),this.actorBodies.clear(),this.staticBodies.clear(),this.staticMeshes.clear(),this.colliders.clear(),this.fixedupdateSub?.unsubscribe(),this.collisionSub?.unsubscribe(),this.world?.bodies.forEach(t=>this.world.removeRigidBody(t));try{this.world?.free(),this.world=void 0}catch(t){console.warn("Error while freeing physics world",t)}Q.length=0}}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed();o.setSleeping(!0);const n=this.world.createRigidBody(o);let r=0;for(const i of e){if(r>128){console.warn("Too many collision shapes for object",t);break}if(r++,null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=o&&(null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution))}return Z(n,t),n.userData=t.uuid,n.sleep(),n}addShape(t=void 0,e,i){const s=i?.getWorldScale(wt)??et,o=this.createShape(e,s);if(null==o)return void console.error("Failed to create physics shape. This can happen if the geometry is degenerate or zero-scaled.",{shapeInfo:e,object:i});this.applyShapeSettings(o,e);const n=e.offset.clone().multiply(s);dt(o.translation,n);const r=(new w).setFromEuler(e.rotation);ht(o.rotation,r),null!=t&&t.numColliders()>128&&console.warn(`Rigid body has many colliders (${t.numColliders()}). Consider using a Trimesh if this is static geometry.`,t);try{return this.world.createCollider(o,t)}catch(t){return void console.error("Failed to create collider",t)}}applyShapeSettings(t,e){null!=e.collisionGroup&&t.setCollisionGroups(e.collisionGroup),t.friction=e.friction??.1,null!=e.restitution&&(t.restitution=e.restitution),null!=e.density&&(t.density=e.density,t.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(t.mass=e.mass,t.massPropsMode=i.MassPropsMode.Mass)}createShape(t,e){if(t instanceof D)return this.rapier.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof T){return this.rapier.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof V){const i=null!=t.geometry.getIndex()?t.geometry:v.mergeVertices(t.geometry),s=extractFloat32Array(i.getAttribute("position"));for(let t=0;t<s.length;t+=3)s[t]*=e.x,s[t+1]*=e.y,s[t+2]*=e.z;const o=i.getIndex();return null==o?(console.error("Trimesh collision shape is missing an index buffer.",t),null):this.rapier.ColliderDesc.trimesh(s,new Uint32Array(o.array))}if(t instanceof M){let i,s;t.mesh instanceof d.Mesh?i=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?i=t.mesh:console.log("Unknownd shape",{shapeInfo:t}),t.mesh instanceof d.Mesh&&(s=N(t.mesh));const o=`${i.uuid}|${s?.x??1},${s?.y??1},${s?.z??1}|${e.x},${e.y},${e.z}`,n=tt.get(o);if(void 0!==n)return n;const r=extractFloat32Array(i.getAttribute("position"));if(null!=s)for(let t=0;t<r.length;t+=3)r[t]*=s.x,r[t+1]*=s.y,r[t+2]*=s.z;for(let t=0;t<r.length;t+=3)r[t]*=e.x,r[t+1]*=e.y,r[t+2]*=e.z;const a=this.rapier.ColliderDesc.convexHull(r);return null==a&&console.error("Failed to compute convex hull. Points may be coplanar or too few.",{count:r.length/3}),tt.set(o,a),a}if(t instanceof F){const i=2*e.x-e.y-e.z;return Math.abs(i)>.01?this.createShape(new M(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):this.rapier.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof E?this.rapier.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof z?this.rapier.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof _?this.rapier.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),this.rapier.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new this.rapier.CharacterCollision}};$=t([C(),e("design:paramtypes",[])],$);export{$ as PhysicsSystem};const X=new b,Y=new d.Quaternion;function Z(t,e){const i=e.getWorldPosition(X),s=e.getWorldQuaternion(Y);t.setTranslation(rt(i),!1),t.setRotation(at(s),!1)}const J=new b,tt=new Map,et=new b(1,1,1),it=new i.Vector3(0,0,0),st=new i.Vector3(0,0,0),ot=new b,nt=new d.Vector2;function rt(t){return dt(it,t),it}function at(t){return ht(H,t),H}let lt=null;const ct=async()=>(null==lt&&(lt=(async()=>{let t=await import("@dimforge/rapier3d-simd-compat");return await t.init(),t})()),lt);function dt(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function ht(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function ut(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function yt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function pt(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const gt=new b,mt=new b,ft=t=>!t.isSensor(),wt=new b;let xt,Bt=class extends S{constructor(){super(...arguments),this._active=!0,this.physics=R($),this.world=R(L)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};Bt=t([A()],Bt);export function extractFloat32Array(t){const e=t.itemSize,i=t.count,s=new Float32Array(i*e);for(let o=0;o<i;o++)for(let i=0;i<e;i++)s[o*e+i]=t.getComponent(o,i);return s}function bt(t,e,i,s){return s.set(t.x,t.y,t.z,t.w),i.set(e.x,e.y,e.z),i.applyQuaternion(s),i}export class PhysicsCollider{constructor(t,e){this.collider=t,this.world=e,this.disposed=new l,this.onBeginOverlapActor=new l,this.onEndOverlapActor=new l}dispose(){this.world.removeCollider(this.collider,!1),this.disposed.next(!0),this.disposed.complete(),this.onBeginOverlapActor.complete(),this.onEndOverlapActor.complete()}set mass(t){this.collider.setMass(t)}get mass(){return this.collider.mass()}set friction(t){this.collider.setFriction(t)}get friction(){return this.collider.friction()}set restitution(t){this.collider.setRestitution(t)}get restitution(){return this.collider.restitution()}set density(t){this.collider.setDensity(t)}get density(){return this.collider.density()}set isTrigger(t){this.collider.setSensor(t)}get isTrigger(){return this.collider.isSensor()}set collisionGroups(t){this.collider.setCollisionGroups(t)}get collisionGroups(){return this.collider.collisionGroups()}set enabled(t){this.collider.setEnabled(t)}get enabled(){return this.collider.isEnabled()}}export class PhysicsBody{constructor(t,e){this.body=t,this.world=e}dispose(){this.world.removeRigidBody(this.body)}setEnabled(t){this.body.setEnabled(t)}isEnabled(){return this.body.isEnabled()}getPosition(t){const e=this.body.translation();return t.set(e.x,e.y,e.z),t}setPosition(t){this.body.setTranslation({x:t.x,y:t.y,z:t.z},!0)}getRotation(t){const e=this.body.rotation();return t.set(e.x,e.y,e.z,e.w),t}setRotation(t){this.body.setRotation({x:t.x,y:t.y,z:t.z,w:t.w},!0)}getLinearVelocity(t){const e=this.body.linvel();return t.set(e.x,e.y,e.z),t}setLinearVelocity(t){this.body.setLinvel({x:t.x,y:t.y,z:t.z},!0)}getAngularVelocity(t){const e=this.body.angvel();return t.set(e.x,e.y,e.z),t}setAngularVelocity(t){this.body.setAngvel({x:t.x,y:t.y,z:t.z},!0)}applyImpulse(t,e=!0){this.body.applyImpulse({x:t.x,y:t.y,z:t.z},e)}applyTorqueImpulse(t,e=!0){this.body.applyTorqueImpulse({x:t.x,y:t.y,z:t.z},e)}setNextKinematicPosition(t){this.body.setNextKinematicTranslation(t)}setNextKinematicRotation(t){this.body.setNextKinematicRotation(t)}setType(t){this.body.setBodyType(function(t){switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyType.Dynamic;case PhysicsBodyType.static:return i.RigidBodyType.Fixed;case PhysicsBodyType.kinematic:return i.RigidBodyType.KinematicPositionBased;case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyType.KinematicVelocityBased}}(t),t!==PhysicsBodyType.static)}setGravityScale(t){this.body.setGravityScale(t,!1)}getGravityScale(){return this.body.gravityScale()}isDynamic(){return this.body.isDynamic()}isKinematic(){return this.body.isKinematic()}isStatic(){return this.body.isFixed()}sleep(){this.body.sleep()}wakeUp(){this.body.wakeUp()}}/*
1
+ import{__decorate as t,__metadata as e}from"tslib";import*as i from"@dimforge/rapier3d-simd-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-simd-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as l,takeUntil as c}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as p,Group as y,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as x,Scene as b,Vector3 as B}from"three";import*as v from"three/examples/jsm/utils/BufferGeometryUtils.js";import{Service as C}from"typedi";import{ActorComponent as S,Component as A}from"../../../gameplay/actors/component.js";import{inject as R}from"../../../gameplay/inject.js";import{BoxCollisionShape as z,CapsuleCollisionShape as D,ConeCollisionShape as T,ConvexPolyhedronCollisionShape as M,CylinderCollisionShape as E,PhysicalShapeMesh as P,PlaneCollisionShape as _,SphereCollisionShape as F,toInstancedCollisionShape as W,TrimeshCollisionShape as I}from"../../../index.js";import{AssetMeshInstance as j}from"../../../scene/asset-resource-loader.js";import{LandscapeGroup as V}from"../../../scene/landscape/landscape.js";import{calculateEffectiveScale as k}from"../../../utils/three/traverse.js";import{ViewController as N}from"../render.js";import{World as L}from"../world.js";import{AbstractPhysicsSystem as O}from"./abstract-physics-system.js";import{NetRole as G}from"../../net/index.js";export{ActorComponent,attach,Attach,Component}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new B,this.hitNormal=new B}}export class ShapeCastResult{constructor(){this.hasHit=!1,this.hitPoint=new B,this.normal=new B}reset(){this.actor=void 0,this.hasHit=!1,this.distance=0,this.hitPoint.set(0,0,0),this.normal.set(0,0,0)}}ShapeCastResult.shared=new ShapeCastResult;export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));const K=new B,U=new B,H=new w,q=new w,Q=new w,X=[];let $=class extends O{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(){super(),this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.colliders=new Map,this.collisionEvents=new l,this.beforeStep=new l,this.afterStep=new l,this.shouldRenderDebug=!1,this.viewController=R(N),this.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new x,this._reusableResult=new RayTestResult,this._raytestDiff=new B,this._raytestDirection=new B,this.controlledActors=new Set,this._isStopped=!1,this.ready=this.setup()}getBallShape(t){let e=this.shapeCacheBall.get(t);return null==e&&(e=new this.rapier.Ball(t),this.shapeCacheBall.set(t,e)),e}getBoxShape(t,e,i){const s=t+1e6*e+1e12*i;let o=this.shapeCacheBox.get(s);return null==o&&(o=new this.rapier.Cuboid(t,e,i),this.shapeCacheBox.set(s,o)),o}hasBoxIntersection(t){const e=t.getCenter(K),i=t.getSize(U),s=this.getBoxShape(i.x/2,i.y/2,i.z/2);return null!=this.world.intersectionWithShape(e,H,s)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,H,e)}findActorsInRadius(t,e,i){const s=this.getBallShape(e),o=[];for(const[e,n]of this.bodyActors)if(n instanceof i||null==i)for(let i=0,r=e.numColliders();i<r;i++){e.collider(i).intersectsShape(s,t,H)&&o.push(n)}return o}createDebugMesh(){return new g(new p,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.handleCollisionEvents(),this.ready}handleCollisionEvents(){this.collisionSub=this.collisionEvents.subscribe(t=>{const e=this.colliders.get(t.handle1);if(null==e)return;const i=this.world.getCollider(t.handle2);if(null==i||null==i.parent())return;const s=this.bodyActors.get(i.parent());null!=s&&(t.started?e.onBeginOverlapActor.next({actor:s}):e.onEndOverlapActor.next({actor:s}))})}renderDebug(){if(null==this.scene)return;null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.scene?.add(this.debugMesh));const t=this.world.debugRender().vertices,e=this.debugMesh.geometry,i=e.getAttribute("position");null==i||(i.array.length,t.length);{const i=new u(t,3);i.setUsage(d.DynamicDrawUsage),e.setAttribute("position",i)}e.setDrawRange(0,t.length/3)}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await dt(),this.eventQueue=new this.rapier.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe(t=>{this._isStopped||(t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach(t=>{if(t.isFixed())return;let e,i=this.staticMeshes.get(t);if(null==i&&(e=this.bodyActors.get(t),null!=e)){if(e.netRole===G.simulatedProxy)return;i=e.object}null!=i&&i.parent instanceof b&&(pt(i.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&yt(i.quaternion,t.rotation()),i.matrixWorldNeedsUpdate=!0)}),this.afterStep.next(t))})}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this._isStopped||(this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents((t,e,i)=>{this.collisionEvents.next({handle1:t,handle2:e,started:i}),this.collisionEvents.next({handle1:e,handle2:t,started:i})}))}rayTestFromCamera(t,e,i){this._raycaster.setFromCamera(rt,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(s);return this.rayTest(s,o,e,i)}rayTest(t,e,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),i;null==bt&&(bt=new this.rapier.Ray(new this.rapier.Vector3(0,0,0),new this.rapier.Vector3(0,1,0))),ht(bt.origin,t),ht(bt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(bt,r,!1,void 0,s?.collisionFilter,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?t=>!t.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const e=bt.pointAt(a.timeOfImpact);if(i._internal=a,pt(i.hitNormal,a.normal),pt(i.hitPoint,e),i.distance=mt.subVectors(i.hitPoint,t).length(),!1!==s?.resolveActor){const t=this.world.bodies.getAll().find(t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,t=>t===a.collider));i.actor=null!=t?this.bodyActors.get(t):null}}if(this.showDebug){let e;X.length>0?(e=X.pop(),e.setDirection(n),e.position.copy(t),e.setLength(r,.2,.1),e.setColor(s?.debugColor??255)):e=new h(n,t,r,s?.debugColor??255),this.scene?.add(e),setTimeout(()=>{this.scene?.remove(e),X.push(e)},s?.debugLifetime??200)}return i}setGravity(t,e,i){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=i}getGravity(){return tt.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())gt(t,t=>t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof P&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof j){const e=!1!==t.userData?.src?.collisionDetection;if(t.children[0]&&(t.children[0].instanceMatrix&&e||t.children[0].isBatchedMesh))this.createForInstancedMesh(t.children[0],t.collisionShapes);else if(e&&t.children.length>0){const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}}else t instanceof V?this.addLandscapeGroup(t):(t instanceof y||t instanceof b)&&t.children.forEach(t=>this.addRecursively(t))}createForInstancedMesh(t,e){const i=new m;if(t instanceof d.BatchedMesh){const e=t._instanceInfo??t._drawInfo,s=new Map;for(let o=0;o<e.length;o++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[o])continue;const e=t.userData.collisionShapes;let n=e?.[o];if(null==n&&null==e&&t.parent instanceof j&&(n=t.parent.collisionShapes),null==n)continue;let r=s.get(n);null==r&&(r=this.instancedShapeReset(n),s.set(n,r));const a=new f;a.matrix.identity(),t.getMatrixAt(o,i),a.applyMatrix4(i);this.createStaticBody(a,r)}}else{const s=this.instancedShapeReset(e);for(let e=0;e<t.count;e++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[e])continue;const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*e),o.applyMatrix4(i);this.createStaticBody(o,s)}}}instancedShapeReset(t){return t.filter(t=>null!=t).map(t=>W(t))}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,i,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,o,wt);const a=e.computedMovement();return pt(ft,a),ft}setActorCapsuleCollider(t,e,i,s){const o=this.actorBodies.get(t.id),n=o?.collider(0);if(null==o||null==n)return!1;const r=t.object?.getWorldScale(xt)??it,a=Math.max(0,e*Math.abs(r.y)),l=Math.max(.001,i*Math.max(Math.abs(r.x),Math.abs(r.z)));return n.setHalfHeight(a/2),n.setRadius(l),nt.set(0,s,0).multiply(r),ht(st,nt),n.setTranslationWrtParent(st),o.recomputeMassPropertiesFromColliders(),!0}hasActorCapsuleIntersection(t,e,i,o,n,r=null){const a=this.actorBodies.get(t.id),l=t.object?.getWorldScale(xt)??it,c=Math.max(0,i*Math.abs(l.y)),d=Math.max(.001,o*Math.max(Math.abs(l.x),Math.abs(l.z))),h=new this.rapier.Capsule(c/2,d),u=t.object?.getWorldQuaternion(Q)??H;nt.set(0,n,0).multiply(l).applyQuaternion(u).add(e);return null!=this.world.intersectionWithShape(nt,u,h,s.EXCLUDE_SENSORS,r??void 0,void 0,a,wt)}createCollider(t,e){const i=this.addShape(e?.body,t),s=new PhysicsCollider(i,this.world);return this.colliders.set(i.handle,s),s.disposed.subscribe(()=>{this.colliders.delete(i.handle)}),s}createBody(t=PhysicsBodyType.dynamic,e={}){const i=(()=>{switch(t){case PhysicsBodyType.dynamic:return this.rapier.RigidBodyDesc.dynamic();case PhysicsBodyType.static:return this.rapier.RigidBodyDesc.fixed();case PhysicsBodyType.kinematic:return this.rapier.RigidBodyDesc.kinematicPositionBased();case PhysicsBodyType.kinematicVelocityBased:return this.rapier.RigidBodyDesc.kinematicVelocityBased();default:return this.rapier.RigidBodyDesc.dynamic()}})();e.position&&i.setTranslation(e.position.x,e.position.y,e.position.z),e.rotation&&i.setRotation({x:e.rotation.x,y:e.rotation.y,z:e.rotation.z,w:e.rotation.w}),"boolean"==typeof e.canSleep&&i.setCanSleep(e.canSleep),"boolean"==typeof e.ccdEnabled&&i.setCcdEnabled(e.ccdEnabled),"number"==typeof e.gravityScale&&i.setGravityScale(e.gravityScale),"number"==typeof e.mass&&i.setAdditionalMass(e.mass),void 0!==e.userData&&(i.userData=e.userData);const s=this.world.createRigidBody(i);return new PhysicsBody(s,this.world)}getCharacterComputedMovement(t,e,i,o=null){const n=t.collider;e.computeColliderMovement(n,i,s.EXCLUDE_SENSORS,o,wt);const r=e.computedMovement();return pt(ft,r),ft}setNextKinematicTranslation(t,e){const i=this.actorBodies.get(t.id),s=i.translation();s.x+=e.x,s.y+=e.y,s.z+=e.z,i?.setNextKinematicTranslation(s)}setNextKinematicPosition(t,e){this.actorBodies.get(t.id).setNextKinematicTranslation(e)}setNextKinematicRotation(t,e){this.actorBodies.get(t.id).setNextKinematicRotation(e)}setNextKinematicTransform(t){!function(t,e){const i=e.getWorldPosition(Y),s=e.getWorldQuaternion(Z);t.setNextKinematicTranslation(at(i)),t.setNextKinematicRotation(lt(s))}(this.actorBodies.get(t.id),t.object)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);st.x=e.x,st.y=e.y,st.z=e.z,i?.setAngvel(st,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);st.x=e.x,st.y=e.y,st.z=e.z,i?.setLinvel(st,!0)}getLinearVelocity(t,e=new B){const i=this.actorBodies.get(t.id).linvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}getAngularVelocity(t,e=new B){const i=this.actorBodies.get(t.id).angvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}setLinearDamping(t,e){const i=this.actorBodies.get(t.id);i?.setLinearDamping(e)}getLienarDamping(t){const e=this.actorBodies.get(t.id);return e?.linearDamping()??0}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}getAngularDamping(t){const e=this.actorBodies.get(t.id);e?.angularDamping()}setPosition(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(at(e),!1)}getPosition(t,e=new B){const i=this.actorBodies.get(t.id);i&&pt(e,i.translation())}setRotation(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(lt(e),!1)}getRotation(t,e=new w){const i=this.actorBodies.get(t.id);i&&yt(e,i.rotation())}lockTranslations(t,e){const i=this.actorBodies.get(t.id);i?.lockTranslations(e,!1)}lockRotations(t,e){const i=this.actorBodies.get(t.id);i?.lockRotations(e,!1)}setEnabledTranslations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledTranslations(e,i,s,!1)}setEnabledRotations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledRotations(e,i,s,!1)}addLandscapeGroup(t){const e=t.userData.src,s=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new B);if(e.landscape.holes&&e.landscape.holes.some(t=>t.m===n.name&&0!==t.w[0])){const t=n.geometry.clone(),i=n.scale,s=n.geometry.getAttribute("hole"),r=new Float32Array(t.getAttribute("position").array);for(let t=0;t<r.length;t+=3)r[t]*=i.x,r[t+1]*=i.y,r[t+2]*=i.z;const a=t.index;for(let t=0;t<a.count;t+=3){const e=s.getX(a.getX(t)),i=s.getX(a.getY(t)),o=s.getX(a.getZ(t));(e>.5||i>.5||o>.5)&&(a.setX(t,0),a.setY(t,0),a.setZ(t,0))}const l=this.rapier.ColliderDesc.trimesh(r,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(this.rapier.RigidBodyDesc.fixed()),e=new this.rapier.Vector3(0,0,0);ht(e,o),t.setTranslation(e,!1),this.world.createCollider(l,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const l=s.find(t=>t.x===n.x&&t.y==n.y);if(null!=l)for(const e of l.points){if(null==a[e.i%t])continue;const i=t-1-Math.floor(e.i/t);i in a[e.i%t]?a[e.i%t][i]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:i,heightMap:l})}const c=e.landscape.options.density,d=a.flatMap(t=>t.reverse()),h=i.ColliderDesc.heightfield(c,c,new Float32Array(d),new this.rapier.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(this.rapier.RigidBodyDesc.fixed()),e=new this.rapier.Vector3(0,0,0);ht(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const i=this.actorBodies.get(t.id);i?.setEnabled(e)}addActor(t,e,i={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const s=t.object;let o;switch(i.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:o=this.rapier.RigidBodyDesc.dynamic(),o.mass=i.mass??1;break;case PhysicsBodyType.kinematic:o=this.rapier.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:o=this.rapier.RigidBodyDesc.kinematicVelocityBased();break;default:o=i.isTrigger?this.rapier.RigidBodyDesc.kinematicVelocityBased():this.rapier.RigidBodyDesc.fixed()}const n=this.world.createRigidBody(o);n.enableCcd(1==i.continousCollisionDetection);for(const t of e)this.addShape(n,t,s);return gt(n,t=>{null!=i.isTrigger&&(t.setSensor(i.isTrigger),t.setActiveCollisionTypes(this.rapier.ActiveCollisionTypes.ALL),t.setActiveEvents(this.rapier.ActiveEvents.COLLISION_EVENTS)),null!=i.friction&&t.setFriction(i.friction),null!=i.density&&t.setDensity(i.density),null!=i.mass&&t.setMass(i.mass),null!=i.restitution&&t.setRestitution(i.restitution)}),J(n,s),!0===i.ignoreForNavMesh&&(n.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,n),this.bodyActors.set(n,t),new PhysicsBody(n,this.world)}applyTorque(t,e){const i=this.actorBodies.get(t.id);st.x=e.x,st.y=e.y,st.z=e.z,i?.addTorque(st,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);st.x=e.x,st.y=e.y,st.z=e.z,i?.applyTorqueImpulse(st,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const i=this.actorBodies.get(t.id);st.x=e.x,st.y=e.y,st.z=e.z,i?.addForce(st,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);st.x=e.x,st.y=e.y,st.z=e.z,i?.applyImpulse(st,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);ht(st,e),null==i?s?.addForce(st,!0):(ht(ot,i),s?.addForceAtPoint(st,ot,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);ht(st,e),null==i?s.applyImpulse(st,!0):(ht(ot,i),s.applyImpulseAtPoint(st,ot,!0))}applyRadiusImpulse(t,e,s){this.world.bodies.forEach(o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const n=nt;pt(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);st.x=a.x,st.y=a.y,st.z=a.z,o.applyImpulse(st,!0)})}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){if(null==t)return;const e=new Set;t.traverse(t=>{e.add(t.uuid)});for(const[t,i]of this.staticBodies.entries())e.has(t.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(i))}removeSceneObject(t){if(t instanceof V){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,i){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(({started:t})=>t===i),a(({handle1:t,handle2:e,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:i})),r(({a1:i,a2:s})=>null!=i&&null!=s&&i.id===t.id&&e(i,s)),a(({a2:t})=>t))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(t=>t.started),r(({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id}),a(t=>t.handle2))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(t=>!t.started),r(({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id}),a(t=>t.handle2))}onHasContactChanged(t){const e=new Set,i=new o(!1);return this.onBeginContact(t).subscribe(t=>{e.add(t),i.next(e.size>0)}),this.onEndContact(t).subscribe(t=>{e.delete(t),i.next(e.size>0)}),i.pipe(n())}onBeginOverlap(t){return this._onCollisionWithActorEvent(t,()=>!0,!0)}onEndOverlap(t){return this._onCollisionWithActorEvent(t,()=>!0,!1)}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>i instanceof e,!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>i instanceof e,!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>e.id===i.id,!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>e.id===i.id,!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e&&J(e,t.object)}flushModifiedBodyPositionsToColliders(){this.world.propagateModifiedBodyPositionsToColliders()}setupWorld(){const t=new this.rapier.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,i,s,o=ShapeCastResult.shared,n){o.reset();const r=this.getBallShape(e);this.shapeCacheBall.get;const a={x:t.x,y:t.y,z:t.z},l={x:i.x,y:i.y,z:i.z},c=n?.excludeActor?this.actorBodies.get(n.excludeActor.id):null,d=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n?.collisionFilter??void 0,null,c,n?.excludeTriggers?t=>!t.isSensor():void 0);if(null!=d){pt(o.hitPoint,d.witness1),o.normal.set(d.normal1.x,d.normal1.y,d.normal1.z),o.distance=d.time_of_impact,o.hasHit=!0;const t=d.collider.parent();if(t){const e=this.bodyActors.get(t);e&&(o.actor=e)}}return o}castActorShape(t,e,i,s=ShapeCastResult.shared,o=void 0){s.reset();const n=this.actorBodies.get(t.id);if(n&&n.numColliders()>0){for(let t=0;t<n.numColliders();t++){const r=n.collider(t);let a=r.shape,l=r.translation(),c=r.rotation(),d=e,h=i;const u=this.world.castShape(l,c,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=u){u.collider;const t=r;return pt(s.hitPoint,u.witness1),vt(t.rotation(),u.normal1,s.normal,q),s.distance=u.time_of_impact,s.actor=this.bodyActors.get(u.collider.parent()),s.hasHit=!0,s}}return s}return console.warn("Actor is not added to the physics system"),s}stop(){if(!this._isStopped){this._isStopped=!0,this.bodyActors.clear(),this.actorBodies.clear(),this.staticBodies.clear(),this.staticMeshes.clear(),this.colliders.clear(),this.fixedupdateSub?.unsubscribe(),this.collisionSub?.unsubscribe(),this.world?.bodies.forEach(t=>this.world.removeRigidBody(t));try{this.world?.free(),this.world=void 0}catch(t){console.warn("Error while freeing physics world",t)}X.length=0}}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed();o.setSleeping(!0);const n=this.world.createRigidBody(o);let r=0;for(const i of e){if(r>128){console.warn("Too many collision shapes for object",t);break}if(r++,null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=o&&(null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution))}return J(n,t),n.userData=t.uuid,n.sleep(),n}addShape(t=void 0,e,i){const s=i?.getWorldScale(xt)??it,o=this.createShape(e,s);if(null==o)return void console.error("Failed to create physics shape. This can happen if the geometry is degenerate or zero-scaled.",{shapeInfo:e,object:i});this.applyShapeSettings(o,e);const n=e.offset.clone().multiply(s);ht(o.translation,n);const r=(new w).setFromEuler(e.rotation);ut(o.rotation,r),null!=t&&t.numColliders()>128&&console.warn(`Rigid body has many colliders (${t.numColliders()}). Consider using a Trimesh if this is static geometry.`,t);try{return this.world.createCollider(o,t)}catch(t){return void console.error("Failed to create collider",t)}}applyShapeSettings(t,e){null!=e.collisionGroup&&t.setCollisionGroups(e.collisionGroup),t.friction=e.friction??.1,null!=e.restitution&&(t.restitution=e.restitution),null!=e.density&&(t.density=e.density,t.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(t.mass=e.mass,t.massPropsMode=i.MassPropsMode.Mass)}createShape(t,e){if(t instanceof z)return this.rapier.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof D){return this.rapier.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof I){const i=null!=t.geometry.getIndex()?t.geometry:v.mergeVertices(t.geometry),s=extractFloat32Array(i.getAttribute("position"));for(let t=0;t<s.length;t+=3)s[t]*=e.x,s[t+1]*=e.y,s[t+2]*=e.z;const o=i.getIndex();return null==o?(console.error("Trimesh collision shape is missing an index buffer.",t),null):this.rapier.ColliderDesc.trimesh(s,new Uint32Array(o.array))}if(t instanceof M){let i,s;t.mesh instanceof d.Mesh?i=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?i=t.mesh:console.log("Unknownd shape",{shapeInfo:t}),t.mesh instanceof d.Mesh&&(s=k(t.mesh));const o=`${i.uuid}|${s?.x??1},${s?.y??1},${s?.z??1}|${e.x},${e.y},${e.z}`,n=et.get(o);if(void 0!==n)return n;const r=extractFloat32Array(i.getAttribute("position"));if(null!=s)for(let t=0;t<r.length;t+=3)r[t]*=s.x,r[t+1]*=s.y,r[t+2]*=s.z;for(let t=0;t<r.length;t+=3)r[t]*=e.x,r[t+1]*=e.y,r[t+2]*=e.z;const a=this.rapier.ColliderDesc.convexHull(r);return null==a&&console.error("Failed to compute convex hull. Points may be coplanar or too few.",{count:r.length/3}),et.set(o,a),a}if(t instanceof F){const i=2*e.x-e.y-e.z;return Math.abs(i)>.01?this.createShape(new M(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new B(1,1,1)):this.rapier.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof E?this.rapier.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof T?this.rapier.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof _?this.rapier.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),this.rapier.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new this.rapier.CharacterCollision}};$=t([C(),e("design:paramtypes",[])],$);export{$ as PhysicsSystem};const Y=new B,Z=new d.Quaternion;function J(t,e){const i=e.getWorldPosition(Y),s=e.getWorldQuaternion(Z);t.setTranslation(at(i),!1),t.setRotation(lt(s),!1)}const tt=new B,et=new Map,it=new B(1,1,1),st=new i.Vector3(0,0,0),ot=new i.Vector3(0,0,0),nt=new B,rt=new d.Vector2;function at(t){return ht(st,t),st}function lt(t){return ut(q,t),q}let ct=null;const dt=async()=>(null==ct&&(ct=(async()=>{let t=await import("@dimforge/rapier3d-simd-compat");return await t.init(),t})()),ct);function ht(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function ut(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function pt(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function yt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function gt(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const mt=new B,ft=new B,wt=t=>!t.isSensor(),xt=new B;let bt,Bt=class extends S{constructor(){super(...arguments),this._active=!0,this.physics=R($),this.world=R(L)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};Bt=t([A()],Bt);export function extractFloat32Array(t){const e=t.itemSize,i=t.count,s=new Float32Array(i*e);for(let o=0;o<i;o++)for(let i=0;i<e;i++)s[o*e+i]=t.getComponent(o,i);return s}function vt(t,e,i,s){return s.set(t.x,t.y,t.z,t.w),i.set(e.x,e.y,e.z),i.applyQuaternion(s),i}export class PhysicsCollider{constructor(t,e){this.collider=t,this.world=e,this.disposed=new l,this.onBeginOverlapActor=new l,this.onEndOverlapActor=new l}dispose(){this.world.removeCollider(this.collider,!1),this.disposed.next(!0),this.disposed.complete(),this.onBeginOverlapActor.complete(),this.onEndOverlapActor.complete()}set mass(t){this.collider.setMass(t)}get mass(){return this.collider.mass()}set friction(t){this.collider.setFriction(t)}get friction(){return this.collider.friction()}set restitution(t){this.collider.setRestitution(t)}get restitution(){return this.collider.restitution()}set density(t){this.collider.setDensity(t)}get density(){return this.collider.density()}set isTrigger(t){this.collider.setSensor(t)}get isTrigger(){return this.collider.isSensor()}set collisionGroups(t){this.collider.setCollisionGroups(t)}get collisionGroups(){return this.collider.collisionGroups()}set enabled(t){this.collider.setEnabled(t)}get enabled(){return this.collider.isEnabled()}}export class PhysicsBody{constructor(t,e){this.body=t,this.world=e}dispose(){this.world.removeRigidBody(this.body)}setEnabled(t){this.body.setEnabled(t)}isEnabled(){return this.body.isEnabled()}getPosition(t){const e=this.body.translation();return t.set(e.x,e.y,e.z),t}setPosition(t){this.body.setTranslation({x:t.x,y:t.y,z:t.z},!0)}getRotation(t){const e=this.body.rotation();return t.set(e.x,e.y,e.z,e.w),t}setRotation(t){this.body.setRotation({x:t.x,y:t.y,z:t.z,w:t.w},!0)}getLinearVelocity(t){const e=this.body.linvel();return t.set(e.x,e.y,e.z),t}setLinearVelocity(t){this.body.setLinvel({x:t.x,y:t.y,z:t.z},!0)}getAngularVelocity(t){const e=this.body.angvel();return t.set(e.x,e.y,e.z),t}setAngularVelocity(t){this.body.setAngvel({x:t.x,y:t.y,z:t.z},!0)}applyImpulse(t,e=!0){this.body.applyImpulse({x:t.x,y:t.y,z:t.z},e)}applyTorqueImpulse(t,e=!0){this.body.applyTorqueImpulse({x:t.x,y:t.y,z:t.z},e)}setNextKinematicPosition(t){this.body.setNextKinematicTranslation(t)}setNextKinematicRotation(t){this.body.setNextKinematicRotation(t)}setType(t){this.body.setBodyType(function(t){switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyType.Dynamic;case PhysicsBodyType.static:return i.RigidBodyType.Fixed;case PhysicsBodyType.kinematic:return i.RigidBodyType.KinematicPositionBased;case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyType.KinematicVelocityBased}}(t),t!==PhysicsBodyType.static)}setGravityScale(t){this.body.setGravityScale(t,!1)}getGravityScale(){return this.body.gravityScale()}isDynamic(){return this.body.isDynamic()}isKinematic(){return this.body.isKinematic()}isStatic(){return this.body.isFixed()}sleep(){this.body.sleep()}wakeUp(){this.body.wakeUp()}}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -4,6 +4,7 @@ import { Euler, Scene, Vector3 } from 'three';
4
4
  import { Observable } from 'rxjs';
5
5
  import { RenderingView } from "../../rendering.js";
6
6
  import { Prefab } from "../../scene/objects/prefab.js";
7
+ import type { SceneMaterializer } from "../../scene/materializer.js";
7
8
  import { PrefabInstance } from '../../scene/objects/prefab';
8
9
  import { BasePlayerController } from "../actors/controller/actor-controller.js";
9
10
  declare class DirectionalLightController {
@@ -29,12 +30,17 @@ export type ActorSpawnOptions = {
29
30
  export declare class World {
30
31
  private actorFactory;
31
32
  private view;
33
+ private viewController;
32
34
  private physics;
35
+ private assetsProvider;
36
+ private eventGraphAssets;
33
37
  readonly actors: BaseActor[];
34
38
  readonly actorAdded: Observable<BaseActor>;
35
39
  readonly actorRemoved: Observable<BaseActor>;
36
40
  scene: Scene;
37
41
  readonly directionalLight: DirectionalLightController;
42
+ private readonly sceneEventGraphs;
43
+ private readonly sceneEventGraphSubscriptions;
38
44
  spawnActor<T extends BaseActor>(type: Constructable<T>, position?: Vector3, rotation?: Euler, options?: ActorSpawnOptions): Promise<T>;
39
45
  /**
40
46
  * Spawn the player controller to run locally.
@@ -47,6 +53,12 @@ export declare class World {
47
53
  removeActor(actor: BaseActor): void;
48
54
  findActorByType<T extends BaseActor>(type: Constructable<T>, name?: string): T;
49
55
  findActorsByType<T extends BaseActor>(type: Constructable<T>, name?: string): T[];
56
+ /** Starts event graphs owned by prefabs that were materialized with the scene. */
57
+ startSceneEventGraphs(materializer: SceneMaterializer): Promise<void>;
58
+ /** Stops scene-owned graphs before their actors or materializer are disposed. */
59
+ stopSceneEventGraphs(): void;
60
+ private activateSceneEventGraph;
61
+ private deactivateSceneEventGraph;
50
62
  spawnPrefab(prefab: Prefab, position?: Vector3, rotation?: Euler): Promise<PrefabInstance>;
51
63
  removePrefab(instance: PrefabInstance): void;
52
64
  }
@@ -1,4 +1,4 @@
1
- import{__decorate as t}from"tslib";import{Service as r}from"typedi";import{BaseActor as o}from"../actors/actor.js";import{ActorFactory as e}from"../actors/factory.js";import{Group as i,Vector3 as n}from"three";import{ActorComponent as s}from"../../gameplay/actors/component.js";import{Subject as c}from"rxjs";import{RenderingView as a}from"../../rendering.js";import{randomUUID as h}from"../../utils/uuid";import{PrefabInstance as l}from"../../scene/objects/prefab";import{PhysicsSystem as m}from"./physics/physics-system.js";import{inject as p}from"../../gameplay/inject.js";import{isComponentEnabledInEnvironment as d}from"../actors/internal/component-init.js";import{NetRole as f}from"../net/service/net-actor-role.js";import{BasePlayerController as y}from"../actors/controller/actor-controller.js";const w=new n;class u{constructor(t){this.view=t}get direction(){return this.view.csm.lightDirection}set intensity(t){this.view.csm.lightIntensity=t,this.view.csm.lights.forEach(t=>t.intensity=this.view.csm.lightIntensity)}get intensity(){return this.view.csm.lightIntensity}get position(){return 0==this.view.csm.lights.length?w:this.view.csm.lights[0].position}}let b=class{constructor(){this.actorFactory=p(e),this.view=p(a),this.physics=p(m),this.actors=[],this.actorAdded=new c,this.actorRemoved=new c,this.directionalLight=new u(this.view)}async spawnActor(t,r,o,e){if(null==t)throw new Error("Cannot spawn actor with null type");if("prefab"in t){const i=t.prefab,n=await this.spawnPrefab(i,r,o),s=n.mainActor;if(null==s)throw new Error(`Prefab has no main actor or there was an error when spwaning it. Prefab: ${JSON.stringify(i)}`);return s.disposed.subscribe(()=>{const t=n.actors.findIndex(t=>t===s);t>=0&&n.actors.splice(t,1),this.removePrefab(n)}),null!=e?.owner&&(s.owner=e.owner),s}const i=await this.actorFactory.create(t,r,o);return null!=e?.owner&&(i.owner=e.owner),this.addActor(i,r,o),i}async spawnActorWithNetInfo(t,r,o,e,i,n){const s=await this.actorFactory.create(t,i,n,!0),c=null!=e&&0!==e?this.actors.find(t=>t.__netid===e):null;return s.__netid=r,s.netRole=o,s.owner=c,s instanceof y&&(s.isLocallyControlled=o===f.autonomousProxy),this.actorFactory.initActor(s),this.addActor(s,i,n),s}async spawnLocalPlayerController(t,r,o){const e=await this.actorFactory.create(t,r,o,!0);return e.isLocallyControlled=!0,this.actorFactory.initActor(e),this.addActor(e,r,o),e}spawnActorSync(t,r,o){if(null==t)throw new Error("Cannot spawn actor with null type");const e=this.actorFactory.createSync(t,r,o);return this.addActor(e,r,o),e}addActor(t,r,o){r&&t.object.position.copy(r),o&&t.object.rotation.copy(o),null==t.object.parent&&this.scene.add(t.object),this.actors.push(t),j(t,t=>t.onBeginPlay(),this.actorFactory.inEditor),this.actorAdded.next(t)}removeActor(t){j(t,t=>t.onEndPlay(),this.actorFactory.inEditor);const r=this.actors.indexOf(t);r>=0&&this.actors.splice(r,1),t.object.removeFromParent(),t.disposed.next(!0),this.actorRemoved.next(t),this.physics.removeActor(t)}findActorByType(t,r){return this.actors.find(o=>o instanceof t&&(null==r||o.object.name==r))}findActorsByType(t,r){return this.actors.filter(o=>o instanceof t&&(null==r||o.object.name==r))}async spawnPrefab(t,r,o){if(null==this.materializer)return console.error("Internal error: Materializer is missing on World"),null;const e=new l,n=new i;null!=r&&n.position.copy(r),null!=o&&n.rotation.copy(o),this.materializer.setScene(this.scene),this.materializer.inEditor=this.actorFactory.inEditor;const{object:s,actors:c,mainActor:a}=await this.materializer.createFromPrefabAsset(t.asset,{sceneObjectChain:["r-"+h()]},n,void 0,!1);return e.object=s,e.actors=c,e.mainActor=a,this.scene.attach(s),c.forEach(t=>{this.addActor(t)}),this.physics.addFromScene(s),e}removePrefab(t){t.actors.forEach(t=>this.removeActor(t)),t.object?.removeFromParent(),this.physics.removeRemoved(t.object)}};b=t([r()],b);export{b as World};function j(t,r,e=!1,i=new WeakSet){if(!i.has(t))return i.add(t),r(t),t instanceof o&&t.attachedComponents.forEach(t=>{d(t,e)&&j(t,r,e,i)}),Object.entries(t).filter(([t,r])=>r instanceof s&&d(r,e)).forEach(([t,o])=>{j(o,r,e,i)})}/*
1
+ import{__decorate as t}from"tslib";import{Service as e}from"typedi";import{BaseActor as r}from"../actors/actor.js";import{ActorFactory as s}from"../actors/factory.js";import{Group as o,Vector3 as i}from"three";import{ActorComponent as n}from"../../gameplay/actors/component.js";import{Subject as a}from"rxjs";import{RenderingView as c}from"../../rendering.js";import{randomUUID as h}from"../../utils/uuid";import{PrefabInstance as p}from"../../scene/objects/prefab";import{PhysicsSystem as l}from"./physics/physics-system.js";import{inject as d}from"../../gameplay/inject.js";import{isComponentEnabledInEnvironment as m}from"../actors/internal/component-init.js";import{NetRole as v}from"../net/service/net-actor-role.js";import{BasePlayerController as f}from"../actors/controller/actor-controller.js";import{EventGraphInstance as y}from"../event-graph/runtime.js";import{ViewController as w}from"./render.js";import{AssetsProvider as u}from"../../scene/assets-provider.js";import{WorldEventGraphAssetRuntime as b}from"../event-graph/runtime-assets.js";import{hasExecutableEventGraphDocument as E}from"../event-graph/model.js";const A=new i;class G{constructor(t){this.view=t}get direction(){return this.view.csm.lightDirection}set intensity(t){this.view.csm.lightIntensity=t,this.view.csm.lights.forEach(t=>t.intensity=this.view.csm.lightIntensity)}get intensity(){return this.view.csm.lightIntensity}get position(){return 0==this.view.csm.lights.length?A:this.view.csm.lights[0].position}}let g=class{constructor(){this.actorFactory=d(s),this.view=d(c),this.viewController=d(w),this.physics=d(l),this.assetsProvider=d(u),this.eventGraphAssets=new b(this,this.assetsProvider),this.actors=[],this.actorAdded=new a,this.actorRemoved=new a,this.directionalLight=new G(this.view),this.sceneEventGraphs=new Map,this.sceneEventGraphSubscriptions=[]}async spawnActor(t,e,r,s){if(null==t)throw new Error("Cannot spawn actor with null type");if("prefab"in t){const o=t.prefab,i=await this.spawnPrefab(o,e,r),n=i.mainActor;if(null==n)throw new Error(`Prefab has no main actor or there was an error when spwaning it. Prefab: ${JSON.stringify(o)}`);return n.disposed.subscribe(()=>{const t=i.actors.findIndex(t=>t===n);t>=0&&i.actors.splice(t,1),this.removePrefab(i)}),null!=s?.owner&&(n.owner=s.owner),n}const o=await this.actorFactory.create(t,e,r);return null!=s?.owner&&(o.owner=s.owner),this.addActor(o,e,r),o}async spawnActorWithNetInfo(t,e,r,s,o,i){const n=await this.actorFactory.create(t,o,i,!0),a=null!=s&&0!==s?this.actors.find(t=>t.__netid===s):null;return n.__netid=e,n.netRole=r,n.owner=a,n instanceof f&&(n.isLocallyControlled=r===v.autonomousProxy),this.actorFactory.initActor(n),this.addActor(n,o,i),n}async spawnLocalPlayerController(t,e,r){const s=await this.actorFactory.create(t,e,r,!0);return s.isLocallyControlled=!0,this.actorFactory.initActor(s),this.addActor(s,e,r),s}spawnActorSync(t,e,r){if(null==t)throw new Error("Cannot spawn actor with null type");const s=this.actorFactory.createSync(t,e,r);return this.addActor(s,e,r),s}addActor(t,e,r){e&&t.object.position.copy(e),r&&t.object.rotation.copy(r),null==t.object.parent&&this.scene.add(t.object),this.actors.push(t),j(t,t=>t.onBeginPlay(),this.actorFactory.inEditor),this.actorAdded.next(t)}removeActor(t){for(const[e,r]of[...this.sceneEventGraphs])r.binding.mainActor===t&&this.deactivateSceneEventGraph(e);j(t,t=>t.onEndPlay(),this.actorFactory.inEditor);const e=this.actors.indexOf(t);e>=0&&this.actors.splice(e,1),t.object.removeFromParent(),t.disposed.next(!0),this.actorRemoved.next(t),this.physics.removeActor(t)}findActorByType(t,e){return this.actors.find(r=>r instanceof t&&(null==e||r.object.name==e))}findActorsByType(t,e){return this.actors.filter(r=>r instanceof t&&(null==e||r.object.name==e))}resolveSceneActor(t){return this.materializer?.resolveSceneActor(t)}async startSceneEventGraphs(t){this.stopSceneEventGraphs(),this.sceneEventGraphSubscriptions.push(t.prefabEventGraphAdded$.subscribe(t=>{this.activateSceneEventGraph(t).catch(e=>{console.error(`Failed to start scene prefab event graph ${JSON.stringify(t.id)}`,e)})}),t.prefabEventGraphRemoved$.subscribe(t=>{this.deactivateSceneEventGraph(t.id);for(const e of t.actors)this.actors.includes(e)&&this.removeActor(e)}));for(const e of t.prefabEventGraphInstances)await this.activateSceneEventGraph(e)}stopSceneEventGraphs(){for(const t of this.sceneEventGraphSubscriptions)t.unsubscribe();this.sceneEventGraphSubscriptions.length=0;for(const t of[...this.sceneEventGraphs.keys()])this.deactivateSceneEventGraph(t)}async activateSceneEventGraph(t){if(this.sceneEventGraphs.has(t.id))return;for(const e of t.actors)this.actors.includes(e)||this.addActor(e);const e=new y(t.graph,{world:this,actorsById:t.actorsById,mainActor:t.mainActor,updates:this.viewController.onUpdate(),timer:this.viewController,physics:this.physics,assets:this.eventGraphAssets});this.sceneEventGraphs.set(t.id,{binding:t,runtime:e});try{await e.beginPlay()}catch(r){throw this.sceneEventGraphs.delete(t.id),e.endPlay(),r}}deactivateSceneEventGraph(t){const e=this.sceneEventGraphs.get(t);null!=e&&(this.sceneEventGraphs.delete(t),e.runtime.endPlay())}async spawnPrefab(t,e,r){if(null==this.materializer)return console.error("Internal error: Materializer is missing on World"),null;const s=new p,i=new o;null!=e&&i.position.copy(e),null!=r&&i.rotation.copy(r),this.materializer.setScene(this.scene),this.materializer.inEditor=this.actorFactory.inEditor;const{object:n,actors:a,actorsById:c,mainActor:l}=await this.materializer.createFromPrefabAsset(t.asset,{sceneObjectChain:["r-"+h()],runtimeSpawn:!0},i,void 0,!1);s.object=n,s.actors=a,s.mainActor=l,this.scene.attach(n),a.forEach(t=>{this.addActor(t)}),this.physics.addFromScene(n);const d=t.asset.prefab?.eventGraph;if(!this.actorFactory.inEditor&&E(d)){s.eventGraph=new y(d,{world:this,actorsById:c,mainActor:l,updates:this.viewController.onUpdate(),timer:this.viewController,physics:this.physics,assets:this.eventGraphAssets});try{await s.eventGraph.beginPlay()}catch(t){throw this.removePrefab(s),t}}return s}removePrefab(t){if(t.destroyed)return;t.destroyed=!0,t.eventGraph?.endPlay(),t.eventGraph=void 0;t.actors.splice(0).forEach(t=>this.removeActor(t)),t.object?.removeFromParent(),this.physics.removeRemoved(t.object)}};g=t([e()],g);export{g as World};function j(t,e,s=!1,o=new WeakSet){if(!o.has(t))return o.add(t),e(t),t instanceof r&&t.attachedComponents.forEach(t=>{m(t,s)&&j(t,e,s,o)}),Object.entries(t).filter(([t,e])=>e instanceof n&&m(e,s)).forEach(([t,r])=>{j(r,e,s,o)})}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */