@hology/core 0.0.233 → 0.0.235

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 (150) hide show
  1. package/dist/csm.d.ts +2 -2
  2. package/dist/data/surface-definition.js +1 -1
  3. package/dist/effects/sequence/sequence-action.d.ts +4 -4
  4. package/dist/effects/sequence/sequence-animation-retiming.d.ts +1 -1
  5. package/dist/effects/sequence/sequence-data.d.ts +3 -2
  6. package/dist/effects/sequence/sequence-definitions.d.ts +2 -2
  7. package/dist/effects/sequence/sequence-event.d.ts +1 -1
  8. package/dist/effects/sequence/sequence-locator.d.ts +1 -1
  9. package/dist/effects/sequence/sequence-ops.d.ts +1 -1
  10. package/dist/effects/sequence/sequence-player.d.ts +8 -7
  11. package/dist/effects/sequence/sequence-transform.d.ts +1 -1
  12. package/dist/effects/sequence/sequence-value-lane.d.ts +2 -2
  13. package/dist/effects/vfx/behaviours.d.ts +2 -1
  14. package/dist/effects/vfx/initializsers.d.ts +2 -1
  15. package/dist/effects/vfx/rates.d.ts +1 -1
  16. package/dist/effects/vfx/trail-renderer.d.ts +1 -1
  17. package/dist/effects/vfx/vfx-asset.d.ts +4 -3
  18. package/dist/effects/vfx/vfx-binding-runtime.d.ts +2 -2
  19. package/dist/effects/vfx/vfx-collision-behaviour.d.ts +3 -2
  20. package/dist/effects/vfx/vfx-defs.d.ts +5 -3
  21. package/dist/effects/vfx/vfx-input-runtime.d.ts +1 -1
  22. package/dist/effects/vfx/vfx-materializer.d.ts +7 -7
  23. package/dist/effects/vfx/vfx-param.d.ts +3 -3
  24. package/dist/effects/vfx/vfx-renderers.d.ts +4 -3
  25. package/dist/effects/vfx/vfx-renderers.js +1 -1
  26. package/dist/effects/vfx/vfx-service.d.ts +1 -1
  27. package/dist/effects/vfx/vfx-service.js +1 -1
  28. package/dist/game-component/game-component.d.ts +1 -1
  29. package/dist/gameplay/actors/builtin/components/character/character-movement.js +1 -1
  30. package/dist/gameplay/actors/builtin/components/editor-sprite-component.d.ts +1 -1
  31. package/dist/gameplay/actors/builtin/components/editor-sprite-component.js +1 -1
  32. package/dist/gameplay/actors/builtin/components/volume-editor-component.d.ts +1 -1
  33. package/dist/gameplay/actors/builtin/components/volume-editor-component.js +1 -1
  34. package/dist/gameplay/actors/builtin/navmesh-actor.d.ts +1 -1
  35. package/dist/gameplay/actors/builtin/navmesh-actor.js +1 -1
  36. package/dist/gameplay/actors/builtin/post-process-volume-actor.d.ts +1 -1
  37. package/dist/gameplay/actors/builtin/post-process-volume-actor.js +1 -1
  38. package/dist/gameplay/actors/component.d.ts +2 -2
  39. package/dist/gameplay/actors/controller/actor-controller.d.ts +1 -1
  40. package/dist/gameplay/actors/controller/actor-controller.js +1 -1
  41. package/dist/gameplay/actors/internal/component-init.d.ts +1 -1
  42. package/dist/gameplay/actors/internal/container-map.d.ts +2 -2
  43. package/dist/gameplay/ai/behavior-tree/move.d.ts +3 -3
  44. package/dist/gameplay/ai/behavior-tree/move.js +1 -1
  45. package/dist/gameplay/ai/build-tile.d.ts +2 -1
  46. package/dist/gameplay/ai/dynamic-tiled-navmesh.d.ts +4 -3
  47. package/dist/gameplay/ai/navigation.js +1 -1
  48. package/dist/gameplay/animation/anim-sm.d.ts +1 -1
  49. package/dist/gameplay/animation/retarget.d.ts +2 -1
  50. package/dist/gameplay/animation/root-motion.d.ts +2 -1
  51. package/dist/gameplay/event-graph/runtime-assets.d.ts +1 -1
  52. package/dist/gameplay/initiate.d.ts +5 -5
  53. package/dist/gameplay/inject.d.ts +1 -1
  54. package/dist/gameplay/net/browser/index.d.ts +3 -2
  55. package/dist/gameplay/net/browser/index.js +1 -1
  56. package/dist/gameplay/net/net-session.d.ts +2 -2
  57. package/dist/gameplay/services/asset-loader.js +1 -1
  58. package/dist/gameplay/services/game-time-scheduler.d.ts +1 -1
  59. package/dist/gameplay/services/physics/abstract-physics-system.d.ts +7 -7
  60. package/dist/gameplay/services/pointer-events.d.ts +2 -2
  61. package/dist/gameplay/services/pointer-events.js +1 -1
  62. package/dist/gameplay/services/world.d.ts +1 -1
  63. package/dist/gameplay/services/world.js +1 -1
  64. package/dist/index.d.ts +3 -3
  65. package/dist/index.js +1 -1
  66. package/dist/rendering/cluster-generator.d.ts +2 -1
  67. package/dist/rendering/fog/fog-volume-actor.d.ts +1 -1
  68. package/dist/rendering/fog/fog-volume-actor.js +1 -1
  69. package/dist/rendering/fog/fog-volume-object.d.ts +2 -1
  70. package/dist/rendering/fog/volumetric-fog-pass.d.ts +4 -2
  71. package/dist/rendering/fog/volumetric-fog-pass.js +1 -1
  72. package/dist/rendering/light-probes/light-volume-capture.d.ts +2 -1
  73. package/dist/rendering/motion-vector-node.d.ts +8 -0
  74. package/dist/rendering/motion-vector-node.js +4 -0
  75. package/dist/rendering/node-material-webgpu-resolver.d.ts +2 -1
  76. package/dist/rendering/post-process-effect.d.ts +1 -1
  77. package/dist/rendering/webgpu-experimental-backend.d.ts +23 -3
  78. package/dist/rendering/webgpu-experimental-backend.js +1 -1
  79. package/dist/rendering.d.ts +14 -2
  80. package/dist/rendering.js +1 -1
  81. package/dist/scene/asset-resource-loader.d.ts +5 -4
  82. package/dist/scene/assets-provider.d.ts +2 -2
  83. package/dist/scene/batched-mesh-2.d.ts +1 -1
  84. package/dist/scene/bootstrap.d.ts +8 -7
  85. package/dist/scene/collision/collision-shape-import.d.ts +3 -3
  86. package/dist/scene/collision/collision-shape.d.ts +2 -1
  87. package/dist/scene/custom-param-deserialize.d.ts +1 -1
  88. package/dist/scene/custom-param-runtime-types.d.ts +2 -1
  89. package/dist/scene/landscape/landscape-manager.d.ts +6 -6
  90. package/dist/scene/landscape/landscape-manager.js +1 -1
  91. package/dist/scene/landscape/utils.d.ts +2 -2
  92. package/dist/scene/materializer.js +1 -1
  93. package/dist/scene/materials/grass-foliage.d.ts +2 -2
  94. package/dist/scene/materials/grass.d.ts +1 -1
  95. package/dist/scene/materials/utils/material-painting.d.ts +2 -1
  96. package/dist/scene/materials/water.d.ts +1 -1
  97. package/dist/scene/model.d.ts +1 -1
  98. package/dist/scene/objects/prefab.d.ts +3 -3
  99. package/dist/scene/objects/shapes.d.ts +4 -2
  100. package/dist/scene/runtime-asset-service.d.ts +2 -2
  101. package/dist/scene/runtime-backend-service.d.ts +2 -2
  102. package/dist/scene/runtime-bundled-backend-service.d.ts +3 -3
  103. package/dist/scene/scatter/painted-scatter-manager.d.ts +1 -1
  104. package/dist/scene/scatter/surface-scatter-manager.d.ts +4 -4
  105. package/dist/scene/scene-data-service.d.ts +1 -1
  106. package/dist/scene/surface-query.d.ts +2 -2
  107. package/dist/scene/surface-query.js +1 -1
  108. package/dist/shader/builtin/decal-unlit-shader.js +1 -1
  109. package/dist/shader/builtin/index.d.ts +1 -1
  110. package/dist/shader/decal-shader.d.ts +3 -2
  111. package/dist/shader/graph/compiler.d.ts +1 -1
  112. package/dist/shader/parameter.d.ts +8 -8
  113. package/dist/shader/post-process-shader.d.ts +2 -1
  114. package/dist/shader/shader.d.ts +6 -5
  115. package/dist/shader/trail-shader.d.ts +3 -2
  116. package/dist/shader/trail-shader.js +1 -1
  117. package/dist/shader/uv-nodes.d.ts +2 -2
  118. package/dist/shader-nodes/bulge.d.ts +1 -1
  119. package/dist/shader-nodes/curve-sample.d.ts +2 -2
  120. package/dist/shader-nodes/depth.d.ts +3 -3
  121. package/dist/shader-nodes/dither.d.ts +1 -1
  122. package/dist/shader-nodes/effects.d.ts +1 -1
  123. package/dist/shader-nodes/glsl-node.d.ts +1 -1
  124. package/dist/shader-nodes/glsl-node.js +1 -1
  125. package/dist/shader-nodes/gradient-sample.d.ts +1 -1
  126. package/dist/shader-nodes/landscape.d.ts +1 -1
  127. package/dist/shader-nodes/layers.d.ts +1 -1
  128. package/dist/shader-nodes/material-flags.d.ts +1 -1
  129. package/dist/shader-nodes/material-flags.js +1 -1
  130. package/dist/shader-nodes/particle.d.ts +1 -1
  131. package/dist/shader-nodes/particle.js +1 -1
  132. package/dist/shader-nodes/pom.d.ts +2 -1
  133. package/dist/shader-nodes/pom.js +1 -1
  134. package/dist/shader-nodes/scene-sample.d.ts +2 -1
  135. package/dist/shader-nodes/shapes.d.ts +1 -1
  136. package/dist/shader-nodes/texture-sequence.d.ts +1 -1
  137. package/dist/shader-nodes/time.d.ts +1 -1
  138. package/dist/shader-nodes/voronoi.d.ts +1 -1
  139. package/dist/shader-nodes/wgsl-node.d.ts +1 -1
  140. package/dist/shader-nodes/wgsl-node.js +1 -1
  141. package/dist/test/parameter-definition.test.js +1 -1
  142. package/dist/utils/materials.d.ts +1 -1
  143. package/dist/utils/mesh.d.ts +1 -1
  144. package/dist/utils/obb-utils.d.ts +2 -1
  145. package/dist/utils/three/cleanup.d.ts +1 -1
  146. package/dist/utils/three/depth-pass.d.ts +1 -1
  147. package/dist/utils/three/traverse.d.ts +2 -1
  148. package/dist/worker/index.js +1 -1
  149. package/package.json +2 -1
  150. package/tsconfig.tsbuildinfo +1 -1
package/dist/csm.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Material } from 'three';
2
- import { RenderingView } from './rendering.js';
1
+ import type { Material } from 'three';
2
+ import type { RenderingView } from './rendering.js';
3
3
  import * as THREE from 'three';
4
4
  export declare const CSMUtil: {
5
5
  /**
@@ -1,4 +1,4 @@
1
- import{__decorate as r}from"tslib";import{DataAssetDefinition as s}from"../shader";let t=class{};t=r([s("base.surface",{abstract:!0})],t);export{t as BaseSurfaceDefinition};/*
1
+ import{__decorate as r}from"tslib";import{DataAssetDefinition as s}from"../shader/index.js";let t=class{};t=r([s("base.surface",{abstract:!0})],t);export{t as BaseSurfaceDefinition};/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,7 +1,7 @@
1
- import { SequenceRole } from './sequence-data.js';
2
- import { BaseActor } from '../../gameplay/actors/actor.js';
3
- import { Object3D } from 'three';
4
- import { SequenceLocatorReader } from './sequence-locator.js';
1
+ import type { SequenceRole } from './sequence-data.js';
2
+ import type { BaseActor } from '../../gameplay/actors/actor.js';
3
+ import type { Object3D } from 'three';
4
+ import type { SequenceLocatorReader } from './sequence-locator.js';
5
5
  import type { Observable } from 'rxjs';
6
6
  /**
7
7
  * SequenceAction is used to play, pause, stop, etc. a sequence.
@@ -1,5 +1,5 @@
1
1
  import * as THREE from 'three';
2
- import { AnimationClipInstance, AnimationClipRetiming, AnimationClipRetimingMode, AnimationClipRetimingPoint } from './sequence-data.js';
2
+ import type { AnimationClipInstance, AnimationClipRetiming, AnimationClipRetimingMode, AnimationClipRetimingPoint } from './sequence-data.js';
3
3
  export declare const MAX_ANIMATION_CLIP_RETIME_POINTS = 3;
4
4
  export interface AnimationClipRetimingControlPoint extends AnimationClipRetimingPoint {
5
5
  implicit: boolean;
@@ -1,5 +1,6 @@
1
- import { AssetId, CustomParamValue, SerializedParamType } from '../../scene/model.js';
2
- import { AudioParameterId } from './audio-parameters.js';
1
+ import type { AssetId, CustomParamValue } from '../../scene/model.js';
2
+ import { SerializedParamType } from '../../scene/model.js';
3
+ import type { AudioParameterId } from './audio-parameters.js';
3
4
  import type { CameraShakeSettings } from '../../gameplay/services/camera-shake.js';
4
5
  import type { PostProcessEffectStage } from '../../rendering/post-process-effect.js';
5
6
  export interface SequencePropertyOption {
@@ -1,5 +1,5 @@
1
- import { AnimationClipInstance, PropertySubTrackOptions, MaterialSubTrackOptions, SequenceTrack, SequenceTrackType, SubTrack, SubTrackType } from './sequence-data.js';
2
- import { AudioParameterId } from './audio-parameters.js';
1
+ import type { AnimationClipInstance, PropertySubTrackOptions, MaterialSubTrackOptions, SequenceTrack, SequenceTrackType, SubTrack, SubTrackType } from './sequence-data.js';
2
+ import type { AudioParameterId } from './audio-parameters.js';
3
3
  import { SerializedParamType } from '../../scene/model.js';
4
4
  export type SequenceTrackRuntimeEvaluator = 'object' | 'locator' | 'camera' | 'cameraShake' | 'postProcess' | 'audio' | 'vfx' | 'spawn' | 'group';
5
5
  export type SequenceSubTrackRuntimeEvaluator = 'transform' | 'animation' | 'visibility' | 'parameter' | 'event';
@@ -1,6 +1,6 @@
1
1
  import 'reflect-metadata';
2
2
  import type { ParameterOptions, ParameterType, PropertyParameter } from '../../shader/parameter.js';
3
- import { Type } from '../../utils/type.js';
3
+ import type { Type } from '../../utils/type.js';
4
4
  /**
5
5
  * Metadata about a sequence event method on an actor
6
6
  */
@@ -1,4 +1,4 @@
1
- import { Quaternion, Vector3 } from 'three';
1
+ import type { Quaternion, Vector3 } from 'three';
2
2
  export interface SequenceLocatorSnapshot {
3
3
  trackId: string;
4
4
  name: string;
@@ -1,4 +1,4 @@
1
- import { AnimationClipInstance, PropertyKeyframe, SequenceData, SequenceEventData, SequenceTrack, SubTrack, SubTrackType, TransformKeyframe, VisibilityKeyframe } from './sequence-data.js';
1
+ import type { AnimationClipInstance, PropertyKeyframe, SequenceData, SequenceEventData, SequenceTrack, SubTrack, SubTrackType, TransformKeyframe, VisibilityKeyframe } from './sequence-data.js';
2
2
  export interface SequenceTrackReference {
3
3
  trackId: string;
4
4
  }
@@ -1,14 +1,15 @@
1
1
  import { Subject } from 'rxjs';
2
2
  import * as THREE from 'three';
3
- import { AnimationAction, AnimationMixer, Euler, Object3D, Vector3 } from 'three';
4
- import { VfxService } from '../../effects/vfx/vfx-service.js';
3
+ import type { AnimationAction } from 'three';
4
+ import { AnimationMixer, Euler, Object3D, Vector3 } from 'three';
5
+ import type { VfxService } from '../../effects/vfx/vfx-service.js';
5
6
  import { BaseActor } from '../../gameplay/actors/actor.js';
6
- import { ActorFactory } from '../../gameplay/actors/factory.js';
7
- import { AssetLoader } from '../../gameplay/services/asset-loader.js';
7
+ import type { ActorFactory } from '../../gameplay/actors/factory.js';
8
+ import type { AssetLoader } from '../../gameplay/services/asset-loader.js';
8
9
  import type { World } from '../../gameplay/services/world.js';
9
- import { PrefabInstance } from '../../scene/objects/prefab.js';
10
- import { SequenceData, SequenceRole, SequenceTrack } from './sequence-data.js';
11
- import { SequenceLocatorReader, SequenceLocatorSnapshot } from './sequence-locator.js';
10
+ import type { PrefabInstance } from '../../scene/objects/prefab.js';
11
+ import type { SequenceData, SequenceRole, SequenceTrack } from './sequence-data.js';
12
+ import type { SequenceLocatorReader, SequenceLocatorSnapshot } from './sequence-locator.js';
12
13
  import { CharacterAnimationComponent } from '../../gameplay/actors/index.js';
13
14
  import type { ViewController } from '../../gameplay/services/render.js';
14
15
  /**
@@ -1,5 +1,5 @@
1
1
  import { Vector3 } from 'three';
2
- import { TransformKeyframe } from './sequence-data.js';
2
+ import type { TransformKeyframe } from './sequence-data.js';
3
3
  export type TransformPositionTangentDirection = 'in' | 'out';
4
4
  /** Evaluates transform position keys without allocating in the playback path. */
5
5
  export declare function evaluateTransformPosition(keyframes: readonly TransformKeyframe[], time: number, target: Vector3): boolean;
@@ -1,5 +1,5 @@
1
- import { CustomParamValue } from '../../scene/model.js';
2
- import { InterpolationMode, PropertyKeyframe } from './sequence-data.js';
1
+ import type { CustomParamValue } from '../../scene/model.js';
2
+ import type { InterpolationMode, PropertyKeyframe } from './sequence-data.js';
3
3
  export interface TimedSequenceItem {
4
4
  time: number;
5
5
  }
@@ -1,5 +1,6 @@
1
1
  import { Vector3 } from "three";
2
- import { Behaviour, Emitter, Particle } from "@hology/nebula";
2
+ import type { Emitter, Particle } from "@hology/nebula";
3
+ import { Behaviour } from "@hology/nebula";
3
4
  import * as THREE from 'three';
4
5
  export type EasingFunction = (x: number) => number;
5
6
  /**
@@ -1,5 +1,6 @@
1
1
  import { Vector3, Color } from "three";
2
- import { Emitter, Particle, Initializer } from "@hology/nebula";
2
+ import type { Emitter, Particle } from "@hology/nebula";
3
+ import { Initializer } from "@hology/nebula";
3
4
  export declare class DefaultInitializer extends Initializer {
4
5
  init(emitter: Emitter, particle: Particle): void;
5
6
  initialize(target: Emitter | Particle): void;
@@ -1,5 +1,5 @@
1
1
  import { Rate } from "@hology/nebula";
2
- import { Span, SpanValue } from '@hology/nebula';
2
+ import type { Span, SpanValue } from '@hology/nebula';
3
3
  export { Rate } from "@hology/nebula";
4
4
  export declare class DelayRate extends Rate {
5
5
  readonly delay: number;
@@ -1,6 +1,6 @@
1
1
  import * as THREE from "three";
2
2
  import { NodeShaderMaterial } from 'three-shader-graph';
3
- import { OutputTextureSetting } from '../../gameplay';
3
+ import type { OutputTextureSetting } from '../../gameplay/index.js';
4
4
  export declare const trailUV: import("three-shader-graph").Vec2Node;
5
5
  export declare const trailDragUV: import("three-shader-graph").Vec2Node;
6
6
  export declare class Trail extends THREE.Object3D {
@@ -1,6 +1,7 @@
1
- import { LibraryShapeType } from '../../scene/objects/shapes.js';
2
- import { AssetId, CustomParamValue, SerializedParamType } from '../../scene/model.js';
3
- import { LibraryVfxBehaviourType, LibraryVfxInitalizerType } from './vfx-defs.js';
1
+ import type { LibraryShapeType } from '../../scene/objects/shapes.js';
2
+ import type { AssetId, CustomParamValue } from '../../scene/model.js';
3
+ import { SerializedParamType } from '../../scene/model.js';
4
+ import type { LibraryVfxBehaviourType, LibraryVfxInitalizerType } from './vfx-defs.js';
4
5
  export type OnceRateData = {
5
6
  type: 'once';
6
7
  count: number;
@@ -1,6 +1,6 @@
1
1
  import { Behaviour, Initializer } from "@hology/nebula";
2
- import { CustomParamValue } from "../../scene/model.js";
3
- import { VfxInputRuntime } from "./vfx-input-runtime.js";
2
+ import type { CustomParamValue } from "../../scene/model.js";
3
+ import type { VfxInputRuntime } from "./vfx-input-runtime.js";
4
4
  export type VfxBindingMode = 'spawn' | 'live';
5
5
  export type VfxBindableParameterType = 'number' | 'color' | 'string' | 'select' | 'vec2' | 'vec3' | 'curve' | 'animationclip' | 'boolean';
6
6
  export type VfxBindableParameterDefinition = {
@@ -1,5 +1,6 @@
1
- import { Behaviour, Emitter, Particle } from "@hology/nebula";
2
- import { PhysicsSystem } from "../../gameplay/services/physics/physics-system.js";
1
+ import type { Particle } from "@hology/nebula";
2
+ import { Behaviour, Emitter } from "@hology/nebula";
3
+ import type { PhysicsSystem } from "../../gameplay/services/physics/physics-system.js";
3
4
  export declare class WorldCollisionBehaviour extends Behaviour {
4
5
  private physics;
5
6
  private bounce;
@@ -1,9 +1,11 @@
1
- import { AnimationClip, Vector2, Vector3 } from "three";
2
- import { Alpha, Attraction, Behaviour, Color as ChangeColor, Force, Gravity, Initializer, Life, Mass, Position, RadialVelocity, RandomDrift, Repulsion, Rotate } from "@hology/nebula";
1
+ import type { AnimationClip } from "three";
2
+ import { Vector2, Vector3 } from "three";
3
+ import type { Behaviour, Initializer } from "@hology/nebula";
4
+ import { Alpha, Attraction, Color as ChangeColor, Force, Gravity, Life, Mass, Position, RadialVelocity, RandomDrift, Repulsion, Rotate } from "@hology/nebula";
3
5
  import { Disperse, FollowParent, LinearDamping, MoveOverLife, RotatePosition, Scale, ScaleComponents } from './behaviours.js';
4
6
  import { AdditiveVelocity, InitialScale, InitialScaleComponents, RandomColor, RandomDirection, RandomScale, Rotation } from './initializsers.js';
5
7
  import { Curve2 } from "../../utils/curve.js";
6
- import { VfxBindingAdapter, VfxBindingMode, VfxBoundBehaviourDefinition, VfxBoundInitializerDefinition } from "./vfx-binding-runtime.js";
8
+ import type { VfxBindingAdapter, VfxBindingMode, VfxBoundBehaviourDefinition, VfxBoundInitializerDefinition } from "./vfx-binding-runtime.js";
7
9
  type HexColor = `#${string}`;
8
10
  export type ShapeParameterDef<T = boolean | number | string | Vector3 | Vector2 | HexColor | Curve2 | AnimationClip> = {
9
11
  type: T extends number ? 'number' : T extends HexColor ? 'color' : T extends string ? 'string' | 'select' : T extends Vector2 ? 'vec2' : T extends Vector3 ? 'vec3' : T extends Curve2 ? 'curve' : T extends AnimationClip ? 'animationclip' : T extends boolean ? 'boolean' : never;
@@ -1,5 +1,5 @@
1
1
  import * as THREE from 'three';
2
- import { VfxEffectInputDefinition } from './vfx-asset.js';
2
+ import type { VfxEffectInputDefinition } from './vfx-asset.js';
3
3
  export declare class VfxInputRuntime {
4
4
  private readonly definitions;
5
5
  private readonly inputIdsByName;
@@ -1,13 +1,13 @@
1
1
  import System from "@hology/nebula";
2
2
  import * as THREE from 'three';
3
3
  import { Object3D } from "three";
4
- import { PhysicsSystem } from '../../gameplay/services/physics/physics-system.js';
5
- import { ViewController } from '../../gameplay/services/render.js';
6
- import { Asset, VfxAsset } from '../../scene/model.js';
7
- import { ShaderProvider } from "../../gameplay/services/shader-provider.js";
8
- import { AssetResourceLoader } from "../../scene/asset-resource-loader.js";
9
- import { AssetsProvider } from "../../scene/assets-provider.js";
10
- import { VfxInputRuntime } from "./vfx-input-runtime.js";
4
+ import type { PhysicsSystem } from '../../gameplay/services/physics/physics-system.js';
5
+ import type { ViewController } from '../../gameplay/services/render.js';
6
+ import type { Asset, VfxAsset } from '../../scene/model.js';
7
+ import type { ShaderProvider } from "../../gameplay/services/shader-provider.js";
8
+ import type { AssetResourceLoader } from "../../scene/asset-resource-loader.js";
9
+ import type { AssetsProvider } from "../../scene/assets-provider.js";
10
+ import type { VfxInputRuntime } from "./vfx-input-runtime.js";
11
11
  export type VfxAssetProvider = {
12
12
  getAsset(assetId: string): Promise<Asset>;
13
13
  getTexture(assetId: string): Promise<THREE.Texture>;
@@ -1,7 +1,7 @@
1
1
  import { VfxActor } from './vfx-actor.js';
2
- import { ActorProvider } from "../../scene/materializer.js";
3
- import { VfxAsset } from "../../scene/model.js";
4
- import { Object3D } from 'three';
2
+ import type { ActorProvider } from "../../scene/materializer.js";
3
+ import type { VfxAsset } from "../../scene/model.js";
4
+ import type { Object3D } from 'three';
5
5
  import { BaseActor } from '../../gameplay/actors/actor.js';
6
6
  export declare class VisualEffect {
7
7
  private actorProvider;
@@ -1,8 +1,9 @@
1
- import { CustomRenderer, MeshRenderer, Particle } from '@hology/nebula';
1
+ import type { Particle } from '@hology/nebula';
2
+ import { CustomRenderer, MeshRenderer } from '@hology/nebula';
2
3
  import * as THREE from 'three';
3
4
  import { Object3D } from 'three';
4
- import { ViewController } from '../../gameplay/services/render.js';
5
- import { OutputTextureSetting } from './vfx-asset.js';
5
+ import type { ViewController } from '../../gameplay/services/render.js';
6
+ import type { OutputTextureSetting } from './vfx-asset.js';
6
7
  export declare class MultiRenderer extends CustomRenderer {
7
8
  private worldContainer;
8
9
  private localContainer;
@@ -1,4 +1,4 @@
1
- import{CustomRenderer as e,MeshRenderer as t,PUID as r}from"@hology/nebula";import*as a from"three";import{InstancedBufferAttribute as o,Object3D as n}from"three";import{NodeShaderMaterial as i}from"three-shader-graph";import{StretchedSprite as s}from"./stretched-sprite.js";import{Trail as l}from"./trail-renderer.js";import{SpriteNodeShaderMaterial as c}from"../../shader/sprite-shader";import{particleEnergyUniformName as d}from"../../shader-nodes/particle";import{AssetMeshInstance as m}from"../../scene/asset-resource-loader.js";import{markMaterialUniformValuesNeedUpdate as u}from"../../rendering/node-material-webgpu-resolver.js";var h;!function(e){e[e.mesh=0]="mesh",e[e.instanced=1]="instanced",e[e.sprite=2]="sprite",e[e.stretchedBillboard=3]="stretchedBillboard",e[e.trail=4]="trail"}(h||(h={}));export class MultiRenderer extends e{constructor(e,t,r,a){super(),this.worldContainer=e,this.localContainer=t,this.three=r,this.view=a,this.localRenderers=[],this.worldRenderers=[]}onSystemUpdate(){for(const e of this.worldRenderers)e?.onSystemUpdate();for(const e of this.localRenderers)e?.onSystemUpdate()}onParticleCreated(e){e.target=null,this.getRenderer(e)?.onParticleCreated(e)}onParticleUpdate(e){this.getRenderer(e)?.onParticleUpdate(e)}onParticleDead(e){this.getRenderer(e)?.onParticleDead(e),e._renderer=null}getRenderer(e){if(e._renderer)return e._renderer;const t=(null!=e?.parent?e?.parent._space:null)??"world",r="world"===t?this.worldContainer:this.localContainer,o="world"===t?this.worldRenderers:this.localRenderers;return"trail"===e.body.type?(null==o[h.trail]&&(o[h.trail]=new TrailRenderer(r,this.three)),e._renderer=o[h.trail]):e.body instanceof s?(null==o[h.stretchedBillboard]&&(o[h.stretchedBillboard]=new StretchedSpriteInstancedRenderer(r,this.three,this.view)),e._renderer=o[h.stretchedBillboard]):e.body instanceof a.Sprite?(null==o[h.sprite]&&(o[h.sprite]=new CombinedRenderer(r,this.three)),e._renderer=o[h.sprite]):e.body instanceof a.Mesh&&0==e.body.children.length&&e.body.material instanceof i?(null==o[h.instanced]&&(o[h.instanced]=new InstancedRenderer(r,this.three,this.view)),e._renderer=o[h.instanced]):e.body instanceof a.Object3D?(null==o[h.mesh]&&(o[h.mesh]=new CombinedRenderer(r,this.three)),e._renderer=o[h.mesh]):void 0}dispose(){this.localRenderers.forEach(e=>{e instanceof InstancedRenderer&&e.dispose()}),this.worldRenderers.forEach(e=>{e instanceof InstancedRenderer&&e.dispose()})}}export class TrailRenderer extends t{constructor(){super(...arguments),this.trails=[]}dispose(){}onSystemUpdate(){for(const e of this.trails)e.update()}onParticleCreated(e){const t=e.body,r=new l(this.container,!1),o=new n;this.container.add(o),o.updateMatrixWorld(),o.updateWorldMatrix(!0,!0);const i=t.material?.clone()??l.createBaseMaterial(t.texture,t.scrollSpeed,t.opacityChannel,t.billboard??!1);i.uniforms.taper&&(i.uniforms.taper.value=t.taper??!1);const s=new a.Color(t.color??0).multiplyScalar(t.intensity??1),c=new a.Color(t.colorEnd??0).multiplyScalar(t.intensityEnd??t.intensity??1);i.uniforms.headColor&&i.uniforms.tailColor&&(i.uniforms.headColor.value=new a.Vector4(s.r,s.g,s.b,t.opacityStart??1),i.uniforms.tailColor.value=new a.Vector4(c.r,c.g,c.b,t.opacityEnd??1)),i.uniforms.color&&null==i.uniforms.headColor&&(i.uniforms.color.value=s),i.uniforms.opacity&&null==i.uniforms.headColor&&(i.uniforms.opacity.value=t.opacityStart??1),t.bloom&&(i.userData.hasBloom=!0),r.initialize(i,Math.round(t.length??10),!1,t.width,null,o,t.billboard??!1),null!=t.renderOrder&&null!=r.mesh&&(r.mesh.renderOrder=t.renderOrder);const d=e.rotation;o.rotation.set(d.x,d.y,d.z);e.scale;r.activate(),this.trails.push(r),e.target=o}onParticleUpdate(e){const t=e.target;t.position.copy(e.position);const r=e.body;let a=v;e.old&&e.old.position?a.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z):a.copy(e.velocity),a.lengthSq()>1e-8?a.normalize():a.copy(U);const o=P;o.setFromUnitVectors(a,U),t.rotation.set(0,0,0),t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),t.applyQuaternion(o);const n=this.trails.findIndex(e=>e.targetObject.id===t.id);if(-1!=n){const t=this.trails[n];if(e.useAlpha){if(t.material.uniforms.headColor&&t.material.uniforms.tailColor){t.material.uniforms.headColor.value.setW((r.opacityStart??1)*e.alpha);t.material.uniforms.tailColor.value.setW((r.opacityEnd??1)*e.alpha)}null!=t.material.uniforms.opacity&&(t.material.uniforms.opacity.value=e.alpha)}e.useColor&&null!=t.material.uniforms.color&&t.material.uniforms.color.value.copy(e.color),null!=t.material.uniforms[d]&&(t.material.uniforms[d].value=e.energy),u(t.material)}}onParticleDead(e){const t=e.target,r=this.trails.findIndex(e=>e.targetObject.id===t.id);if(-1!=r){const e=this.trails[r];e.removeFromParent(),e.mesh.removeFromParent(),e.targetObject.removeFromParent(),t.removeFromParent(),this.trails.splice(r,1)}}}export class CombinedRenderer extends t{dispose(){}scale(e){const t=e.transform.initialScale;e.target instanceof a.Sprite?null!=t?e.target.scale.set(t.x*e.scale*e.radius,t.y*e.scale*e.radius,1):e.target.scale.set(e.scale*e.radius,e.scale*e.radius,1):null!=t?e.target.scale.set(t.x*e.scale,t.y*e.scale,t.z*e.scale):super.scale(e)}rotate(e){e.target.material.rotation=e.rotation.z}onParticleCreated(e){e.target||(e.target=this._targetPool.get(e.body),(e.useAlpha||e.useColor)&&(e.target instanceof a.Mesh||e.target instanceof a.Sprite&&e.target.material instanceof a.Material)&&(e.target.material.__puid=r.id(e.body.material),e.target.material=this._materialPool.get(e.target.material))),e.target&&e.target instanceof n&&(e.target.position.set(e.position.x,e.position.y,e.position.z),this.container.add(e.target))}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:o,rotation:i}=e;if(t){if(t.position.copy(e.position),this.isThreeSprite(e)||(t instanceof a.Mesh&&t.material instanceof c?e.target.material.rotation=e.rotation.z:t.rotation.set(i.x,i.y,i.z)),this.scale(e),e.transform&&e.transform.orientAlongVelocity&&t instanceof n){const r=p.set(e.velocity.x,e.velocity.y,e.velocity.z).normalize(),a=t.getWorldDirection(f);a.applyAxisAngle(y,Math.PI/-2),g.setFromUnitVectors(a,r),t.quaternion.copy(g)}(r||o)&&this.applyUniforms(t,e)}}applyUniforms(e,t){if(e instanceof m&&e.traverse(r=>r!==e&&this.applyUniforms(r,t)),e instanceof a.Mesh){let r=!1;t.useAlpha&&(e.material instanceof c&&null!=e.material.uniforms.opacity&&(e.material.uniforms.opacity.value=t.alpha,r=!0),e.material instanceof a.ShaderMaterial&&null!=e.material.uniforms.opacity?(e.material.uniforms.opacity.value=t.alpha,r=!0):(e.material.opacity=t.alpha,r=!0),e.material.transparent=!0),t.useColor&&(null!=e.material.color?(e.material.color.copy(t.color),r=!0):e.material instanceof a.ShaderMaterial&&null!=e.material.uniforms.color&&(e.material.uniforms.color.value=t.color,r=!0)),r&&u(e.material)}}onParticleDead(e){e.target&&(e.target.material&&(e.useAlpha||e.useColor)&&this._materialPool.expire(e.target.material),this._targetPool.expire(e.target),this.container.remove(e.target),e.target=null)}}export class StretchedSpriteInstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach(e=>e.mesh.geometry.dispose())}onSystemUpdate(){for(const e of this.meshes){const t=e.mesh.geometry.getAttribute("offset"),r=e.mesh.geometry.getAttribute("size"),o=e.mesh.geometry.getAttribute("velocity"),n=e.mesh.geometry.getAttribute("rotation"),i=e.mesh.geometry.getAttribute("particleColor");let s=0;for(const l of e.particles){if(null==l||l.dead)continue;if(l.useColor||l.color instanceof a.Color){const e=S.copy(l.color).getRGB(z);i.setXYZW(s,e.r,e.g,e.b,1),i.needsUpdate=!0}l.useAlpha&&(i.setW(s,l.alpha),i.needsUpdate=!0),"number"==typeof l.rotation?n.setX(s,l.rotation):n.setX(s,l.rotation.x);const e=l.position;if(t.setXYZ(s,e.x,e.y,e.z),"number"!=typeof l.scale)throw new Error("Particle scale is not a number");r.setXYZ(s,l.scale,l.scale,l.scale);let c=l.body.scaleFactor;0===c&&(c=.001);const d=1,m=l.velocity;o.setXYZW(s,m.x*c,m.y*c,m.z*c,d),s++}s>0&&(t.clearUpdateRanges(),t.addUpdateRange(0,3*s),t.needsUpdate=!0,r.clearUpdateRanges(),r.addUpdateRange(0,3*s),r.needsUpdate=!0,i.clearUpdateRanges(),i.addUpdateRange(0,4*s),i.needsUpdate=!0,o.clearUpdateRanges(),o.addUpdateRange(0,4*s),o.needsUpdate=!0,n.clearUpdateRanges(),n.addUpdateRange(0,s),n.needsUpdate=!0)}}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate,r=t.timePan.a;if(!Number.isFinite(r)||r<=0)return t.numPan.b*this.calcMaxCount(e.parent.parentParticle);return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(e.body instanceof s&&null==e.target){const t=e.body;let r=this.meshes.find(e=>e.mesh.material.uuid===t.material.uuid);if(null==r){const n=this.calcMaxCount(e),i=new a.InstancedBufferGeometry;i.setIndex(t.geometry.getIndex()),i.setAttribute("position",t.geometry.getAttribute("position")),t.geometry.hasAttribute("normal")&&i.setAttribute("normal",t.geometry.getAttribute("normal")),i.setAttribute("uv",t.geometry.getAttribute("uv"));const s=new o(new Float32Array(3*n),3);s.setUsage(a.DynamicDrawUsage),i.setAttribute("offset",s);const l=new o(new Float32Array(4*n),4);if(l.setUsage(a.DynamicDrawUsage),i.setAttribute("particleColor",l),t.material instanceof c){const e=new a.Color(t.material.color);for(let t=0;t<l.count;t++)l.setXYZW(t,e.r,e.g,e.b,1)}const d=new o(new Float32Array(3*n),3);d.setUsage(a.DynamicDrawUsage),i.setAttribute("size",d);const m=new o(new Float32Array(4*n),4);m.setUsage(a.DynamicDrawUsage),i.setAttribute("velocity",m);const u=new o(new Float32Array(4*n),1);u.setUsage(a.DynamicDrawUsage),i.setAttribute("rotation",u),r={mesh:new a.Mesh(i,t.material),indices:new Float32Array(n),particles:[]},r.mesh.renderOrder=t.renderOrder,this.meshes.push(r),this.container.add(r.mesh)}let n=r.indices.findIndex(e=>0===e);n<0&&(n=function(e){let t=e[0],r=0;for(let a=1;a<e.length;a++)e[a]<t&&(t=e[a],r=a);return r}(r.indices)),r.indices[n]=performance.now(),e.target=n,r.particles[n]=e}}onParticleUpdate(e){}onParticleDead(e){const t=e.body;let r=this.meshes.find(e=>e.mesh.material.uuid===t.material.uuid);if(r){const t=r.mesh.geometry.getAttribute("size");t.setXYZ(e.target,0,0,0),t.needsUpdate=!0,r.particles[e.target]=null,r.indices[e.target]=0}e.target=null}}const p=new a.Vector3,f=new a.Vector3,g=new a.Quaternion,y=new a.Vector3(1,0,0),b=1e5;function w(e){return Number.isFinite(e)?Math.min(Math.max(Math.ceil(e),1),b):b}export class InstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach(e=>e.mesh.dispose())}onSystemUpdate(){for(const e of this.meshes)e.mesh.material.transparent&&e.mesh.material.blending===a.NormalBlending&&F(e,this.view.getCamera())}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate,r=t.timePan.a,a=t.numPan.b,o=e.parent.parentParticle;if(!Number.isFinite(r)||r<=0)return w(a*this.calcMaxCount(o));return w(a*Math.ceil(e.life/Math.min(Math.max(r,.01),1))*this.calcMaxCount(o))}onParticleCreated(e){if(e.body instanceof a.Sprite)return;const t=e.body;let r=this.meshes.find(e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid);if(null==r){const o=this.calcMaxCount(e);r={mesh:new a.InstancedMesh(t.geometry,t.material,o),indices:new Array(o).fill(null),particles:[],sortOrder:new Array(o),sortDistances:new Float32Array(o),sortedMatrices:new Float32Array(16*o),sortedColors:new Float32Array(4*o),sortedParticleData:new Float32Array(3*o),sortedRotations:new Float32Array(o),sortedParticles:new Array(o),sortedIndices:new Array(o)},r.mesh.renderOrder=t.renderOrder,r.mesh.userData.webGpuCacheMaterial=!0;const n=new Float32Array(4*o);n.fill(1),r.mesh.instanceColor=new a.InstancedBufferAttribute(n,4),r.mesh.setColorAt(0,S.setScalar(1)),r.mesh.instanceColor.needsUpdate=!0,r.mesh.material.defines.USE_INSTANCING="",r.mesh.material.needsUpdate=!0;const i=new Float32Array(3*o);M.makeScale(0,0,0);for(let e=0;e<o;e++)i[3*e+0]=1,i[3*e+1]=1,i[3*e+2]=1,r.mesh.instanceMatrix.array.set(M.elements,16*e);r.mesh.instanceMatrix.needsUpdate=!0,r.mesh.geometry.setAttribute("particleData",new a.InstancedBufferAttribute(i,3));const s=new a.InstancedBufferAttribute(new Float32Array(o),1);s.setUsage(a.DynamicDrawUsage),r.mesh.geometry.setAttribute("rotation",s),this.meshes.push(r),this.container.add(r.mesh)}let o=r.indices.findIndex(e=>null==e);if(o<0&&(o=r.indices.indexOf(Math.min(...r.indices))),o<0||o>=r.mesh.instanceMatrix.count)return void(e.target=null);const n=r.particles[o];if(null!=n&&n!==e&&(n.target=null),r.indices[o]=performance.now(),e.target=o,r.particles[o]=e,r.mesh.count<=o&&(r.mesh.count=o+1),"number"==typeof e.target){e.transform.initialScale;const t=e.body;let r=this.meshes.find(e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid);C(e,r.mesh),e.useAlpha&&(r.mesh.material.transparent||(r.mesh.material.transparent=!0,r.mesh.material.needsUpdate=!0))}}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:a,rotation:o}=e;if(null==t)return;const n=e.body,i=this.meshes.find(e=>e.mesh.geometry.uuid===n.geometry.uuid&&e.mesh.material.uuid===n.material.uuid);if(null==i)return;if(!A(i,e))return void(e.target=null);if(i.mesh.frustumCulled=!1,C(e,i.mesh),a){S.copy(e.color);const t=i.mesh.instanceColor.array,r=e.target*i.mesh.instanceColor.itemSize;t[r+0]=S.r,t[r+1]=S.g,t[r+2]=S.b,i.mesh.instanceColor.itemSize>=4&&(t[r+3]=1),i.mesh.instanceColor.needsUpdate=!0}const s=i.mesh.geometry.getAttribute("particleData");r&&s.setX(e.target,e.alpha),s.setY(e.target,e.energy),s.needsUpdate=!0;const l=i.mesh.geometry.getAttribute("rotation");l.setX(e.target,o.z),l.needsUpdate=!0}onParticleDead(e){if(null!=e.target){const t=e.body,r=this.meshes.find(e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid);if(null==r)return;if(!A(r,e))return void(e.target=null);r.indices[e.target]=null,r.particles[e.target]=null,e.scale=0,C(e,r.mesh),r.mesh.instanceMatrix.needsUpdate=!0,e.target=null}}}const x=new n;function A(e,t){const r=t.target;return"number"==typeof r&&Number.isInteger(r)&&r>=0&&r<e.mesh.instanceMatrix.count&&e.particles[r]===t}function C(e,t){if(!Number.isInteger(e.target)||e.target<0||e.target>=t.instanceMatrix.count)return;if(v.set(e.position.x,e.position.y,e.position.z),e.transform&&e.transform.orientAlongVelocity){const r=p.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize();t.getMatrixAt(e.target,x.matrix);const a=x.getWorldDirection(R);a.applyAxisAngle(y,Math.PI/-2),P.setFromUnitVectors(a,r)}else D.set(e.rotation.x,e.rotation.y,e.rotation.z),P.setFromEuler(D);const r=e.transform.initialScale;null!=r?R.set(r.x*e.scale,r.y*e.scale,r.z*e.scale):R.set(e.scale,e.scale,e.scale),M.compose(v,P,R),t.instanceMatrix.array.set(M.elements,16*e.target),t.instanceMatrix.needsUpdate=!0}const U=new a.Vector3(0,0,-1),M=new a.Matrix4,P=new a.Quaternion,v=new a.Vector3,R=new a.Vector3,D=new a.Euler,S=new a.Color(0),z={r:0,g:0,b:0};function F(e,t){const r=e.mesh,a=r.instanceMatrix.array,o=r.instanceColor.array,n=r.geometry.getAttribute("particleData"),i=n.array,s=r.geometry.getAttribute("rotation"),l=s.array,c=r.worldToLocal(t.getWorldPosition(I));let d=0;for(let t=0;t<e.particles.length;t++){if(null==e.particles[t])continue;const r=16*t,o=a[r+12]-c.x,n=a[r+13]-c.y,i=a[r+14]-c.z;e.sortDistances[t]=o*o+n*n+i*i,e.sortOrder[d++]=t}e.sortOrder.length=d,e.sortOrder.sort((t,r)=>e.sortDistances[r]-e.sortDistances[t]);for(let t=0;t<d;t++){const r=e.sortOrder[t];for(let o=0;o<16;o++)e.sortedMatrices[16*t+o]=a[16*r+o];for(let a=0;a<4;a++)e.sortedColors[4*t+a]=o[4*r+a];for(let a=0;a<3;a++)e.sortedParticleData[3*t+a]=i[3*r+a];e.sortedRotations[t]=l[r],e.sortedParticles[t]=e.particles[r],e.sortedIndices[t]=e.indices[r]}for(let t=0;t<d;t++){const r=e.sortedParticles[t];e.particles[t]=r,e.indices[t]=e.sortedIndices[t],l[t]=e.sortedRotations[t],r.target=t}for(let t=d;t<e.indices.length;t++)e.particles[t]=null,e.indices[t]=null;for(let t=0;t<16*d;t++)a[t]=e.sortedMatrices[t];for(let t=0;t<4*d;t++)o[t]=e.sortedColors[t];for(let t=0;t<3*d;t++)i[t]=e.sortedParticleData[t];r.count=d,r.instanceMatrix.needsUpdate=!0,r.instanceColor.needsUpdate=!0,n.needsUpdate=!0,s.needsUpdate=!0}export{F as sortInstancedMeshByDistance};const I=new a.Vector3;/*
1
+ import{CustomRenderer as e,MeshRenderer as t,PUID as r}from"@hology/nebula";import*as a from"three";import{InstancedBufferAttribute as o,Object3D as n}from"three";import{NodeShaderMaterial as i}from"three-shader-graph";import{StretchedSprite as s}from"./stretched-sprite.js";import{Trail as l}from"./trail-renderer.js";import{SpriteNodeShaderMaterial as c}from"../../shader/sprite-shader.js";import{particleEnergyUniformName as d}from"../../shader-nodes/particle.js";import{AssetMeshInstance as m}from"../../scene/asset-resource-loader.js";import{markMaterialUniformValuesNeedUpdate as u}from"../../rendering/node-material-webgpu-resolver.js";var h;!function(e){e[e.mesh=0]="mesh",e[e.instanced=1]="instanced",e[e.sprite=2]="sprite",e[e.stretchedBillboard=3]="stretchedBillboard",e[e.trail=4]="trail"}(h||(h={}));export class MultiRenderer extends e{constructor(e,t,r,a){super(),this.worldContainer=e,this.localContainer=t,this.three=r,this.view=a,this.localRenderers=[],this.worldRenderers=[]}onSystemUpdate(){for(const e of this.worldRenderers)e?.onSystemUpdate();for(const e of this.localRenderers)e?.onSystemUpdate()}onParticleCreated(e){e.target=null,this.getRenderer(e)?.onParticleCreated(e)}onParticleUpdate(e){this.getRenderer(e)?.onParticleUpdate(e)}onParticleDead(e){this.getRenderer(e)?.onParticleDead(e),e._renderer=null}getRenderer(e){if(e._renderer)return e._renderer;const t=(null!=e?.parent?e?.parent._space:null)??"world",r="world"===t?this.worldContainer:this.localContainer,o="world"===t?this.worldRenderers:this.localRenderers;return"trail"===e.body.type?(null==o[h.trail]&&(o[h.trail]=new TrailRenderer(r,this.three)),e._renderer=o[h.trail]):e.body instanceof s?(null==o[h.stretchedBillboard]&&(o[h.stretchedBillboard]=new StretchedSpriteInstancedRenderer(r,this.three,this.view)),e._renderer=o[h.stretchedBillboard]):e.body instanceof a.Sprite?(null==o[h.sprite]&&(o[h.sprite]=new CombinedRenderer(r,this.three)),e._renderer=o[h.sprite]):e.body instanceof a.Mesh&&0==e.body.children.length&&e.body.material instanceof i?(null==o[h.instanced]&&(o[h.instanced]=new InstancedRenderer(r,this.three,this.view)),e._renderer=o[h.instanced]):e.body instanceof a.Object3D?(null==o[h.mesh]&&(o[h.mesh]=new CombinedRenderer(r,this.three)),e._renderer=o[h.mesh]):void 0}dispose(){this.localRenderers.forEach(e=>{e instanceof InstancedRenderer&&e.dispose()}),this.worldRenderers.forEach(e=>{e instanceof InstancedRenderer&&e.dispose()})}}export class TrailRenderer extends t{constructor(){super(...arguments),this.trails=[]}dispose(){}onSystemUpdate(){for(const e of this.trails)e.update()}onParticleCreated(e){const t=e.body,r=new l(this.container,!1),o=new n;this.container.add(o),o.updateMatrixWorld(),o.updateWorldMatrix(!0,!0);const i=t.material?.clone()??l.createBaseMaterial(t.texture,t.scrollSpeed,t.opacityChannel,t.billboard??!1);i.uniforms.taper&&(i.uniforms.taper.value=t.taper??!1);const s=new a.Color(t.color??0).multiplyScalar(t.intensity??1),c=new a.Color(t.colorEnd??0).multiplyScalar(t.intensityEnd??t.intensity??1);i.uniforms.headColor&&i.uniforms.tailColor&&(i.uniforms.headColor.value=new a.Vector4(s.r,s.g,s.b,t.opacityStart??1),i.uniforms.tailColor.value=new a.Vector4(c.r,c.g,c.b,t.opacityEnd??1)),i.uniforms.color&&null==i.uniforms.headColor&&(i.uniforms.color.value=s),i.uniforms.opacity&&null==i.uniforms.headColor&&(i.uniforms.opacity.value=t.opacityStart??1),t.bloom&&(i.userData.hasBloom=!0),r.initialize(i,Math.round(t.length??10),!1,t.width,null,o,t.billboard??!1),null!=t.renderOrder&&null!=r.mesh&&(r.mesh.renderOrder=t.renderOrder);const d=e.rotation;o.rotation.set(d.x,d.y,d.z);e.scale;r.activate(),this.trails.push(r),e.target=o}onParticleUpdate(e){const t=e.target;t.position.copy(e.position);const r=e.body;let a=v;e.old&&e.old.position?a.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z):a.copy(e.velocity),a.lengthSq()>1e-8?a.normalize():a.copy(U);const o=P;o.setFromUnitVectors(a,U),t.rotation.set(0,0,0),t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),t.applyQuaternion(o);const n=this.trails.findIndex(e=>e.targetObject.id===t.id);if(-1!=n){const t=this.trails[n];if(e.useAlpha){if(t.material.uniforms.headColor&&t.material.uniforms.tailColor){t.material.uniforms.headColor.value.setW((r.opacityStart??1)*e.alpha);t.material.uniforms.tailColor.value.setW((r.opacityEnd??1)*e.alpha)}null!=t.material.uniforms.opacity&&(t.material.uniforms.opacity.value=e.alpha)}e.useColor&&null!=t.material.uniforms.color&&t.material.uniforms.color.value.copy(e.color),null!=t.material.uniforms[d]&&(t.material.uniforms[d].value=e.energy),u(t.material)}}onParticleDead(e){const t=e.target,r=this.trails.findIndex(e=>e.targetObject.id===t.id);if(-1!=r){const e=this.trails[r];e.removeFromParent(),e.mesh.removeFromParent(),e.targetObject.removeFromParent(),t.removeFromParent(),this.trails.splice(r,1)}}}export class CombinedRenderer extends t{dispose(){}scale(e){const t=e.transform.initialScale;e.target instanceof a.Sprite?null!=t?e.target.scale.set(t.x*e.scale*e.radius,t.y*e.scale*e.radius,1):e.target.scale.set(e.scale*e.radius,e.scale*e.radius,1):null!=t?e.target.scale.set(t.x*e.scale,t.y*e.scale,t.z*e.scale):super.scale(e)}rotate(e){e.target.material.rotation=e.rotation.z}onParticleCreated(e){e.target||(e.target=this._targetPool.get(e.body),(e.useAlpha||e.useColor)&&(e.target instanceof a.Mesh||e.target instanceof a.Sprite&&e.target.material instanceof a.Material)&&(e.target.material.__puid=r.id(e.body.material),e.target.material=this._materialPool.get(e.target.material))),e.target&&e.target instanceof n&&(e.target.position.set(e.position.x,e.position.y,e.position.z),this.container.add(e.target))}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:o,rotation:i}=e;if(t){if(t.position.copy(e.position),this.isThreeSprite(e)||(t instanceof a.Mesh&&t.material instanceof c?e.target.material.rotation=e.rotation.z:t.rotation.set(i.x,i.y,i.z)),this.scale(e),e.transform&&e.transform.orientAlongVelocity&&t instanceof n){const r=p.set(e.velocity.x,e.velocity.y,e.velocity.z).normalize(),a=t.getWorldDirection(f);a.applyAxisAngle(y,Math.PI/-2),g.setFromUnitVectors(a,r),t.quaternion.copy(g)}(r||o)&&this.applyUniforms(t,e)}}applyUniforms(e,t){if(e instanceof m&&e.traverse(r=>r!==e&&this.applyUniforms(r,t)),e instanceof a.Mesh){let r=!1;t.useAlpha&&(e.material instanceof c&&null!=e.material.uniforms.opacity&&(e.material.uniforms.opacity.value=t.alpha,r=!0),e.material instanceof a.ShaderMaterial&&null!=e.material.uniforms.opacity?(e.material.uniforms.opacity.value=t.alpha,r=!0):(e.material.opacity=t.alpha,r=!0),e.material.transparent=!0),t.useColor&&(null!=e.material.color?(e.material.color.copy(t.color),r=!0):e.material instanceof a.ShaderMaterial&&null!=e.material.uniforms.color&&(e.material.uniforms.color.value=t.color,r=!0)),r&&u(e.material)}}onParticleDead(e){e.target&&(e.target.material&&(e.useAlpha||e.useColor)&&this._materialPool.expire(e.target.material),this._targetPool.expire(e.target),this.container.remove(e.target),e.target=null)}}export class StretchedSpriteInstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach(e=>e.mesh.geometry.dispose())}onSystemUpdate(){for(const e of this.meshes){const t=e.mesh.geometry.getAttribute("offset"),r=e.mesh.geometry.getAttribute("size"),o=e.mesh.geometry.getAttribute("velocity"),n=e.mesh.geometry.getAttribute("rotation"),i=e.mesh.geometry.getAttribute("particleColor");let s=0;for(const l of e.particles){if(null==l||l.dead)continue;if(l.useColor||l.color instanceof a.Color){const e=S.copy(l.color).getRGB(z);i.setXYZW(s,e.r,e.g,e.b,1),i.needsUpdate=!0}l.useAlpha&&(i.setW(s,l.alpha),i.needsUpdate=!0),"number"==typeof l.rotation?n.setX(s,l.rotation):n.setX(s,l.rotation.x);const e=l.position;if(t.setXYZ(s,e.x,e.y,e.z),"number"!=typeof l.scale)throw new Error("Particle scale is not a number");r.setXYZ(s,l.scale,l.scale,l.scale);let c=l.body.scaleFactor;0===c&&(c=.001);const d=1,m=l.velocity;o.setXYZW(s,m.x*c,m.y*c,m.z*c,d),s++}s>0&&(t.clearUpdateRanges(),t.addUpdateRange(0,3*s),t.needsUpdate=!0,r.clearUpdateRanges(),r.addUpdateRange(0,3*s),r.needsUpdate=!0,i.clearUpdateRanges(),i.addUpdateRange(0,4*s),i.needsUpdate=!0,o.clearUpdateRanges(),o.addUpdateRange(0,4*s),o.needsUpdate=!0,n.clearUpdateRanges(),n.addUpdateRange(0,s),n.needsUpdate=!0)}}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate,r=t.timePan.a;if(!Number.isFinite(r)||r<=0)return t.numPan.b*this.calcMaxCount(e.parent.parentParticle);return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(e.body instanceof s&&null==e.target){const t=e.body;let r=this.meshes.find(e=>e.mesh.material.uuid===t.material.uuid);if(null==r){const n=this.calcMaxCount(e),i=new a.InstancedBufferGeometry;i.setIndex(t.geometry.getIndex()),i.setAttribute("position",t.geometry.getAttribute("position")),t.geometry.hasAttribute("normal")&&i.setAttribute("normal",t.geometry.getAttribute("normal")),i.setAttribute("uv",t.geometry.getAttribute("uv"));const s=new o(new Float32Array(3*n),3);s.setUsage(a.DynamicDrawUsage),i.setAttribute("offset",s);const l=new o(new Float32Array(4*n),4);if(l.setUsage(a.DynamicDrawUsage),i.setAttribute("particleColor",l),t.material instanceof c){const e=new a.Color(t.material.color);for(let t=0;t<l.count;t++)l.setXYZW(t,e.r,e.g,e.b,1)}const d=new o(new Float32Array(3*n),3);d.setUsage(a.DynamicDrawUsage),i.setAttribute("size",d);const m=new o(new Float32Array(4*n),4);m.setUsage(a.DynamicDrawUsage),i.setAttribute("velocity",m);const u=new o(new Float32Array(4*n),1);u.setUsage(a.DynamicDrawUsage),i.setAttribute("rotation",u),r={mesh:new a.Mesh(i,t.material),indices:new Float32Array(n),particles:[]},r.mesh.renderOrder=t.renderOrder,this.meshes.push(r),this.container.add(r.mesh)}let n=r.indices.findIndex(e=>0===e);n<0&&(n=function(e){let t=e[0],r=0;for(let a=1;a<e.length;a++)e[a]<t&&(t=e[a],r=a);return r}(r.indices)),r.indices[n]=performance.now(),e.target=n,r.particles[n]=e}}onParticleUpdate(e){}onParticleDead(e){const t=e.body;let r=this.meshes.find(e=>e.mesh.material.uuid===t.material.uuid);if(r){const t=r.mesh.geometry.getAttribute("size");t.setXYZ(e.target,0,0,0),t.needsUpdate=!0,r.particles[e.target]=null,r.indices[e.target]=0}e.target=null}}const p=new a.Vector3,f=new a.Vector3,g=new a.Quaternion,y=new a.Vector3(1,0,0),b=1e5;function w(e){return Number.isFinite(e)?Math.min(Math.max(Math.ceil(e),1),b):b}export class InstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach(e=>e.mesh.dispose())}onSystemUpdate(){for(const e of this.meshes)e.mesh.material.transparent&&e.mesh.material.blending===a.NormalBlending&&F(e,this.view.getCamera())}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate,r=t.timePan.a,a=t.numPan.b,o=e.parent.parentParticle;if(!Number.isFinite(r)||r<=0)return w(a*this.calcMaxCount(o));return w(a*Math.ceil(e.life/Math.min(Math.max(r,.01),1))*this.calcMaxCount(o))}onParticleCreated(e){if(e.body instanceof a.Sprite)return;const t=e.body;let r=this.meshes.find(e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid);if(null==r){const o=this.calcMaxCount(e);r={mesh:new a.InstancedMesh(t.geometry,t.material,o),indices:new Array(o).fill(null),particles:[],sortOrder:new Array(o),sortDistances:new Float32Array(o),sortedMatrices:new Float32Array(16*o),sortedColors:new Float32Array(4*o),sortedParticleData:new Float32Array(3*o),sortedRotations:new Float32Array(o),sortedParticles:new Array(o),sortedIndices:new Array(o)},r.mesh.renderOrder=t.renderOrder,r.mesh.userData.webGpuCacheMaterial=!0;const n=new Float32Array(4*o);n.fill(1),r.mesh.instanceColor=new a.InstancedBufferAttribute(n,4),r.mesh.setColorAt(0,S.setScalar(1)),r.mesh.instanceColor.needsUpdate=!0,r.mesh.material.defines.USE_INSTANCING="",r.mesh.material.needsUpdate=!0;const i=new Float32Array(3*o);M.makeScale(0,0,0);for(let e=0;e<o;e++)i[3*e+0]=1,i[3*e+1]=1,i[3*e+2]=1,r.mesh.instanceMatrix.array.set(M.elements,16*e);r.mesh.instanceMatrix.needsUpdate=!0,r.mesh.geometry.setAttribute("particleData",new a.InstancedBufferAttribute(i,3));const s=new a.InstancedBufferAttribute(new Float32Array(o),1);s.setUsage(a.DynamicDrawUsage),r.mesh.geometry.setAttribute("rotation",s),this.meshes.push(r),this.container.add(r.mesh)}let o=r.indices.findIndex(e=>null==e);if(o<0&&(o=r.indices.indexOf(Math.min(...r.indices))),o<0||o>=r.mesh.instanceMatrix.count)return void(e.target=null);const n=r.particles[o];if(null!=n&&n!==e&&(n.target=null),r.indices[o]=performance.now(),e.target=o,r.particles[o]=e,r.mesh.count<=o&&(r.mesh.count=o+1),"number"==typeof e.target){e.transform.initialScale;const t=e.body;let r=this.meshes.find(e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid);C(e,r.mesh),e.useAlpha&&(r.mesh.material.transparent||(r.mesh.material.transparent=!0,r.mesh.material.needsUpdate=!0))}}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:a,rotation:o}=e;if(null==t)return;const n=e.body,i=this.meshes.find(e=>e.mesh.geometry.uuid===n.geometry.uuid&&e.mesh.material.uuid===n.material.uuid);if(null==i)return;if(!A(i,e))return void(e.target=null);if(i.mesh.frustumCulled=!1,C(e,i.mesh),a){S.copy(e.color);const t=i.mesh.instanceColor.array,r=e.target*i.mesh.instanceColor.itemSize;t[r+0]=S.r,t[r+1]=S.g,t[r+2]=S.b,i.mesh.instanceColor.itemSize>=4&&(t[r+3]=1),i.mesh.instanceColor.needsUpdate=!0}const s=i.mesh.geometry.getAttribute("particleData");r&&s.setX(e.target,e.alpha),s.setY(e.target,e.energy),s.needsUpdate=!0;const l=i.mesh.geometry.getAttribute("rotation");l.setX(e.target,o.z),l.needsUpdate=!0}onParticleDead(e){if(null!=e.target){const t=e.body,r=this.meshes.find(e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid);if(null==r)return;if(!A(r,e))return void(e.target=null);r.indices[e.target]=null,r.particles[e.target]=null,e.scale=0,C(e,r.mesh),r.mesh.instanceMatrix.needsUpdate=!0,e.target=null}}}const x=new n;function A(e,t){const r=t.target;return"number"==typeof r&&Number.isInteger(r)&&r>=0&&r<e.mesh.instanceMatrix.count&&e.particles[r]===t}function C(e,t){if(!Number.isInteger(e.target)||e.target<0||e.target>=t.instanceMatrix.count)return;if(v.set(e.position.x,e.position.y,e.position.z),e.transform&&e.transform.orientAlongVelocity){const r=p.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize();t.getMatrixAt(e.target,x.matrix);const a=x.getWorldDirection(R);a.applyAxisAngle(y,Math.PI/-2),P.setFromUnitVectors(a,r)}else D.set(e.rotation.x,e.rotation.y,e.rotation.z),P.setFromEuler(D);const r=e.transform.initialScale;null!=r?R.set(r.x*e.scale,r.y*e.scale,r.z*e.scale):R.set(e.scale,e.scale,e.scale),M.compose(v,P,R),t.instanceMatrix.array.set(M.elements,16*e.target),t.instanceMatrix.needsUpdate=!0}const U=new a.Vector3(0,0,-1),M=new a.Matrix4,P=new a.Quaternion,v=new a.Vector3,R=new a.Vector3,D=new a.Euler,S=new a.Color(0),z={r:0,g:0,b:0};function F(e,t){const r=e.mesh,a=r.instanceMatrix.array,o=r.instanceColor.array,n=r.geometry.getAttribute("particleData"),i=n.array,s=r.geometry.getAttribute("rotation"),l=s.array,c=r.worldToLocal(t.getWorldPosition(I));let d=0;for(let t=0;t<e.particles.length;t++){if(null==e.particles[t])continue;const r=16*t,o=a[r+12]-c.x,n=a[r+13]-c.y,i=a[r+14]-c.z;e.sortDistances[t]=o*o+n*n+i*i,e.sortOrder[d++]=t}e.sortOrder.length=d,e.sortOrder.sort((t,r)=>e.sortDistances[r]-e.sortDistances[t]);for(let t=0;t<d;t++){const r=e.sortOrder[t];for(let o=0;o<16;o++)e.sortedMatrices[16*t+o]=a[16*r+o];for(let a=0;a<4;a++)e.sortedColors[4*t+a]=o[4*r+a];for(let a=0;a<3;a++)e.sortedParticleData[3*t+a]=i[3*r+a];e.sortedRotations[t]=l[r],e.sortedParticles[t]=e.particles[r],e.sortedIndices[t]=e.indices[r]}for(let t=0;t<d;t++){const r=e.sortedParticles[t];e.particles[t]=r,e.indices[t]=e.sortedIndices[t],l[t]=e.sortedRotations[t],r.target=t}for(let t=d;t<e.indices.length;t++)e.particles[t]=null,e.indices[t]=null;for(let t=0;t<16*d;t++)a[t]=e.sortedMatrices[t];for(let t=0;t<4*d;t++)o[t]=e.sortedColors[t];for(let t=0;t<3*d;t++)i[t]=e.sortedParticleData[t];r.count=d,r.instanceMatrix.needsUpdate=!0,r.instanceColor.needsUpdate=!0,n.needsUpdate=!0,s.needsUpdate=!0}export{F as sortInstancedMeshByDistance};const I=new a.Vector3;/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -2,7 +2,7 @@ import { Object3D } from 'three';
2
2
  import { BaseActor } from '../../gameplay/actors/actor.js';
3
3
  import { VfxActor } from './vfx-actor.js';
4
4
  import { Asset, AssetId } from '../../scene/model.js';
5
- import { VfxPool } from './vfx-param';
5
+ import { VfxPool } from './vfx-param.js';
6
6
  export type VfxSpawnOptions = {
7
7
  inputs?: Record<string, unknown>;
8
8
  };
@@ -1,4 +1,4 @@
1
- import{__decorate as t}from"tslib";import{ActorFactory as s}from"../../gameplay/actors/factory.js";import{AssetLoader as e}from"../../gameplay/services/asset-loader.js";import{BaseActor as o}from"../../gameplay/actors/actor.js";import{inject as r}from"../../gameplay/inject.js";import{Service as a}from"typedi";import{World as c}from"../../gameplay/services/world.js";import{VfxActor as i}from"./vfx-actor.js";import{VfxPool as m}from"./vfx-param";let l=class{constructor(){this.pools=new Map,this.actorFactory=r(s),this.assetService=r(e),this.world=r(c)}async createFromAssetId(t,s=this.world.scene,e){const o=await this.assetService.getAsset(t);return this.createFromAsset(o,s,e)}async createFromAsset(t,s=this.world.scene,e){const r=await this.actorFactory.create(i);return s instanceof o?s.object.add(r.object):s.add(r.object),await r.fromAsset(t,e?.inputs),r}async createPoolFromAssetId(t,s=this.world.scene){const e=await this.assetService.getAsset(t);return this.createPoolFromAsset(e,s)}async createPoolFromAsset(t,s=this.world.scene){let e;return this.pools.has(t.id)||(e=new m(()=>this.createFromAsset(t,s)),this.pools.set(t.id,e)),e}clearPool(t){this.pools.delete(t)}};l=t([a()],l);export{l as VfxService};/*
1
+ import{__decorate as t}from"tslib";import{ActorFactory as s}from"../../gameplay/actors/factory.js";import{AssetLoader as e}from"../../gameplay/services/asset-loader.js";import{BaseActor as o}from"../../gameplay/actors/actor.js";import{inject as r}from"../../gameplay/inject.js";import{Service as a}from"typedi";import{World as c}from"../../gameplay/services/world.js";import{VfxActor as i}from"./vfx-actor.js";import{VfxPool as m}from"./vfx-param.js";let l=class{constructor(){this.pools=new Map,this.actorFactory=r(s),this.assetService=r(e),this.world=r(c)}async createFromAssetId(t,s=this.world.scene,e){const o=await this.assetService.getAsset(t);return this.createFromAsset(o,s,e)}async createFromAsset(t,s=this.world.scene,e){const r=await this.actorFactory.create(i);return s instanceof o?s.object.add(r.object):s.add(r.object),await r.fromAsset(t,e?.inputs),r}async createPoolFromAssetId(t,s=this.world.scene){const e=await this.assetService.getAsset(t);return this.createPoolFromAsset(e,s)}async createPoolFromAsset(t,s=this.world.scene){let e;return this.pools.has(t.id)||(e=new m(()=>this.createFromAsset(t,s)),this.pools.set(t.id,e)),e}clearPool(t){this.pools.delete(t)}};l=t([a()],l);export{l as VfxService};/*
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 { Object3D } from 'three';
1
+ import type { Object3D } from 'three';
2
2
  export declare abstract class GameComponent {
3
3
  id: string;
4
4
  object: Object3D;
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as e}from"tslib";import i from"@dimforge/rapier3d-simd-compat";import{takeUntil as o}from"rxjs";import*as s from"three";import{ArrowHelper as n,MathUtils as r,Quaternion as a,Vector3 as h}from"three";import{RootMotionClip as l}from"../../../../animation/root-motion.js";import{inject as c}from"../../../../inject.js";import{ActionInput as u,AxisInput as d,RotationInput as p}from"../../../../input/index.js";import{NetRole as m}from"../../../../net/service/net-actor-role.js";import{RunOnClient as v,RunOnNotOwner as y,RunOnServer as S}from"../../../../net/service/rpc-decorator.js";import{NetService as g}from"../../../../net/service/net-service.js";import{PhysicsSystem as M,RayTestResult as f}from"../../../../services/physics/physics-system.js";import{CapsuleCollisionShape as x}from"../../../../../scene/collision/collision-shape.js";import{Parameter as T}from"../../../../../shader/parameter.js";import{PhysicsBodyType as C}from"../../../../services/physics/physics-system.js";import{ActorComponent as R,Component as w}from"../../../component.js";import{CharacterMovementMode as A}from"./modes.js";import{DEFAULT_MAX_CLIENT_TIME_AHEAD as q,DEFAULT_LARGE_CORRECTION_THRESHOLD as D,DEFAULT_MAX_COMBINED_MOVE_DELTA_TIME as b,DEFAULT_MAX_MOVE_DELTA_TIME as k,DEFAULT_MAX_MOVES_PER_PACKET as I,DEFAULT_MAX_REPLAYED_MOVES as z,DEFAULT_MAX_SERVER_MOVES_PER_TICK as P,DEFAULT_MAX_SAVED_MOVES as O,DEFAULT_MAX_SERVER_MOVE_DELTA_TIME_SCALAR as j,DEFAULT_MAX_SERVER_MOVE_TIME_BUDGET as G,DEFAULT_MAX_SUBSTEP_DELTA_TIME as Y,DEFAULT_MOVE_SEND_INTERVAL as F,DEFAULT_SIMULATED_INTERPOLATION_DELAY as N,DEFAULT_SIMULATED_STATE_INTERVAL as V,DEFAULT_SMALL_CORRECTION_TOLERANCE as U,DEFAULT_TELEPORT_SNAP_THRESHOLD as X,MOVE_FLAG_CROUCH as E,MOVE_FLAG_JUMP as L,MOVE_FLAG_ROOT_MOTION as B,MOVE_FLAG_SLIDE_START as H,MOVE_FLAG_SPRINT as Z,MOVE_FLAG_SPRINT_START as W,SNAPSHOT_FLAG_CROUCH_SUPPRESSED as $,SNAPSHOT_FLAG_CROUCHING as Q,NetCharacterProxySmoother as J,NetCharacterSavedMoveBuffer as K,accrueNetCharacterServerMoveTime as _,createNetCharacterMovementSnapshot as tt,createNetCharacterServerMoveTimingState as et,consumeNetCharacterServerMoveTime as it,decodeNetCharacterMoveBatch as ot,decodeNetCharacterOwnerAck as st,decodeNetCharacterOwnerCorrection as nt,decodeNetCharacterSimulatedState as rt,encodeNetCharacterMoveBatch as at,encodeNetCharacterOwnerAck as ht,encodeNetCharacterOwnerCorrection as lt,encodeNetCharacterSimulatedState as ct,validateNetCharacterMove as ut}from"./net-character-movement-protocol.js";import{NetMode as dt}from"../../../../net/net-session.js";import{setSlideJumpVelocity as pt,shouldContinueSlide as mt,shouldStartSlide as vt,updateSlideVelocity as yt,updateSlideVelocityFromDisplacement as St}from"./character-slide.js";export*from"./net-character-movement-protocol.js";const gt=131070,Mt=new h(0,1,0),ft=new h,xt=new h,Tt=new h,Ct=new h,Rt=new h,wt=new h,At=new h,qt=new h,Dt=new h,bt=new h,kt=new h,It=new h,zt=new h,Pt=new h,Ot=new h(0,1,0),jt=new h(0,-.05,0),Gt=new h,Yt=new a,Ft=new s.Euler,Nt=new h,Vt=new h,Ut=new h,Xt=new h,Et=new i.CharacterCollision;let Lt=class extends R{get autoStepMinWidth(){return this.cc.autostepMinWidth()}set autoStepMinWidth(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),t,this.cc.autostepIncludesDynamicBodies())}get autoStepDynamicObjects(){return this.cc.autostepIncludesDynamicBodies()}set autoStepDynamicObjects(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),this.cc.autostepMinWidth(),t)}get autoStepMaxHeight(){return this.cc.autostepMaxHeight()}set autoStepMaxHeight(t){this.cc.enableAutostep(t,this.cc.autostepMinWidth(),this.cc.autostepIncludesDynamicBodies())}get snapToGround(){return this.cc.snapToGroundDistance()}set snapToGround(t){this.cc.enableSnapToGround(t)}set offset(t){this.cc.setOffset(t)}get offset(){return this.cc.offset()}set normalNudgeFactor(t){this.cc.setNormalNudgeFactor(t)}get normalNudgeFactor(){return this.cc.normalNudgeFactor()}constructor(){super(),this.isDefaultCharacterMovementComponent=!0,this.directionInput=new d,this.jumpInput=new u,this.sprintInput=new u,this.crouchInput=new u,this.rotationInput=new p,this.horizontalSpeed=0,this.maxSpeed=8,this.maxSpeedBackwards=8,this.maxSpeedSprint=12,this.maxSpeedCrouch=4,this.slideEnabled=!1,this.slideMinStartSpeed=8,this.slideMinExitSpeed=4,this.slideDeceleration=3,this.slideGravityScale=1,this.slideSteeringRate=2,this.sprintStartBoostSpeed=0,this.sprintStartBoostDamping=6,this.jumpVelocity=7,this.fallingMovementControl=.5,this.fallingReorientation=!1,this.groundAccelerationRate=4,this.gravityOverride=null,this.colliderHeight=2,this.colliderRadius=.5,this.crouchColliderHeight=1,this.crouchColliderRadius=null,this.jumpInAir=!1,this.mass=50,this.allowSliding=!0,this.minSlopeSlideAngle=r.degToRad(70),this.maxSlopeClimbAngle=r.degToRad(70),this.applyImpulsesToDynamicBodies=!0,this.normalizedDirection=!0,this.characterCollision=!1,this.allowRootMotionJumpCancel=!1,this.enabled=!0,this.rotateToMovementDirection=!1,this.smoothRotation=!0,this.rotationSpeed=40,this.maxRotationSpeed=100,this.impulseDamping=2,this.moveSendInterval=F,this.simulatedStateInterval=V,this.maxSavedMoves=O,this.maxReplayedMoves=z,this.maxServerMovesPerTick=P,this.maxMovesPerPacket=I,this.maxMoveDeltaTime=k,this.maxCombinedMoveDeltaTime=b,this.maxServerMoveDeltaTimeScalar=j,this.maxClientTimeAhead=q,this.maxServerMoveTimeBudget=G,this.maxSubstepDeltaTime=Y,this.fallGraceTime=.1,this.correctionToleranceSq=U*U,this.largeCorrectionThreshold=D,this.teleportSnapThreshold=X,this.listenServerSmoothing=!0,this.listenServerSmoothLocationTime=.04,this.listenServerMaxSmoothUpdateDistance=1,this.listenServerNoSmoothUpdateDistance=2.5,this.debugCorrections=!0,this.suppressUncrouchLift=!1,this.velocity=new h,this.visualSmoothingOffset=new h,this.slideDirection=new h,this.slideSurfaceNormal=new h(0,1,0),this.mode=A.walking,this.isSprinting=!1,this.isCrouching=!1,this.isSliding=!1,this.pressedJump=!1,this.rayTestResult=new f,this.groundRayTestOptions={debug:!1,excludeTriggers:!0,excludeActor:void 0,resolveActor:!1},this.physicsSystem=c(M),this.netService=c(g),this.state={sequence:0,position:new h,velocity:new h,yaw:0,lookYaw:0,mode:A.walking,grounded:!1,currentSpeed:0,fallGraceTime:0,prevInputDirection:new h,prevRotateToMovementDirection:!1},this.movementModes=new Map,this.savedMoves=new K(O),this.serverMoveTiming=et(),this.serverMoveQueue=[],this.inputMoveScratch={sequence:0,clientTime:0,dt:0,inputX:0,inputY:0,yaw:0,flags:0,clientX:0,clientY:0,clientZ:0,rootMotionX:0,rootMotionY:0,rootMotionZ:0},this.authoritativeMoveScratch={sequence:0,clientTime:0,dt:0,inputX:0,inputY:0,yaw:0,flags:0,clientX:0,clientY:0,clientZ:0,rootMotionX:0,rootMotionY:0,rootMotionZ:0},this.movementModeContext={component:this,state:this.state,move:this.inputMoveScratch,deltaTime:0,rotatedDirection:xt,platformVelocity:Ct,outVelocity:Tt,rootMotionActive:!1,startedSprinting:!1},this.proxySmoother=new J(N,X),this.proxySample=tt(),this.pendingSnapshot=tt(),this.impulse=new h,this.prevRootMotionPos=new h,this.rootMotionOptions={},this.resetRootMotion=!1,this.nextMoveSequence=0,this.clientMoveTime=0,this.lastSentClientMoveTime=0,this.moveSendAccumulator=0,this.simulatedStateAccumulator=0,this.proxyTime=0,this.lastServerProcessedSequence=0,this.lastServerReceivedSequence=0,this.lastAutonomousMoveFlags=0,this.previousSprintInput=!1,this.previousCrouchInput=!1,this.crouchSuppressedUntilRelease=!1,this.slideOnLandingRequested=!1,this.initialized=!1,this.cc=this.physicsSystem.getCharacterController(.1),this.cc.enableSnapToGround(.1),this.cc.enableAutostep(0,.1,!1),this.registerMovementMode(Bt),this.registerMovementMode(Ht),this.registerMovementMode({mode:A.sliding,update:t=>this.updateSlidingMode(t)})}onInit(){this.groundRayTestOptions.excludeActor=this.actor,this.configureCharacterController(),this.physicsSystem.addActor(this.actor,[this.createCollisionShape()],{mass:0,type:C.kinematic,continousCollisionDetection:!1,friction:0,restitution:.5,ignoreForNavMesh:!0}),this.rotationInput.rotation.copy(this.actor.rotation),this.initializeStateFromActor(),this.initialized=!0,this.physicsSystem.beforeStep.pipe(o(this.disposed)).subscribe(t=>this.tick(t))}onLateUpdate(t){this.updateVisualSmoothing(t)}registerMovementMode(t){this.movementModes.set(t.mode,t)}applyImpulse(t){this.impulse.add(t)}getEffectiveGravity(){return this.gravityOverride??this.physicsSystem.getGravity().y}get isGrounded(){return this.rayTestResult.hasHit||this.cc.computedGrounded()}setRootMotionAction(t,e={}){const i=t?.getClip();if(i instanceof l){this.rootMotionAction=t,this.rootMotionOptions=e,this.resetRootMotion=!0;const o=[];this.rootMotionInterpolant=i.motionTrack.InterpolantFactoryMethodSmooth(o);const n=s.PropertyBinding.parseTrackName(i.motionTrack.name);this.rootMotionRootBone=this.actor.object.getObjectByName(n.nodeName)}}serverMove(t){const e=ot(t);if(e.ok)for(const t of e.value.moves)ut(t,this.lastServerReceivedSequence,this.maxMoveDeltaTime)&&(this.lastServerReceivedSequence=t.sequence,this.serverMoveQueue.push(t))}clientMoveAck(t){const e=st(t);e.ok&&this.actor.netRole===m.autonomousProxy&&(this.savedMoves.ack(e.value.sequence),this.sprintPolicy?.ack?.(e.value.sequence,!1))}clientMoveCorrection(t){const e=nt(t);e.ok&&this.actor.netRole===m.autonomousProxy&&(this.debugCorrections&&(null==this.correctionDebug&&(this.correctionDebug=new Qt(Kt(this.actor.object))),this.correctionDebug.update(this.state.position,e.value.snapshot)),this.applyCorrection(e.value.snapshot))}simulatedState(t){const e=rt(t);e.ok&&this.actor.netRole===m.simulatedProxy&&this.proxySmoother.push(e.value,this.proxyTime)}tick(t){if(!this.initialized)return;t=Math.min(.1,t);const e=this.actor.netRole,i=this.netService.mode;e!==m.simulatedProxy?this.enabled&&(e!==m.autonomousProxy?this.isRemoteControlledAuthority(i,e)?this.tickRemoteAuthority(t):this.tickAuthority(t,i):this.tickAutonomousProxy(t)):this.tickSimulatedProxy(t)}tickAutonomousProxy(t){const e=this.state.mode,i=this.lastAutonomousMoveFlags,o=this.createMoveFromInput(t,++this.nextMoveSequence,{quantizeClientTime:!0});this.performMove(o,_t),this.resetToggleCrouchAfterSlide(e);const s=this.state.mode!==e||o.flags!==i;this.lastAutonomousMoveFlags=o.flags,this.savedMoves.capacity=this.maxSavedMoves,this.savedMoves.maxCombinedDeltaTime=Math.min(this.maxCombinedMoveDeltaTime,this.maxMoveDeltaTime),this.savedMoves.push(o),this.sendSavedMoves(t,s)}tickAuthority(t,e){const i=this.state.mode,o=this.createMoveFromInput(t,++this.nextMoveSequence);this.performMove(o,_t),this.resetToggleCrouchAfterSlide(i),e!==dt.none&&this.sendSimulatedState(t,!1)}resetToggleCrouchAfterSlide(t){t===A.sliding&&this.state.mode!==A.sliding&&"toggle"===this.crouchInput.mode&&this.crouchInput.activated&&this.crouchInput.setActivated(!1)}tickRemoteAuthority(t){_(this.serverMoveTiming,t,this.maxServerMoveTimeBudget);let e=!1;const i=Number.isFinite(this.maxServerMovesPerTick)?Math.max(1,Math.floor(this.maxServerMovesPerTick)):this.serverMoveQueue.length,o=Math.min(this.serverMoveQueue.length,i),s=Ut.copy(this.actor.position);let n=!1;for(let t=0;t<o;t++){const t=this.serverMoveQueue.shift();if(null==t)break;if(!ut(t,this.lastServerProcessedSequence,this.maxMoveDeltaTime)){console.log("Net: Invalid move",t),this.sendOwnerCorrection(!0),e=!0;continue}const i=it(this.serverMoveTiming,t,{maxMoveDeltaTime:this.maxMoveDeltaTime,maxServerMoveDeltaTimeScalar:this.maxServerMoveDeltaTimeScalar,maxClientTimeAhead:this.maxClientTimeAhead});if(i<0){this.sendOwnerCorrection(!0),e=!0;continue}const o=Wt(t,this.authoritativeMoveScratch);o.dt=i,o.rootMotionX=0,o.rootMotionY=0,o.rootMotionZ=0,o.flags&=~B,this.performMove(o,{immediate:!0,savedRootMotion:!1}),n=!0,this.lastServerProcessedSequence=o.sequence;const s=$t(this.state,t);if(s>this.correctionToleranceSq){console.log(`Net server: Correction error: ${Math.sqrt(s)}`);const o=this.state.position.x-t.clientX,n=this.state.position.y-t.clientY,r=this.state.position.z-t.clientZ;console.log(`diff x: ${o}, y: ${n}, z: ${r}`),console.log({sequence:t.sequence,moveDt:t.dt,serverMoveDeltaTime:i,flags:t.flags,mode:this.state.mode,grounded:this.state.grounded,fallGraceTime:this.state.fallGraceTime}),this.sendOwnerCorrection(s>this.largeCorrectionThreshold*this.largeCorrectionThreshold),e=!0}}0===this.lastServerProcessedSequence||e||(this.sprintPolicy?.ack?.(this.lastServerProcessedSequence,!1),this.clientMoveAck(ht(this.lastServerProcessedSequence))),n&&this.accumulateListenServerVisualSmoothing(s,this.actor.position),this.sendSimulatedState(t,!1)}tickSimulatedProxy(t){this.proxyTime+=t,this.proxySmoother.sample(this.proxyTime,this.proxySample)&&this.applySnapshot(this.proxySample,!0)}accumulateListenServerVisualSmoothing(t,e){if(!this.shouldSmoothListenServerRemoteAuthority())return void this.visualSmoothingOffset.set(0,0,0);Xt.subVectors(t,e);const i=Xt.lengthSq();i>1e-8&&(i>this.listenServerNoSmoothUpdateDistance*this.listenServerNoSmoothUpdateDistance?this.visualSmoothingOffset.set(0,0,0):(i>this.listenServerMaxSmoothUpdateDistance*this.listenServerMaxSmoothUpdateDistance&&Xt.setLength(this.listenServerMaxSmoothUpdateDistance),this.visualSmoothingOffset.add(Xt)))}updateVisualSmoothing(t){if(this.visualSmoothingOffset.lengthSq()<=1e-8)return void this.visualSmoothingOffset.set(0,0,0);if(!this.shouldSmoothListenServerRemoteAuthority())return void this.visualSmoothingOffset.set(0,0,0);const e=Math.max(.001,this.listenServerSmoothLocationTime);t<e?this.visualSmoothingOffset.multiplyScalar(1-t/e):this.visualSmoothingOffset.set(0,0,0),this.visualSmoothingOffset.lengthSq()<=1e-4&&this.visualSmoothingOffset.set(0,0,0)}shouldSmoothListenServerRemoteAuthority(){return this.listenServerSmoothing&&this.actor.netRole===m.authority&&this.netService.isServer&&!this.netService.isDedicatedServer&&this.isRemoteControlledAuthority()}createMoveFromInput(t,e,i={}){const o=r.clamp(t,.001,this.maxMoveDeltaTime);this.clientMoveTime+=o;let s=this.clientMoveTime,n=o;!0===i.quantizeClientTime&&(s=Math.max(this.lastSentClientMoveTime+.001,Math.round(1e3*this.clientMoveTime)/1e3),n=r.clamp(s-this.lastSentClientMoveTime,.001,this.maxMoveDeltaTime),this.lastSentClientMoveTime=s),this.sampleRootMotion(At);const a=this.crouchInput.activated,h=a&&!this.previousCrouchInput;this.previousCrouchInput=a;const l=!a&&this.sprintInput.activated,c=l&&!this.previousSprintInput;this.previousSprintInput=l;const u=(this.jumpInput.activated?L:0)|(l?Z:0)|(a?E:0)|(h&&this.slideEnabled?H:0)|(c?W:0)|(At.lengthSq()>0?B:0),d=function(t,e){e.set(t.x,0,t.y),e.lengthSq()>1&&e.normalize();return e}(this.directionInput.vector,Nt),p=this.inputMoveScratch;return p.sequence=e>>>0,p.clientTime=s,p.dt=n,p.inputX=d.x,p.inputY=d.z,p.yaw=this.rotationInput.rotation.y,p.flags=u,p.clientX=this.state.position.x,p.clientY=this.state.position.y,p.clientZ=this.state.position.z,p.rootMotionX=At.x,p.rootMotionY=At.y,p.rootMotionZ=At.z,p}performMove(t,e){const i=r.clamp(t.dt,.001,this.maxMoveDeltaTime),o=Math.max(1,Math.ceil(i/this.maxSubstepDeltaTime)),s=0!==(t.flags&Z)&&0===(t.flags&E);this.sprintPolicy?.update?.(i,t.sequence,s),It.set(e.savedRootMotion?t.rootMotionX:0,e.savedRootMotion?t.rootMotionY:0,e.savedRootMotion?t.rootMotionZ:0),e.savedRootMotion||this.sampleRootMotion(It);let n=i;const a=i/o;for(let s=0;s<o;s++){const o=i>0?a/i:1;this.performSubstep(t,Math.min(a,n),It,o,e.immediate,0===s),n-=a}t.clientX=this.state.position.x,t.clientY=this.state.position.y,t.clientZ=this.state.position.z,t.flags=It.lengthSq()>0?t.flags|B:t.flags&~B,this.state.sequence=t.sequence,this.syncPublicState()}performSubstep(t,e,i,o,s,n){if(e<.001)return;this.checkGrounded(this.state.position),this.state.grounded=this.isGrounded;const r=null!=this.rootMotionAction&&this.rootMotionAction.enabled,a=i.lengthSq()>0,h=!r&&0!==(t.flags&L),l=r||a;this.updateCrouchState(t,n,l,h),this.pressedJump=h,this.isSprinting=!1,this.updateRotation(t,e,r,a),this.resolvePlatformVelocity(Ct);const c=this.movementModeContext,u=this.movementModes.get(this.state.mode);if(null!=u){c.move=t,c.deltaTime=e,c.rootMotionActive=l,c.startedSprinting=n&&!l&&0===(t.flags&E)&&0!==(t.flags&W);const i=u.update(c);"number"==typeof i&&(this.state.mode=i)}else Tt.set(0,0,0);if(a){qt.copy(i).multiplyScalar(o).applyQuaternion(this.actor.quaternion),Dt.copy(qt).divideScalar(e),this.state.mode===A.walking?(Tt.x=Dt.x+Ct.x,Tt.z=Dt.z+Ct.z):(Tt.x=Dt.x,Tt.z=Dt.z);const t=Math.sqrt(Dt.x*Dt.x+Dt.z*Dt.z);t>.4&&(this.state.currentSpeed=t)}if(this.applyImpulseToVelocity(Tt,e),h&&this.isSprinting){const t=Math.max(0,this.maxSpeedSprint),e=Zt(Tt);if(e>t){const i=t/e;Tt.x*=i,Tt.z*=i,this.state.velocity.x*=i,this.state.velocity.z*=i}}this.state.mode===A.walking&&this.state.velocity.copy(Tt),this.applyMovement(Tt,e,s),this.state.mode===A.sliding&&(St(this.state.velocity,wt,Ct,this.slideSurfaceNormal,e),this.state.currentSpeed=Zt(this.state.velocity)),this.checkGrounded(this.state.position),this.state.grounded=this.isGrounded,this.updateModeAfterMove(Tt,e),this.state.mode===A.sliding&&this.state.velocity.length()<Math.max(0,this.slideMinExitSpeed)&&(this.state.mode=A.walking)}updateRotation(t,e,i,o){ft.set(-t.inputX,0,t.inputY),ft.lengthSq()>1&&ft.normalize();const s=this.state.prevRotateToMovementDirection!==this.rotateToMovementDirection;let n=r.euclideanModulo(t.yaw-this.state.lookYaw+Math.PI,2*Math.PI)-Math.PI;if(s&&(this.actor.object.quaternion.setFromEuler(Ft.set(0,t.yaw,0)),this.state.prevRotateToMovementDirection||(n=0,this.state.lookYaw=t.yaw),this.state.prevRotateToMovementDirection=this.rotateToMovementDirection),xt.set(0,0,0),i)this.state.lookYaw=t.yaw;else if(this.rotateToMovementDirection){if(ft.lengthSq()>0&&this.state.mode!==A.falling){const i=Ft.setFromQuaternion(this.actor.object.quaternion,"YXZ").y,o=Math.atan2(ft.x,ft.z),s=.99*t.yaw+o;if(this.smoothRotation){const t=r.euclideanModulo(s-i+Math.PI,2*Math.PI)-Math.PI;let o=r.clamp(t*this.rotationSpeed*e,-this.maxRotationSpeed*e,this.maxRotationSpeed*e);Math.abs(o)>Math.abs(t)&&(o=t),this.actor.object.quaternion.setFromEuler(Ft.set(0,i+o,0))}else this.actor.object.quaternion.setFromEuler(Ft.set(0,s,0));this.state.prevInputDirection.lerp(ft,e*this.rotationSpeed),this.state.lookYaw+=n,xt.copy(this.actor.object.getWorldDirection(Nt).normalize())}}else o||(this.state.lookYaw+=n,this.actor.object.quaternion.multiply(Yt.setFromEuler(Ft.set(0,n,0))),ft.lengthSq()>0&&xt.copy(ft).applyQuaternion(this.actor.object.quaternion).normalize())}applyMovement(t,e,i){if(t.lengthSq()>0||!this.state.grounded){if(Rt.copy(t).multiplyScalar(e),this.state.grounded&&((o=this.state.mode)===A.walking||o===A.sliding)&&(this.state.mode===A.walking&&this.rayTestResult.distance<=this.cc.offset()&&(Rt.y=Math.max(0,Ct.y*e)),this.physicsSystem.getActorComputedMovement(this.actor,this.cc,Rt,this.getCollisionGroup()),this.cc.computedCollision(0,Et),null!=Et.normal1)){const t=Nt.copy(Et.normal1);Math.acos(r.clamp(t.dot(Mt),-1,1))>this.cc.maxSlopeClimbAngle()&&(Rt.y=.016*this.getEffectiveGravity()*.5)}wt.copy(this.physicsSystem.getActorComputedMovement(this.actor,this.cc,Rt,this.getCollisionGroup()))}else wt.set(0,0,0);var o;this.suppressUncrouchLift&&(this.suppressUncrouchLift=!1,this.state.grounded&&this.state.mode===A.walking&&Rt.y<=1e-6&&wt.y>0&&(wt.y=0)),this.state.position.add(wt),i?(this.actor.position.copy(this.state.position),this.physicsSystem.updateActorTransform(this.actor),this.physicsSystem.flushModifiedBodyPositionsToColliders()):this.physicsSystem.setNextKinematicPosition(this.actor,this.state.position)}updateModeAfterMove(t,e){const i=function(t){if(0===t.numComputedCollisions())return!1;const e=t.computedCollision(0);Gt.set(e.normal2.x,e.normal2.y,e.normal2.z);const i=Gt.angleTo(Mt);Gt.set(e.normal1.x,e.normal1.y,e.normal1.z);const o=Gt.angleTo(Mt);if(i<100)return!1;return o>t.minSlopeSlideAngle()}(this.cc);!this.state.grounded||i?this.state.mode!==A.falling&&(this.state.fallGraceTime+=e,this.state.fallGraceTime>this.fallGraceTime+1e-6&&(this.state.mode=A.falling,this.state.velocity.copy(t))):this.state.velocity.y<=0&&(this.state.mode===A.falling&&(this.state.mode=A.walking),this.state.mode!==A.sliding&&(this.state.velocity.y=0),this.state.fallGraceTime=0)}applyImpulseToVelocity(t,e){if(this.impulse.lengthSq()<=.1)return void this.impulse.set(0,0,0);const i=Math.min(1,this.impulse.length()/5);t.x=r.lerp(t.x,this.impulse.x,i),t.z=r.lerp(t.z,this.impulse.z,i),t.y+=this.impulse.y;const o=Math.exp(-this.impulseDamping*e);this.impulse.x*=o,this.impulse.y>0?this.impulse.y+=e*this.getEffectiveGravity():this.impulse.y*=o,this.impulse.z*=o}sendSavedMoves(t,e=!1){if(this.moveSendAccumulator+=t,!e&&this.moveSendAccumulator<this.moveSendInterval)return;this.moveSendAccumulator=0;const i=this.savedMoves.getMovesForSend(this.maxMovesPerPacket);0!==i.length&&this.serverMove(at(i))}sendOwnerCorrection(t){const e=this.toSnapshot(this.pendingSnapshot);t&&(e.horizontalSpeed=this.horizontalSpeed),this.sprintPolicy?.ack?.(e.sequence,!0),this.clientMoveCorrection(lt(e))}sendSimulatedState(t,e){this.simulatedStateAccumulator+=t,!e&&this.simulatedStateAccumulator<this.simulatedStateInterval||(this.simulatedStateAccumulator=0,this.simulatedState(ct(this.toSnapshot(this.pendingSnapshot))))}applyCorrection(t){this.sprintPolicy?.restore?.(t.sequence),this.savedMoves.ack(t.sequence),this.sprintPolicy?.ack?.(t.sequence,!0),this.applySnapshot(t,!0),this.savedMoves.replayAfter(t.sequence,t=>(this.performMove(t,{immediate:!0,savedRootMotion:!0}),null),this.maxReplayedMoves)}applySnapshot(t,e){this.state.sequence=t.sequence,this.state.position.set(t.x,t.y,t.z),this.state.velocity.set(t.velocityX,t.velocityY,t.velocityZ),this.state.yaw=t.yaw,this.state.lookYaw=t.yaw,this.state.mode=t.mode,this.state.currentSpeed=t.horizontalSpeed,this.state.fallGraceTime=0,this.actor.position.copy(this.state.position),this.actor.object.quaternion.setFromEuler(Ft.set(0,t.yaw,0)),this.crouchSuppressedUntilRelease=0!==(t.flags&$),this.setCrouching(0!==(t.flags&Q)||t.mode===A.sliding),e&&(this.physicsSystem.updateActorTransform(this.actor),this.physicsSystem.flushModifiedBodyPositionsToColliders()),this.checkGrounded(this.state.position),this.state.grounded=this.isGrounded,this.syncPublicState()}toSnapshot(t){return t.sequence=this.state.sequence,t.x=this.state.position.x,t.y=this.state.position.y,t.z=this.state.position.z,t.velocityX=this.state.velocity.x,t.velocityY=this.state.velocity.y,t.velocityZ=this.state.velocity.z,t.yaw=Ft.setFromQuaternion(this.actor.object.quaternion,"YXZ").y,t.mode=this.state.mode,t.flags=(this.isCrouching?Q:0)|(this.crouchSuppressedUntilRelease?$:0),t.horizontalSpeed=this.state.currentSpeed,t}syncPublicState(){this.velocity.copy(this.state.velocity),this.mode=this.state.mode,this.horizontalSpeed=this.state.currentSpeed,this.isSliding=this.state.mode===A.sliding,this.isSliding?(this.resolveGroundNormal(this.slideSurfaceNormal),this.slideDirection.copy(this.state.velocity).projectOnPlane(this.slideSurfaceNormal),this.slideDirection.lengthSq()>1e-8?this.slideDirection.normalize():this.slideDirection.set(0,0,0)):(this.slideDirection.set(0,0,0),this.slideSurfaceNormal.copy(Mt))}sampleRootMotion(t){if(t.set(0,0,0),null==this.rootMotionAction||this.rootMotionAction.isRunning()||this.clearRootMotionAction(this.rootMotionAction),null!=this.rootMotionAction&&this.rootMotionOptions.cancelWithJump&&this.jumpInput.activated&&(this.isGrounded||this.jumpInAir)){const e=this.rootMotionAction,i=this.rootMotionOptions.onJumpCancel;return this.clearRootMotionAction(e),e.stop(),i?.(),t}if(null==this.rootMotionAction)return t;if(!(this.rootMotionAction.getClip()instanceof l))return t;const e=this.rootMotionInterpolant;this.resetRootMotion&&(this.prevRootMotionPos.fromArray(e.evaluate(0)),this.resetRootMotion=!1),kt.fromArray(e.evaluate(this.rootMotionAction.time)),t.subVectors(kt,this.prevRootMotionPos),this.prevRootMotionPos.copy(kt);return(this.rootMotionRootBone??this.rootMotionAction.getRoot()).getWorldScale(bt),t.multiply(bt),t}clearRootMotionAction(t){null!=t&&this.rootMotionAction!==t||(this.rootMotionAction=null,this.rootMotionOptions={},this.resetRootMotion=!1)}isRemoteControlledAuthority(t=this.netService.mode,e=this.actor.netRole){if(t===dt.none||e!==m.authority||t>=dt.client)return!1;return null!=this.netService.resolveActorConnection(this.actor)&&!this.netService.isLocalOwner(this.actor)}configureCharacterController(){const t=this.cc;t.setApplyImpulsesToDynamicBodies(this.applyImpulsesToDynamicBodies),t.setMinSlopeSlideAngle(this.minSlopeSlideAngle),t.setMaxSlopeClimbAngle(this.maxSlopeClimbAngle),t.setCharacterMass(this.mass),t.setSlideEnabled(this.allowSliding)}initializeStateFromActor(){this.state.position.copy(this.actor.position),this.state.velocity.set(0,0,0),this.state.yaw=this.actor.rotation.y,this.state.lookYaw=this.rotationInput.rotation.y,this.state.mode=this.mode,this.state.currentSpeed=this.horizontalSpeed,this.state.prevRotateToMovementDirection=this.rotateToMovementDirection}createCollisionShape(){const t=this.getColliderHeight(!1),e=this.getColliderRadius(!1),i=new x(t,e);return i.offset.y=this.getCapsuleOffsetY(t,e),i.collisionGroup=gt,i}updateCrouchState(t,e,i,o){if(!(0!==(t.flags&E)))return this.crouchSuppressedUntilRelease=!1,this.slideOnLandingRequested=!1,this.state.mode===A.sliding&&(this.state.mode=A.walking),void this.tryUncrouch();if(this.state.mode===A.sliding&&(!this.slideEnabled||i))return this.slideOnLandingRequested=!1,this.state.mode=A.walking,void(this.crouchSuppressedUntilRelease||this.setCrouching(!0));if(this.state.mode===A.sliding&&o)return this.crouchSuppressedUntilRelease=!0,this.slideOnLandingRequested=!1,void this.tryUncrouch();if(this.crouchSuppressedUntilRelease)return void(this.slideOnLandingRequested=!1);if(this.setCrouching(!0),!this.slideEnabled||i)return void(this.slideOnLandingRequested=!1);if(this.state.mode===A.falling)return void(this.slideOnLandingRequested=!0);this.resolveGroundNormal(Vt);const s=this.slideOnLandingRequested&&this.state.mode===A.walking&&this.state.grounded,n=e&&0!==(t.flags&H)||s;s&&(this.slideOnLandingRequested=!1);const r=Zt(this.state.velocity);this.state.mode===A.walking&&vt(this.slideEnabled,n,this.state.grounded,this.isWalkableSlideSurface(Vt),i,r,this.slideMinStartSpeed)&&(this.state.mode=A.sliding,this.slideSurfaceNormal.copy(Vt),this.state.velocity.projectOnPlane(this.slideSurfaceNormal),this.state.currentSpeed=Zt(this.state.velocity))}updateSlidingMode(t){const e=t.state,i=t.move;this.resolveGroundNormal(this.slideSurfaceNormal);const o=this.isWalkableSlideSurface(this.slideSurfaceNormal),s=e.velocity.length();if(!e.grounded||!o)return e.mode=A.falling,Ht.update(t),A.falling;if(this.slideEnabled&&0!==(i.flags&E)&&!t.rootMotionActive&&0!==(i.flags&L))return pt(t.outVelocity,e.velocity,this.jumpVelocity),e.velocity.copy(t.outVelocity),e.currentSpeed=Zt(e.velocity),A.falling;if(!mt(this.slideEnabled,0!==(i.flags&E),e.grounded,o,t.rootMotionActive,s,this.slideMinExitSpeed))return e.mode=A.walking,Bt.update(t),A.walking;const n=yt(e.velocity,e.velocity,this.slideSurfaceNormal,t.rotatedDirection,this.getEffectiveGravity(),t.deltaTime,this.slideDeceleration,this.slideGravityScale,this.slideSteeringRate);if(e.currentSpeed=Zt(e.velocity),n<Math.max(0,this.slideMinExitSpeed))return e.mode=A.walking,Bt.update(t),A.walking;t.outVelocity.copy(e.velocity).add(t.platformVelocity)}tryUncrouch(){this.isCrouching&&this.canUncrouch()&&this.setCrouching(!1)&&(this.suppressUncrouchLift=!0,this.state.fallGraceTime=0)}resolveGroundNormal(t){return!this.rayTestResult.hasHit||this.rayTestResult.hitNormal.lengthSq()<=1e-8?t.copy(Mt):(t.copy(this.rayTestResult.hitNormal).normalize(),t.dot(Mt)<0&&t.multiplyScalar(-1),t)}isWalkableSlideSurface(t){return t.dot(Mt)>=Math.cos(this.cc.maxSlopeClimbAngle())}setCrouching(t){return this.isCrouching!==t&&(this.isCrouching=t,this.syncColliderShape(),!0)}canUncrouch(){const t=this.getColliderHeight(!1),e=this.getColliderRadius(!1);return!this.physicsSystem.hasActorCapsuleIntersection(this.actor,this.state.position,t,e,this.getCapsuleOffsetY(t,e),this.getCollisionGroup())}syncColliderShape(){const t=this.getColliderHeight(this.isCrouching),e=this.getColliderRadius(this.isCrouching);this.physicsSystem.setActorCapsuleCollider(this.actor,t,e,this.getCapsuleOffsetY(t,e))}getColliderHeight(t){const e=Number.isFinite(this.colliderHeight)?Math.max(0,this.colliderHeight):0;if(!t)return e;const i=Number.isFinite(this.crouchColliderHeight)?this.crouchColliderHeight:e;return r.clamp(i,0,e)}getColliderRadius(t){const e=Number.isFinite(this.colliderRadius)?Math.max(.001,this.colliderRadius):.001;if(!t)return e;const i=this.crouchColliderRadius??e,o=Number.isFinite(i)?i:e;return r.clamp(o,.001,e)}getCapsuleOffsetY(t,e){return e+t/2+this.offset}checkGrounded(t){jt.y=-Math.max(.05,this.cc.snapToGroundDistance()),this.physicsSystem.rayTest(zt.addVectors(t,Ot.set(0,this.offset,0)),Pt.addVectors(t,jt),this.rayTestResult,this.groundRayTestOptions)}resolvePlatformVelocity(t){return t.set(0,0,0),this.rayTestResult.hasHit&&null!=this.rayTestResult.actor&&this.physicsSystem.getLinearVelocity(this.rayTestResult.actor,t),t}getCollisionGroup(){return this.characterCollision?null:gt}};t([T(),e("design:type",Object)],Lt.prototype,"colliderHeight",void 0),t([T(),e("design:type",Object)],Lt.prototype,"colliderRadius",void 0),t([T(),e("design:type",Object)],Lt.prototype,"crouchColliderHeight",void 0),t([T(),e("design:type",Number)],Lt.prototype,"crouchColliderRadius",void 0),t([S(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Lt.prototype,"serverMove",null),t([v(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Lt.prototype,"clientMoveAck",null),t([v(!0),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Lt.prototype,"clientMoveCorrection",null),t([y(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Lt.prototype,"simulatedState",null),Lt=t([w({inEditor:!1}),e("design:paramtypes",[])],Lt);export{Lt as CharacterMovementComponent};const Bt={mode:A.walking,update(t){const e=t.component,i=t.move,o=t.state,s=t.rotatedDirection,n=Math.min(1,Math.sqrt(i.inputX*i.inputX+i.inputY*i.inputY)),r=!e.rotateToMovementDirection&&i.inputY<0,a=e.isCrouching,h=!t.rootMotionActive&&!a&&0===(i.flags&E)&&0!==(i.flags&Z)&&!r&&0!==s.lengthSq()&&(e.sprintPolicy?.canSprint()??!0),l=(a?e.maxSpeedCrouch:r?e.maxSpeedBackwards:h?e.maxSpeedSprint:e.maxSpeed)*(e.normalizedDirection?1:n);if(0!==s.lengthSq()){e.isSprinting=h,h&&e.sprintPolicy?.commitSprint(t.deltaTime,i.sequence);let a=Math.min(l,o.currentSpeed),c=e.groundAccelerationRate;if(h&&t.startedSprinting&&e.sprintStartBoostSpeed>0){const t=e.normalizedDirection?1:n;a=Math.max(a,l+e.sprintStartBoostSpeed*t),c=e.sprintStartBoostDamping}else h&&!r&&e.sprintStartBoostSpeed>0&&o.currentSpeed>l&&(a=o.currentSpeed,c=e.sprintStartBoostDamping);o.currentSpeed=function(t,e,i,o){return e+(t-e)*Math.exp(-i*o)}(a,l,c,t.deltaTime),t.outVelocity.copy(s).multiplyScalar(function(t,e,i,o){const s=i*o;if(s<=1e-6)return t;return e+(t-e)*(1-Math.exp(-s))/s}(a,l,c,t.deltaTime))}else o.currentSpeed=0,t.outVelocity.set(0,0,0);if(0!==(i.flags&L))return o.mode=A.falling,o.velocity.copy(t.outVelocity),o.velocity.y=e.jumpVelocity,A.falling;t.outVelocity.y=t.deltaTime*e.getEffectiveGravity(),t.outVelocity.add(t.platformVelocity)}},Ht={mode:A.falling,update(t){const e=t.component,i=t.state,o=t.move;0!==(o.flags&L)&&e.jumpInAir&&(i.velocity.copy(t.outVelocity),i.velocity.y=e.jumpVelocity),i.velocity.y+=t.deltaTime*e.getEffectiveGravity(),t.outVelocity.copy(i.velocity),t.outVelocity.addScaledVector(t.rotatedDirection,e.fallingMovementControl),e.fallingReorientation&&t.outVelocity.applyAxisAngle(Mt,r.euclideanModulo(o.yaw-i.lookYaw+Math.PI,2*Math.PI)-Math.PI)}};function Zt(t){return Math.sqrt(t.x*t.x+t.z*t.z)}function Wt(t,e){return e.sequence=t.sequence,e.clientTime=t.clientTime,e.dt=t.dt,e.inputX=t.inputX,e.inputY=t.inputY,e.yaw=t.yaw,e.flags=t.flags,e.clientX=t.clientX,e.clientY=t.clientY,e.clientZ=t.clientZ,e.rootMotionX=t.rootMotionX,e.rootMotionY=t.rootMotionY,e.rootMotionZ=t.rootMotionZ,e}function $t(t,e){const i=t.position.x-e.clientX,o=t.position.y-e.clientY,s=t.position.z-e.clientZ;return i*i+o*o+s*s}class Qt{constructor(t){this.scene=t,this.serverPosition=new h,this.direction=new h}update(t,e){const i=this.serverPosition.set(e.x,e.y,e.z),o=i.distanceTo(t);o>.1&&console.log(`Correction applied. Error: ${o.toFixed(3)}. Server position: (${i.x.toFixed(2)}, ${i.y.toFixed(2)}, ${i.z.toFixed(2)}), Client position: (${t.x.toFixed(2)}, ${t.y.toFixed(2)}, ${t.z.toFixed(2)})`);const s=this.direction.copy(i).sub(t).normalize();Jt.position.copy(t),Jt.setDirection(s),Jt.setLength(o);const n=Kt(this.scene);n.add(Jt),setTimeout(()=>{n.remove(Jt)},1e3)}}const Jt=new n(new h(0,1,0),new h,1,16711680);function Kt(t){return null==t.parent?t:Kt(t.parent)}const _t={immediate:!1,savedRootMotion:!0};/*
1
+ import{__decorate as t,__metadata as e}from"tslib";import i from"@dimforge/rapier3d-simd-compat";import{takeUntil as o}from"rxjs";import*as s from"three";import{ArrowHelper as n,MathUtils as r,Quaternion as a,Vector3 as h}from"three";import{RootMotionClip as l}from"../../../../animation/root-motion.js";import{inject as c}from"../../../../inject.js";import{ActionInput as u,AxisInput as d,RotationInput as p}from"../../../../input/index.js";import{NetRole as m}from"../../../../net/service/net-actor-role.js";import{RunOnClient as v,RunOnNotOwner as y,RunOnServer as S}from"../../../../net/service/rpc-decorator.js";import{NetService as g}from"../../../../net/service/net-service.js";import{PhysicsSystem as M,RayTestResult as f}from"../../../../services/physics/physics-system.js";import{CapsuleCollisionShape as x}from"../../../../../scene/collision/collision-shape.js";import{Parameter as T}from"../../../../../shader/parameter.js";import{PhysicsBodyType as C}from"../../../../services/physics/physics-system.js";import{ActorComponent as R,Component as w}from"../../../component.js";import{CharacterMovementMode as A}from"./modes.js";import{DEFAULT_MAX_CLIENT_TIME_AHEAD as q,DEFAULT_LARGE_CORRECTION_THRESHOLD as D,DEFAULT_MAX_COMBINED_MOVE_DELTA_TIME as b,DEFAULT_MAX_MOVE_DELTA_TIME as k,DEFAULT_MAX_MOVES_PER_PACKET as I,DEFAULT_MAX_REPLAYED_MOVES as z,DEFAULT_MAX_SERVER_MOVES_PER_TICK as P,DEFAULT_MAX_SAVED_MOVES as O,DEFAULT_MAX_SERVER_MOVE_DELTA_TIME_SCALAR as j,DEFAULT_MAX_SERVER_MOVE_TIME_BUDGET as G,DEFAULT_MAX_SUBSTEP_DELTA_TIME as Y,DEFAULT_MOVE_SEND_INTERVAL as N,DEFAULT_SIMULATED_INTERPOLATION_DELAY as F,DEFAULT_SIMULATED_STATE_INTERVAL as V,DEFAULT_SMALL_CORRECTION_TOLERANCE as U,DEFAULT_TELEPORT_SNAP_THRESHOLD as X,MOVE_FLAG_CROUCH as E,MOVE_FLAG_JUMP as L,MOVE_FLAG_ROOT_MOTION as B,MOVE_FLAG_SLIDE_START as H,MOVE_FLAG_SPRINT as Z,MOVE_FLAG_SPRINT_START as W,SNAPSHOT_FLAG_CROUCH_SUPPRESSED as $,SNAPSHOT_FLAG_CROUCHING as Q,NetCharacterProxySmoother as J,NetCharacterSavedMoveBuffer as K,accrueNetCharacterServerMoveTime as _,createNetCharacterMovementSnapshot as tt,createNetCharacterServerMoveTimingState as et,consumeNetCharacterServerMoveTime as it,decodeNetCharacterMoveBatch as ot,decodeNetCharacterOwnerAck as st,decodeNetCharacterOwnerCorrection as nt,decodeNetCharacterSimulatedState as rt,encodeNetCharacterMoveBatch as at,encodeNetCharacterOwnerAck as ht,encodeNetCharacterOwnerCorrection as lt,encodeNetCharacterSimulatedState as ct,validateNetCharacterMove as ut}from"./net-character-movement-protocol.js";import{NetMode as dt}from"../../../../net/net-session.js";import{setSlideJumpVelocity as pt,shouldContinueSlide as mt,shouldStartSlide as vt,updateSlideVelocity as yt,updateSlideVelocityFromDisplacement as St}from"./character-slide.js";export*from"./net-character-movement-protocol.js";const gt=131070,Mt=new h(0,1,0),ft=new h,xt=new h,Tt=new h,Ct=new h,Rt=new h,wt=new h,At=new h,qt=new h,Dt=new h,bt=new h,kt=new h,It=new h,zt=new h,Pt=new h,Ot=new h(0,1,0),jt=new h(0,-.05,0),Gt=new h,Yt=new a,Nt=new s.Euler,Ft=new h,Vt=new h,Ut=new h,Xt=new h,Et=new i.CharacterCollision;let Lt=class extends R{get autoStepMinWidth(){return this.cc.autostepMinWidth()}set autoStepMinWidth(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),t,this.cc.autostepIncludesDynamicBodies())}get autoStepDynamicObjects(){return this.cc.autostepIncludesDynamicBodies()}set autoStepDynamicObjects(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),this.cc.autostepMinWidth(),t)}get autoStepMaxHeight(){return this.cc.autostepMaxHeight()}set autoStepMaxHeight(t){this.cc.enableAutostep(t,this.cc.autostepMinWidth(),this.cc.autostepIncludesDynamicBodies())}get snapToGround(){return this.cc.snapToGroundDistance()}set snapToGround(t){this.cc.enableSnapToGround(t)}set offset(t){this.cc.setOffset(t)}get offset(){return this.cc.offset()}set normalNudgeFactor(t){this.cc.setNormalNudgeFactor(t)}get normalNudgeFactor(){return this.cc.normalNudgeFactor()}constructor(){super(),this.isDefaultCharacterMovementComponent=!0,this.directionInput=new d,this.jumpInput=new u,this.sprintInput=new u,this.crouchInput=new u,this.rotationInput=new p,this.horizontalSpeed=0,this.maxSpeed=8,this.maxSpeedBackwards=8,this.maxSpeedSprint=12,this.maxSpeedCrouch=4,this.slideEnabled=!1,this.slideMinStartSpeed=8,this.slideMinExitSpeed=4,this.slideDeceleration=3,this.slideGravityScale=1,this.slideSteeringRate=2,this.sprintStartBoostSpeed=0,this.sprintStartBoostDamping=6,this.jumpVelocity=7,this.fallingMovementControl=.5,this.fallingReorientation=!1,this.groundAccelerationRate=4,this.gravityOverride=null,this.colliderHeight=2,this.colliderRadius=.5,this.crouchColliderHeight=1,this.crouchColliderRadius=null,this.jumpInAir=!1,this.mass=50,this.allowSliding=!0,this.minSlopeSlideAngle=r.degToRad(70),this.maxSlopeClimbAngle=r.degToRad(70),this.applyImpulsesToDynamicBodies=!0,this.normalizedDirection=!0,this.characterCollision=!1,this.allowRootMotionJumpCancel=!1,this.enabled=!0,this.rotateToMovementDirection=!1,this.smoothRotation=!0,this.rotationSpeed=40,this.maxRotationSpeed=100,this.impulseDamping=2,this.moveSendInterval=N,this.simulatedStateInterval=V,this.maxSavedMoves=O,this.maxReplayedMoves=z,this.maxServerMovesPerTick=P,this.maxMovesPerPacket=I,this.maxMoveDeltaTime=k,this.maxCombinedMoveDeltaTime=b,this.maxServerMoveDeltaTimeScalar=j,this.maxClientTimeAhead=q,this.maxServerMoveTimeBudget=G,this.maxSubstepDeltaTime=Y,this.fallGraceTime=.1,this.correctionToleranceSq=U*U,this.largeCorrectionThreshold=D,this.teleportSnapThreshold=X,this.listenServerSmoothing=!0,this.listenServerSmoothLocationTime=.04,this.listenServerMaxSmoothUpdateDistance=1,this.listenServerNoSmoothUpdateDistance=2.5,this.debugCorrections=!0,this.suppressUncrouchLift=!1,this.velocity=new h,this.visualSmoothingOffset=new h,this.slideDirection=new h,this.slideSurfaceNormal=new h(0,1,0),this.mode=A.walking,this.isSprinting=!1,this.isCrouching=!1,this.isSliding=!1,this.pressedJump=!1,this.rayTestResult=new f,this.groundRayTestOptions={debug:!1,excludeTriggers:!0,excludeActor:void 0,resolveActor:!1},this.physicsSystem=c(M),this.netService=c(g),this.state={sequence:0,position:new h,velocity:new h,yaw:0,lookYaw:0,mode:A.walking,grounded:!1,currentSpeed:0,fallGraceTime:0,prevInputDirection:new h,prevRotateToMovementDirection:!1},this.movementModes=new Map,this.savedMoves=new K(O),this.serverMoveTiming=et(),this.serverMoveQueue=[],this.inputMoveScratch={sequence:0,clientTime:0,dt:0,inputX:0,inputY:0,yaw:0,flags:0,clientX:0,clientY:0,clientZ:0,rootMotionX:0,rootMotionY:0,rootMotionZ:0},this.authoritativeMoveScratch={sequence:0,clientTime:0,dt:0,inputX:0,inputY:0,yaw:0,flags:0,clientX:0,clientY:0,clientZ:0,rootMotionX:0,rootMotionY:0,rootMotionZ:0},this.movementModeContext={component:this,state:this.state,move:this.inputMoveScratch,deltaTime:0,rotatedDirection:xt,platformVelocity:Ct,outVelocity:Tt,rootMotionActive:!1,startedSprinting:!1},this.proxySmoother=new J(F,X),this.proxySample=tt(),this.pendingSnapshot=tt(),this.impulse=new h,this.prevRootMotionPos=new h,this.rootMotionOptions={},this.resetRootMotion=!1,this.nextMoveSequence=0,this.clientMoveTime=0,this.lastSentClientMoveTime=0,this.moveSendAccumulator=0,this.simulatedStateAccumulator=0,this.proxyTime=0,this.lastServerProcessedSequence=0,this.lastServerReceivedSequence=0,this.lastAutonomousMoveFlags=0,this.previousSprintInput=!1,this.previousCrouchInput=!1,this.crouchSuppressedUntilRelease=!1,this.slideOnLandingRequested=!1,this.initialized=!1,this.cc=this.physicsSystem.getCharacterController(.1),this.cc.enableSnapToGround(.1),this.cc.enableAutostep(0,.1,!1),this.registerMovementMode(Bt),this.registerMovementMode(Ht),this.registerMovementMode({mode:A.sliding,update:t=>this.updateSlidingMode(t)})}onInit(){this.groundRayTestOptions.excludeActor=this.actor,this.configureCharacterController(),this.physicsSystem.addActor(this.actor,[this.createCollisionShape()],{mass:0,type:C.kinematic,continousCollisionDetection:!1,friction:0,restitution:.5,ignoreForNavMesh:!0}),this.rotationInput.rotation.copy(this.actor.rotation),this.initializeStateFromActor(),this.initialized=!0,this.physicsSystem.beforeStep.pipe(o(this.disposed)).subscribe(t=>this.tick(t))}onLateUpdate(t){this.updateVisualSmoothing(t)}registerMovementMode(t){this.movementModes.set(t.mode,t)}applyImpulse(t){this.impulse.add(t)}getEffectiveGravity(){return this.gravityOverride??this.physicsSystem.getGravity().y}get isGrounded(){return this.rayTestResult.hasHit||this.cc.computedGrounded()}setRootMotionAction(t,e={}){const i=t?.getClip();if(i instanceof l){this.rootMotionAction=t,this.rootMotionOptions=e,this.resetRootMotion=!0;const o=[];this.rootMotionInterpolant=i.motionTrack.InterpolantFactoryMethodSmooth(o);const n=s.PropertyBinding.parseTrackName(i.motionTrack.name);this.rootMotionRootBone=this.actor.object.getObjectByName(n.nodeName)}}serverMove(t){const e=ot(t);if(e.ok)for(const t of e.value.moves)ut(t,this.lastServerReceivedSequence,this.maxMoveDeltaTime)&&(this.lastServerReceivedSequence=t.sequence,this.serverMoveQueue.push(t))}clientMoveAck(t){const e=st(t);e.ok&&this.actor.netRole===m.autonomousProxy&&(this.savedMoves.ack(e.value.sequence),this.sprintPolicy?.ack?.(e.value.sequence,!1))}clientMoveCorrection(t){const e=nt(t);e.ok&&this.actor.netRole===m.autonomousProxy&&(this.debugCorrections&&(null==this.correctionDebug&&(this.correctionDebug=new Qt(Kt(this.actor.object))),this.correctionDebug.update(this.state.position,e.value.snapshot)),this.applyCorrection(e.value.snapshot))}simulatedState(t){const e=rt(t);e.ok&&this.actor.netRole===m.simulatedProxy&&this.proxySmoother.push(e.value,this.proxyTime)}tick(t){if(!this.initialized)return;t=Math.min(.1,t);const e=this.actor.netRole,i=this.netService.mode;e!==m.simulatedProxy?this.enabled&&(e!==m.autonomousProxy?this.isRemoteControlledAuthority(i,e)?this.tickRemoteAuthority(t):this.tickAuthority(t,i):this.tickAutonomousProxy(t)):this.tickSimulatedProxy(t)}tickAutonomousProxy(t){const e=this.state.mode,i=this.lastAutonomousMoveFlags,o=this.createMoveFromInput(t,++this.nextMoveSequence,{quantizeClientTime:!0});this.performMove(o,_t),this.resetToggleCrouchAfterSlide(e);const s=this.state.mode!==e||o.flags!==i;this.lastAutonomousMoveFlags=o.flags,this.savedMoves.capacity=this.maxSavedMoves,this.savedMoves.maxCombinedDeltaTime=Math.min(this.maxCombinedMoveDeltaTime,this.maxMoveDeltaTime),this.savedMoves.push(o),this.sendSavedMoves(t,s)}tickAuthority(t,e){const i=this.state.mode,o=this.createMoveFromInput(t,++this.nextMoveSequence);this.performMove(o,_t),this.resetToggleCrouchAfterSlide(i),e!==dt.none&&this.sendSimulatedState(t,!1)}resetToggleCrouchAfterSlide(t){t===A.sliding&&this.state.mode!==A.sliding&&"toggle"===this.crouchInput.mode&&this.crouchInput.activated&&this.crouchInput.setActivated(!1)}tickRemoteAuthority(t){_(this.serverMoveTiming,t,this.maxServerMoveTimeBudget);let e=!1;const i=Number.isFinite(this.maxServerMovesPerTick)?Math.max(1,Math.floor(this.maxServerMovesPerTick)):this.serverMoveQueue.length,o=Math.min(this.serverMoveQueue.length,i),s=Ut.copy(this.actor.position);let n=!1;for(let t=0;t<o;t++){const t=this.serverMoveQueue.shift();if(null==t)break;if(!ut(t,this.lastServerProcessedSequence,this.maxMoveDeltaTime)){console.log("Net: Invalid move",t),this.sendOwnerCorrection(!0),e=!0;continue}const i=it(this.serverMoveTiming,t,{maxMoveDeltaTime:this.maxMoveDeltaTime,maxServerMoveDeltaTimeScalar:this.maxServerMoveDeltaTimeScalar,maxClientTimeAhead:this.maxClientTimeAhead});if(i<0){this.sendOwnerCorrection(!0),e=!0;continue}const o=Wt(t,this.authoritativeMoveScratch);o.dt=i,o.rootMotionX=0,o.rootMotionY=0,o.rootMotionZ=0,o.flags&=~B,this.performMove(o,{immediate:!0,savedRootMotion:!1}),n=!0,this.lastServerProcessedSequence=o.sequence;const s=$t(this.state,t);if(s>this.correctionToleranceSq){console.log(`Net server: Correction error: ${Math.sqrt(s)}`);const o=this.state.position.x-t.clientX,n=this.state.position.y-t.clientY,r=this.state.position.z-t.clientZ;console.log(`diff x: ${o}, y: ${n}, z: ${r}`),console.log({sequence:t.sequence,moveDt:t.dt,serverMoveDeltaTime:i,flags:t.flags,mode:this.state.mode,grounded:this.state.grounded,fallGraceTime:this.state.fallGraceTime}),this.sendOwnerCorrection(s>this.largeCorrectionThreshold*this.largeCorrectionThreshold),e=!0}}0===this.lastServerProcessedSequence||e||(this.sprintPolicy?.ack?.(this.lastServerProcessedSequence,!1),this.clientMoveAck(ht(this.lastServerProcessedSequence))),n&&this.accumulateListenServerVisualSmoothing(s,this.actor.position),this.sendSimulatedState(t,!1)}tickSimulatedProxy(t){this.proxyTime+=t,this.proxySmoother.sample(this.proxyTime,this.proxySample)&&this.applySnapshot(this.proxySample,!0)}accumulateListenServerVisualSmoothing(t,e){if(!this.shouldSmoothListenServerRemoteAuthority())return void this.visualSmoothingOffset.set(0,0,0);Xt.subVectors(t,e);const i=Xt.lengthSq();i>1e-8&&(i>this.listenServerNoSmoothUpdateDistance*this.listenServerNoSmoothUpdateDistance?this.visualSmoothingOffset.set(0,0,0):(i>this.listenServerMaxSmoothUpdateDistance*this.listenServerMaxSmoothUpdateDistance&&Xt.setLength(this.listenServerMaxSmoothUpdateDistance),this.visualSmoothingOffset.add(Xt)))}updateVisualSmoothing(t){if(this.visualSmoothingOffset.lengthSq()<=1e-8)return void this.visualSmoothingOffset.set(0,0,0);if(!this.shouldSmoothListenServerRemoteAuthority())return void this.visualSmoothingOffset.set(0,0,0);const e=Math.max(.001,this.listenServerSmoothLocationTime);t<e?this.visualSmoothingOffset.multiplyScalar(1-t/e):this.visualSmoothingOffset.set(0,0,0),this.visualSmoothingOffset.lengthSq()<=1e-4&&this.visualSmoothingOffset.set(0,0,0)}shouldSmoothListenServerRemoteAuthority(){return this.listenServerSmoothing&&this.actor.netRole===m.authority&&this.netService.isServer&&!this.netService.isDedicatedServer&&this.isRemoteControlledAuthority()}createMoveFromInput(t,e,i={}){const o=r.clamp(t,.001,this.maxMoveDeltaTime);this.clientMoveTime+=o;let s=this.clientMoveTime,n=o;!0===i.quantizeClientTime&&(s=Math.max(this.lastSentClientMoveTime+.001,Math.round(1e3*this.clientMoveTime)/1e3),n=r.clamp(s-this.lastSentClientMoveTime,.001,this.maxMoveDeltaTime),this.lastSentClientMoveTime=s),this.sampleRootMotion(At);const a=this.crouchInput.activated,h=a&&!this.previousCrouchInput;this.previousCrouchInput=a;const l=!a&&this.sprintInput.activated,c=l&&!this.previousSprintInput;this.previousSprintInput=l;const u=(this.jumpInput.activated?L:0)|(l?Z:0)|(a?E:0)|(h&&this.slideEnabled?H:0)|(c?W:0)|(At.lengthSq()>0?B:0),d=function(t,e){e.set(t.x,0,t.y),e.lengthSq()>1&&e.normalize();return e}(this.directionInput.vector,Ft),p=this.inputMoveScratch;return p.sequence=e>>>0,p.clientTime=s,p.dt=n,p.inputX=d.x,p.inputY=d.z,p.yaw=this.rotationInput.rotation.y,p.flags=u,p.clientX=this.state.position.x,p.clientY=this.state.position.y,p.clientZ=this.state.position.z,p.rootMotionX=At.x,p.rootMotionY=At.y,p.rootMotionZ=At.z,p}performMove(t,e){const i=r.clamp(t.dt,.001,this.maxMoveDeltaTime),o=Math.max(1,Math.ceil(i/this.maxSubstepDeltaTime)),s=0!==(t.flags&Z)&&0===(t.flags&E);this.sprintPolicy?.update?.(i,t.sequence,s),It.set(e.savedRootMotion?t.rootMotionX:0,e.savedRootMotion?t.rootMotionY:0,e.savedRootMotion?t.rootMotionZ:0),e.savedRootMotion||this.sampleRootMotion(It);let n=i;const a=i/o;for(let s=0;s<o;s++){const o=i>0?a/i:1;this.performSubstep(t,Math.min(a,n),It,o,e.immediate,0===s),n-=a}t.clientX=this.state.position.x,t.clientY=this.state.position.y,t.clientZ=this.state.position.z,t.flags=It.lengthSq()>0?t.flags|B:t.flags&~B,this.state.sequence=t.sequence,this.syncPublicState()}performSubstep(t,e,i,o,s,n){if(e<.001)return;this.checkGrounded(this.state.position),this.state.grounded=this.isGrounded;const r=null!=this.rootMotionAction&&this.rootMotionAction.enabled,a=i.lengthSq()>0,h=!r&&0!==(t.flags&L),l=r||a;this.updateCrouchState(t,n,l,h),this.pressedJump=h,this.isSprinting=!1,this.updateRotation(t,e,r,a),this.resolvePlatformVelocity(Ct);const c=this.movementModeContext,u=this.movementModes.get(this.state.mode);if(null!=u){c.move=t,c.deltaTime=e,c.rootMotionActive=l,c.startedSprinting=n&&!l&&0===(t.flags&E)&&0!==(t.flags&W);const i=u.update(c);"number"==typeof i&&(this.state.mode=i)}else Tt.set(0,0,0);if(a){qt.copy(i).multiplyScalar(o).applyQuaternion(this.actor.quaternion),Dt.copy(qt).divideScalar(e),this.state.mode===A.walking?(Tt.x=Dt.x+Ct.x,Tt.z=Dt.z+Ct.z):(Tt.x=Dt.x,Tt.z=Dt.z);const t=Math.sqrt(Dt.x*Dt.x+Dt.z*Dt.z);t>.4&&(this.state.currentSpeed=t)}if(this.applyImpulseToVelocity(Tt,e),h&&this.isSprinting){const t=Math.max(0,this.maxSpeedSprint),e=Zt(Tt);if(e>t){const i=t/e;Tt.x*=i,Tt.z*=i,this.state.velocity.x*=i,this.state.velocity.z*=i}}this.state.mode===A.walking&&this.state.velocity.copy(Tt),this.applyMovement(Tt,e,s),this.state.mode===A.sliding&&(St(this.state.velocity,wt,Ct,this.slideSurfaceNormal,e),this.state.currentSpeed=Zt(this.state.velocity)),this.checkGrounded(this.state.position),this.state.grounded=this.isGrounded,this.updateModeAfterMove(Tt,e),this.state.mode===A.sliding&&this.state.velocity.length()<Math.max(0,this.slideMinExitSpeed)&&(this.state.mode=A.walking)}updateRotation(t,e,i,o){ft.set(-t.inputX,0,t.inputY),ft.lengthSq()>1&&ft.normalize();const s=this.state.prevRotateToMovementDirection!==this.rotateToMovementDirection;let n=r.euclideanModulo(t.yaw-this.state.lookYaw+Math.PI,2*Math.PI)-Math.PI;if(s&&(this.actor.object.quaternion.setFromEuler(Nt.set(0,t.yaw,0)),this.state.prevRotateToMovementDirection||(n=0,this.state.lookYaw=t.yaw),this.state.prevRotateToMovementDirection=this.rotateToMovementDirection),xt.set(0,0,0),i)this.state.lookYaw=t.yaw;else if(this.rotateToMovementDirection){if(ft.lengthSq()>0&&this.state.mode!==A.falling){const i=Nt.setFromQuaternion(this.actor.object.quaternion,"YXZ").y,o=Math.atan2(ft.x,ft.z),s=.99*t.yaw+o;if(this.smoothRotation){const t=r.euclideanModulo(s-i+Math.PI,2*Math.PI)-Math.PI;let o=r.clamp(t*this.rotationSpeed*e,-this.maxRotationSpeed*e,this.maxRotationSpeed*e);Math.abs(o)>Math.abs(t)&&(o=t),this.actor.object.quaternion.setFromEuler(Nt.set(0,i+o,0))}else this.actor.object.quaternion.setFromEuler(Nt.set(0,s,0));this.state.prevInputDirection.lerp(ft,e*this.rotationSpeed),this.state.lookYaw+=n,xt.copy(this.actor.object.getWorldDirection(Ft).normalize())}}else o||(this.state.lookYaw+=n,this.actor.object.quaternion.multiply(Yt.setFromEuler(Nt.set(0,n,0))),ft.lengthSq()>0&&xt.copy(ft).applyQuaternion(this.actor.object.quaternion).normalize())}applyMovement(t,e,i){if(t.lengthSq()>0||!this.state.grounded){if(Rt.copy(t).multiplyScalar(e),this.state.grounded&&((o=this.state.mode)===A.walking||o===A.sliding)&&(this.state.mode===A.walking&&this.rayTestResult.distance<=this.cc.offset()&&(Rt.y=Math.max(0,Ct.y*e)),this.physicsSystem.getActorComputedMovement(this.actor,this.cc,Rt,this.getCollisionGroup()),this.cc.computedCollision(0,Et),null!=Et.normal1)){const t=Ft.copy(Et.normal1);Math.acos(r.clamp(t.dot(Mt),-1,1))>this.cc.maxSlopeClimbAngle()&&(Rt.y=.016*this.getEffectiveGravity()*.5)}wt.copy(this.physicsSystem.getActorComputedMovement(this.actor,this.cc,Rt,this.getCollisionGroup()))}else wt.set(0,0,0);var o;this.suppressUncrouchLift&&(this.suppressUncrouchLift=!1,this.state.grounded&&this.state.mode===A.walking&&Rt.y<=1e-6&&wt.y>0&&(wt.y=0)),this.state.position.add(wt),i?(this.actor.position.copy(this.state.position),this.physicsSystem.updateActorTransform(this.actor),this.physicsSystem.flushModifiedBodyPositionsToColliders()):this.physicsSystem.setNextKinematicPosition(this.actor,this.state.position)}updateModeAfterMove(t,e){const i=function(t){if(0===t.numComputedCollisions())return!1;const e=t.computedCollision(0);Gt.set(e.normal2.x,e.normal2.y,e.normal2.z);const i=Gt.angleTo(Mt);Gt.set(e.normal1.x,e.normal1.y,e.normal1.z);const o=Gt.angleTo(Mt);if(i<100)return!1;return o>t.minSlopeSlideAngle()}(this.cc);!this.state.grounded||i?this.state.mode!==A.falling&&(this.state.fallGraceTime+=e,this.state.fallGraceTime>this.fallGraceTime+1e-6&&(this.state.mode=A.falling,this.state.velocity.copy(t))):this.state.velocity.y<=0&&(this.state.mode===A.falling&&(this.state.mode=A.walking),this.state.mode!==A.sliding&&(this.state.velocity.y=0),this.state.fallGraceTime=0)}applyImpulseToVelocity(t,e){if(this.impulse.lengthSq()<=.1)return void this.impulse.set(0,0,0);const i=Math.min(1,this.impulse.length()/5);t.x=r.lerp(t.x,this.impulse.x,i),t.z=r.lerp(t.z,this.impulse.z,i),t.y+=this.impulse.y;const o=Math.exp(-this.impulseDamping*e);this.impulse.x*=o,this.impulse.y>0?this.impulse.y+=e*this.getEffectiveGravity():this.impulse.y*=o,this.impulse.z*=o}sendSavedMoves(t,e=!1){if(this.moveSendAccumulator+=t,!e&&this.moveSendAccumulator<this.moveSendInterval)return;this.moveSendAccumulator=0;const i=this.savedMoves.getMovesForSend(this.maxMovesPerPacket);0!==i.length&&this.serverMove(at(i))}sendOwnerCorrection(t){const e=this.toSnapshot(this.pendingSnapshot);t&&(e.horizontalSpeed=this.horizontalSpeed),this.sprintPolicy?.ack?.(e.sequence,!0),this.clientMoveCorrection(lt(e))}sendSimulatedState(t,e){this.simulatedStateAccumulator+=t,!e&&this.simulatedStateAccumulator<this.simulatedStateInterval||(this.simulatedStateAccumulator=0,this.simulatedState(ct(this.toSnapshot(this.pendingSnapshot))))}applyCorrection(t){this.sprintPolicy?.restore?.(t.sequence),this.savedMoves.ack(t.sequence),this.sprintPolicy?.ack?.(t.sequence,!0),this.applySnapshot(t,!0),this.savedMoves.replayAfter(t.sequence,t=>(this.performMove(t,{immediate:!0,savedRootMotion:!0}),null),this.maxReplayedMoves)}applySnapshot(t,e){this.state.sequence=t.sequence,this.state.position.set(t.x,t.y,t.z),this.state.velocity.set(t.velocityX,t.velocityY,t.velocityZ),this.state.yaw=t.yaw,this.state.lookYaw=t.yaw,this.state.mode=t.mode,this.state.currentSpeed=t.horizontalSpeed,this.state.fallGraceTime=0,this.actor.position.copy(this.state.position),this.actor.object.quaternion.setFromEuler(Nt.set(0,t.yaw,0)),this.crouchSuppressedUntilRelease=0!==(t.flags&$),this.setCrouching(0!==(t.flags&Q)||t.mode===A.sliding),e&&(this.physicsSystem.updateActorTransform(this.actor),this.physicsSystem.flushModifiedBodyPositionsToColliders()),this.checkGrounded(this.state.position),this.state.grounded=this.isGrounded,this.syncPublicState()}toSnapshot(t){return t.sequence=this.state.sequence,t.x=this.state.position.x,t.y=this.state.position.y,t.z=this.state.position.z,t.velocityX=this.state.velocity.x,t.velocityY=this.state.velocity.y,t.velocityZ=this.state.velocity.z,t.yaw=Nt.setFromQuaternion(this.actor.object.quaternion,"YXZ").y,t.mode=this.state.mode,t.flags=(this.isCrouching?Q:0)|(this.crouchSuppressedUntilRelease?$:0),t.horizontalSpeed=this.state.currentSpeed,t}syncPublicState(){this.velocity.copy(this.state.velocity),this.mode=this.state.mode,this.horizontalSpeed=this.state.currentSpeed,this.isSliding=this.state.mode===A.sliding,this.isSliding?(this.resolveGroundNormal(this.slideSurfaceNormal),this.slideDirection.copy(this.state.velocity).projectOnPlane(this.slideSurfaceNormal),this.slideDirection.lengthSq()>1e-8?this.slideDirection.normalize():this.slideDirection.set(0,0,0)):(this.slideDirection.set(0,0,0),this.slideSurfaceNormal.copy(Mt))}sampleRootMotion(t){if(t.set(0,0,0),null==this.rootMotionAction||this.rootMotionAction.isRunning()||this.clearRootMotionAction(this.rootMotionAction),null!=this.rootMotionAction&&this.rootMotionOptions.cancelWithJump&&this.jumpInput.activated&&(this.isGrounded||this.jumpInAir)){const e=this.rootMotionAction,i=this.rootMotionOptions.onJumpCancel;return this.clearRootMotionAction(e),e.stop(),i?.(),t}if(null==this.rootMotionAction)return t;if(!(this.rootMotionAction.getClip()instanceof l))return t;const e=this.rootMotionInterpolant;this.resetRootMotion&&(this.prevRootMotionPos.fromArray(e.evaluate(0)),this.resetRootMotion=!1),kt.fromArray(e.evaluate(this.rootMotionAction.time)),t.subVectors(kt,this.prevRootMotionPos),this.prevRootMotionPos.copy(kt);return(this.rootMotionRootBone??this.rootMotionAction.getRoot()).getWorldScale(bt),t.multiply(bt),t}clearRootMotionAction(t){null!=t&&this.rootMotionAction!==t||(this.rootMotionAction=null,this.rootMotionOptions={},this.resetRootMotion=!1)}isRemoteControlledAuthority(t=this.netService.mode,e=this.actor.netRole){if(t===dt.none||e!==m.authority||t>=dt.client)return!1;return null!=this.netService.resolveActorConnection(this.actor)&&!this.netService.isLocalOwner(this.actor)}configureCharacterController(){const t=this.cc;t.setApplyImpulsesToDynamicBodies(this.applyImpulsesToDynamicBodies),t.setMinSlopeSlideAngle(this.minSlopeSlideAngle),t.setMaxSlopeClimbAngle(this.maxSlopeClimbAngle),t.setCharacterMass(this.mass),t.setSlideEnabled(this.allowSliding)}initializeStateFromActor(){this.state.position.copy(this.actor.position),this.state.velocity.set(0,0,0),this.state.yaw=this.actor.rotation.y,this.state.lookYaw=this.rotationInput.rotation.y,this.state.mode=this.mode,this.state.currentSpeed=this.horizontalSpeed,this.state.prevRotateToMovementDirection=this.rotateToMovementDirection}createCollisionShape(){const t=this.getColliderHeight(!1),e=this.getColliderRadius(!1),i=new x(t,e);return i.offset.y=this.getCapsuleOffsetY(t,e),i.collisionGroup=gt,i}updateCrouchState(t,e,i,o){if(!(0!==(t.flags&E)))return this.crouchSuppressedUntilRelease=!1,this.slideOnLandingRequested=!1,this.state.mode===A.sliding&&(this.state.mode=A.walking),void this.tryUncrouch();if(this.state.mode===A.sliding&&(!this.slideEnabled||i))return this.slideOnLandingRequested=!1,this.state.mode=A.walking,void(this.crouchSuppressedUntilRelease||this.setCrouching(!0));if(this.state.mode===A.sliding&&o)return this.crouchSuppressedUntilRelease=!0,this.slideOnLandingRequested=!1,void this.tryUncrouch();if(this.crouchSuppressedUntilRelease)return void(this.slideOnLandingRequested=!1);if(this.setCrouching(!0),!this.slideEnabled||i)return void(this.slideOnLandingRequested=!1);if(this.state.mode===A.falling)return void(this.slideOnLandingRequested=!0);this.resolveGroundNormal(Vt);const s=this.slideOnLandingRequested&&this.state.mode===A.walking&&this.state.grounded,n=e&&0!==(t.flags&H)||s;s&&(this.slideOnLandingRequested=!1);const r=Zt(this.state.velocity);this.state.mode===A.walking&&vt(this.slideEnabled,n,this.state.grounded,this.isWalkableSlideSurface(Vt),i,r,this.slideMinStartSpeed)&&(this.state.mode=A.sliding,this.slideSurfaceNormal.copy(Vt),this.state.velocity.projectOnPlane(this.slideSurfaceNormal),this.state.currentSpeed=Zt(this.state.velocity))}updateSlidingMode(t){const e=t.state,i=t.move;this.resolveGroundNormal(this.slideSurfaceNormal);const o=this.isWalkableSlideSurface(this.slideSurfaceNormal),s=e.velocity.length();if(!e.grounded||!o)return e.mode=A.falling,Ht.update(t),A.falling;if(this.slideEnabled&&0!==(i.flags&E)&&!t.rootMotionActive&&0!==(i.flags&L))return pt(t.outVelocity,e.velocity,this.jumpVelocity),e.velocity.copy(t.outVelocity),e.currentSpeed=Zt(e.velocity),A.falling;if(!mt(this.slideEnabled,0!==(i.flags&E),e.grounded,o,t.rootMotionActive,s,this.slideMinExitSpeed))return e.mode=A.walking,Bt.update(t),A.walking;const n=yt(e.velocity,e.velocity,this.slideSurfaceNormal,t.rotatedDirection,this.getEffectiveGravity(),t.deltaTime,this.slideDeceleration,this.slideGravityScale,this.slideSteeringRate);if(e.currentSpeed=Zt(e.velocity),n<Math.max(0,this.slideMinExitSpeed))return e.mode=A.walking,Bt.update(t),A.walking;t.outVelocity.copy(e.velocity).add(t.platformVelocity)}tryUncrouch(){this.isCrouching&&this.canUncrouch()&&this.setCrouching(!1)&&(this.suppressUncrouchLift=!0,this.state.fallGraceTime=0)}resolveGroundNormal(t){return!this.rayTestResult.hasHit||this.rayTestResult.hitNormal.lengthSq()<=1e-8?t.copy(Mt):(t.copy(this.rayTestResult.hitNormal).normalize(),t.dot(Mt)<0&&t.multiplyScalar(-1),t)}isWalkableSlideSurface(t){return t.dot(Mt)>=Math.cos(this.cc.maxSlopeClimbAngle())}setCrouching(t){return this.isCrouching!==t&&(this.isCrouching=t,this.syncColliderShape(),!0)}canUncrouch(){const t=this.getColliderHeight(!1),e=this.getColliderRadius(!1);return!this.physicsSystem.hasActorCapsuleIntersection(this.actor,this.state.position,t,e,this.getCapsuleOffsetY(t,e),this.getCollisionGroup())}syncColliderShape(){const t=this.getColliderHeight(this.isCrouching),e=this.getColliderRadius(this.isCrouching);this.physicsSystem.setActorCapsuleCollider(this.actor,t,e,this.getCapsuleOffsetY(t,e))}getColliderHeight(t){const e=Number.isFinite(this.colliderHeight)?Math.max(0,this.colliderHeight):0;if(!t)return e;const i=Number.isFinite(this.crouchColliderHeight)?this.crouchColliderHeight:e;return r.clamp(i,0,e)}getColliderRadius(t){const e=Number.isFinite(this.colliderRadius)?Math.max(.001,this.colliderRadius):.001;if(!t)return e;const i=this.crouchColliderRadius??e,o=Number.isFinite(i)?i:e;return r.clamp(o,.001,e)}getCapsuleOffsetY(t,e){return e+t/2+this.offset}checkGrounded(t){jt.y=-Math.max(.05,this.cc.snapToGroundDistance()),this.physicsSystem.rayTest(zt.addVectors(t,Ot.set(0,this.offset,0)),Pt.addVectors(t,jt),this.rayTestResult,this.groundRayTestOptions)}resolvePlatformVelocity(t){return t.set(0,0,0),this.rayTestResult.hasHit&&null!=this.rayTestResult.actor&&this.physicsSystem.getLinearVelocity(this.rayTestResult.actor,t),t}getCollisionGroup(){return this.characterCollision?null:gt}};t([T(),e("design:type",Number)],Lt.prototype,"colliderHeight",void 0),t([T(),e("design:type",Number)],Lt.prototype,"colliderRadius",void 0),t([T(),e("design:type",Number)],Lt.prototype,"crouchColliderHeight",void 0),t([T({optional:!0}),e("design:type",Number)],Lt.prototype,"crouchColliderRadius",void 0),t([S(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Lt.prototype,"serverMove",null),t([v(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Lt.prototype,"clientMoveAck",null),t([v(!0),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Lt.prototype,"clientMoveCorrection",null),t([y(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Lt.prototype,"simulatedState",null),Lt=t([w({inEditor:!1}),e("design:paramtypes",[])],Lt);export{Lt as CharacterMovementComponent};const Bt={mode:A.walking,update(t){const e=t.component,i=t.move,o=t.state,s=t.rotatedDirection,n=Math.min(1,Math.sqrt(i.inputX*i.inputX+i.inputY*i.inputY)),r=!e.rotateToMovementDirection&&i.inputY<0,a=e.isCrouching,h=!t.rootMotionActive&&!a&&0===(i.flags&E)&&0!==(i.flags&Z)&&!r&&0!==s.lengthSq()&&(e.sprintPolicy?.canSprint()??!0),l=(a?e.maxSpeedCrouch:r?e.maxSpeedBackwards:h?e.maxSpeedSprint:e.maxSpeed)*(e.normalizedDirection?1:n);if(0!==s.lengthSq()){e.isSprinting=h,h&&e.sprintPolicy?.commitSprint(t.deltaTime,i.sequence);let a=Math.min(l,o.currentSpeed),c=e.groundAccelerationRate;if(h&&t.startedSprinting&&e.sprintStartBoostSpeed>0){const t=e.normalizedDirection?1:n;a=Math.max(a,l+e.sprintStartBoostSpeed*t),c=e.sprintStartBoostDamping}else h&&!r&&e.sprintStartBoostSpeed>0&&o.currentSpeed>l&&(a=o.currentSpeed,c=e.sprintStartBoostDamping);o.currentSpeed=function(t,e,i,o){return e+(t-e)*Math.exp(-i*o)}(a,l,c,t.deltaTime),t.outVelocity.copy(s).multiplyScalar(function(t,e,i,o){const s=i*o;if(s<=1e-6)return t;return e+(t-e)*(1-Math.exp(-s))/s}(a,l,c,t.deltaTime))}else o.currentSpeed=0,t.outVelocity.set(0,0,0);if(0!==(i.flags&L))return o.mode=A.falling,o.velocity.copy(t.outVelocity),o.velocity.y=e.jumpVelocity,A.falling;t.outVelocity.y=t.deltaTime*e.getEffectiveGravity(),t.outVelocity.add(t.platformVelocity)}},Ht={mode:A.falling,update(t){const e=t.component,i=t.state,o=t.move;0!==(o.flags&L)&&e.jumpInAir&&(i.velocity.copy(t.outVelocity),i.velocity.y=e.jumpVelocity),i.velocity.y+=t.deltaTime*e.getEffectiveGravity(),t.outVelocity.copy(i.velocity),t.outVelocity.addScaledVector(t.rotatedDirection,e.fallingMovementControl),e.fallingReorientation&&t.outVelocity.applyAxisAngle(Mt,r.euclideanModulo(o.yaw-i.lookYaw+Math.PI,2*Math.PI)-Math.PI)}};function Zt(t){return Math.sqrt(t.x*t.x+t.z*t.z)}function Wt(t,e){return e.sequence=t.sequence,e.clientTime=t.clientTime,e.dt=t.dt,e.inputX=t.inputX,e.inputY=t.inputY,e.yaw=t.yaw,e.flags=t.flags,e.clientX=t.clientX,e.clientY=t.clientY,e.clientZ=t.clientZ,e.rootMotionX=t.rootMotionX,e.rootMotionY=t.rootMotionY,e.rootMotionZ=t.rootMotionZ,e}function $t(t,e){const i=t.position.x-e.clientX,o=t.position.y-e.clientY,s=t.position.z-e.clientZ;return i*i+o*o+s*s}class Qt{constructor(t){this.scene=t,this.serverPosition=new h,this.direction=new h}update(t,e){const i=this.serverPosition.set(e.x,e.y,e.z),o=i.distanceTo(t);o>.1&&console.log(`Correction applied. Error: ${o.toFixed(3)}. Server position: (${i.x.toFixed(2)}, ${i.y.toFixed(2)}, ${i.z.toFixed(2)}), Client position: (${t.x.toFixed(2)}, ${t.y.toFixed(2)}, ${t.z.toFixed(2)})`);const s=this.direction.copy(i).sub(t).normalize();Jt.position.copy(t),Jt.setDirection(s),Jt.setLength(o);const n=Kt(this.scene);n.add(Jt),setTimeout(()=>{n.remove(Jt)},1e3)}}const Jt=new n(new h(0,1,0),new h,1,16711680);function Kt(t){return null==t.parent?t:Kt(t.parent)}const _t={immediate:!1,savedRootMotion:!0};/*
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 { ActorComponent } from '../../../../gameplay/actors/component';
1
+ import { ActorComponent } from '../../../../gameplay/actors/component.js';
2
2
  export declare class EditorSpriteComponent extends ActorComponent {
3
3
  /**
4
4
  * Path to the file for exmaple 'assets/audio.png'
@@ -1,4 +1,4 @@
1
- import{__decorate as t}from"tslib";import{UnscaledSprite as e}from"../../../../utils/three/unscaled-sprite";import{ActorComponent as r,Component as o}from"../../../../gameplay/actors/component";import*as i from"three";let a=class extends r{onInit(){if(null==this.file)return;const t=(new i.TextureLoader).load(this.file),r=new i.SpriteMaterial({map:t,alphaTest:.5}),o=new e(r);this.actor.object.add(o)}};a=t([o({inEditor:!0,editorOnly:!0})],a);export{a as EditorSpriteComponent};/*
1
+ import{__decorate as t}from"tslib";import{UnscaledSprite as e}from"../../../../utils/three/unscaled-sprite.js";import{ActorComponent as r,Component as o}from"../../../../gameplay/actors/component.js";import*as i from"three";let s=class extends r{onInit(){if(null==this.file)return;const t=(new i.TextureLoader).load(this.file),r=new i.SpriteMaterial({map:t,alphaTest:.5}),o=new e(r);this.actor.object.add(o)}};s=t([o({inEditor:!0,editorOnly:!0})],s);export{s as EditorSpriteComponent};/*
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 { ActorComponent } from '../../../../gameplay/actors/component';
1
+ import { ActorComponent } from '../../../../gameplay/actors/component.js';
2
2
  import { Color } from 'three';
3
3
  export declare class TriggerVolumeMesh extends ActorComponent {
4
4
  color: Color;
@@ -1,4 +1,4 @@
1
- import{__decorate as i,__metadata as s}from"tslib";import{Parameter as e}from"../../../../shader";import{ActorComponent as t,Component as o}from"../../../../gameplay/actors/component";import{Mesh as n,EdgesGeometry as r,LineSegments as h,LineBasicMaterial as m,Vector3 as l,BoxGeometry as c,MeshBasicMaterial as d,Group as p,Color as a}from"three";let w=class extends t{constructor(){super(...arguments),this.color=new a(16777215),this.dimensions=new l(1,1,1),this.mesh=new p}onInit(){const i=new c(this.dimensions.x,this.dimensions.y,this.dimensions.z),s=new r(i),e=new h(s,new m({color:this.color}));new n(i,new d({color:this.color,transparent:!0,opacity:.3,visible:!1}));this.mesh.add(e),this.actor.object.add(this.mesh)}set visible(i){this.mesh.visible=i}get visible(){return this.mesh.visible}};i([e(),s("design:type",a)],w.prototype,"color",void 0),w=i([o({inEditor:!0,editorOnly:!0})],w);export{w as TriggerVolumeMesh};/*
1
+ import{__decorate as s,__metadata as i}from"tslib";import{Parameter as e}from"../../../../shader/index.js";import{ActorComponent as t,Component as o}from"../../../../gameplay/actors/component.js";import{Mesh as n,EdgesGeometry as r,LineSegments as h,LineBasicMaterial as m,Vector3 as l,BoxGeometry as c,MeshBasicMaterial as d,Group as p,Color as a}from"three";let w=class extends t{constructor(){super(...arguments),this.color=new a(16777215),this.dimensions=new l(1,1,1),this.mesh=new p}onInit(){const s=new c(this.dimensions.x,this.dimensions.y,this.dimensions.z),i=new r(s),e=new h(i,new m({color:this.color}));new n(s,new d({color:this.color,transparent:!0,opacity:.3,visible:!1}));this.mesh.add(e),this.actor.object.add(this.mesh)}set visible(s){this.mesh.visible=s}get visible(){return this.mesh.visible}};s([e(),i("design:type",a)],w.prototype,"color",void 0),w=s([o({inEditor:!0,editorOnly:!0})],w);export{w as TriggerVolumeMesh};/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,5 +1,5 @@
1
1
  import { NavMesh } from 'recast-navigation';
2
- import { BaseActor } from "../../";
2
+ import { BaseActor } from "../../index.js";
3
3
  export declare function safeRecastInit(): Promise<boolean | void>;
4
4
  export type NavMeshLoader = {
5
5
  save(): any;