@hology/core 0.0.234 → 0.0.236
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.
- package/dist/csm.d.ts +2 -2
- package/dist/data/surface-definition.js +1 -1
- package/dist/effects/sequence/sequence-action.d.ts +4 -4
- package/dist/effects/sequence/sequence-animation-retiming.d.ts +1 -1
- package/dist/effects/sequence/sequence-data.d.ts +3 -2
- package/dist/effects/sequence/sequence-definitions.d.ts +2 -2
- package/dist/effects/sequence/sequence-event.d.ts +1 -1
- package/dist/effects/sequence/sequence-locator.d.ts +1 -1
- package/dist/effects/sequence/sequence-ops.d.ts +1 -1
- package/dist/effects/sequence/sequence-player.d.ts +8 -7
- package/dist/effects/sequence/sequence-transform.d.ts +1 -1
- package/dist/effects/sequence/sequence-value-lane.d.ts +2 -2
- package/dist/effects/vfx/behaviours.d.ts +2 -1
- package/dist/effects/vfx/initializsers.d.ts +2 -1
- package/dist/effects/vfx/rates.d.ts +1 -1
- package/dist/effects/vfx/trail-renderer.d.ts +1 -1
- package/dist/effects/vfx/vfx-asset.d.ts +4 -3
- package/dist/effects/vfx/vfx-binding-runtime.d.ts +2 -2
- package/dist/effects/vfx/vfx-collision-behaviour.d.ts +3 -2
- package/dist/effects/vfx/vfx-defs.d.ts +7 -3
- package/dist/effects/vfx/vfx-defs.js +1 -1
- package/dist/effects/vfx/vfx-input-runtime.d.ts +1 -1
- package/dist/effects/vfx/vfx-materializer.d.ts +7 -7
- package/dist/effects/vfx/vfx-param.d.ts +3 -3
- package/dist/effects/vfx/vfx-renderers.d.ts +4 -3
- package/dist/effects/vfx/vfx-renderers.js +1 -1
- package/dist/effects/vfx/vfx-service.d.ts +1 -1
- package/dist/effects/vfx/vfx-service.js +1 -1
- package/dist/game-component/game-component.d.ts +1 -1
- package/dist/gameplay/actors/builtin/components/character/character-movement-like.d.ts +2 -0
- package/dist/gameplay/actors/builtin/components/character/character-movement.d.ts +13 -0
- package/dist/gameplay/actors/builtin/components/character/character-movement.js +1 -1
- package/dist/gameplay/actors/builtin/components/character/root-motion-constraint.d.ts +7 -0
- package/dist/gameplay/actors/builtin/components/character/root-motion-constraint.js +4 -0
- package/dist/gameplay/actors/builtin/components/editor-sprite-component.d.ts +1 -1
- package/dist/gameplay/actors/builtin/components/editor-sprite-component.js +1 -1
- package/dist/gameplay/actors/builtin/components/volume-editor-component.d.ts +1 -1
- package/dist/gameplay/actors/builtin/components/volume-editor-component.js +1 -1
- package/dist/gameplay/actors/builtin/navmesh-actor.d.ts +1 -1
- package/dist/gameplay/actors/builtin/navmesh-actor.js +1 -1
- package/dist/gameplay/actors/builtin/post-process-volume-actor.d.ts +1 -1
- package/dist/gameplay/actors/builtin/post-process-volume-actor.js +1 -1
- package/dist/gameplay/actors/component.d.ts +2 -2
- package/dist/gameplay/actors/controller/actor-controller.d.ts +1 -1
- package/dist/gameplay/actors/controller/actor-controller.js +1 -1
- package/dist/gameplay/actors/index.d.ts +1 -0
- package/dist/gameplay/actors/index.js +1 -1
- package/dist/gameplay/actors/internal/component-init.d.ts +1 -1
- package/dist/gameplay/actors/internal/container-map.d.ts +2 -2
- package/dist/gameplay/ai/behavior-tree/move.d.ts +3 -3
- package/dist/gameplay/ai/behavior-tree/move.js +1 -1
- package/dist/gameplay/ai/build-tile.d.ts +2 -1
- package/dist/gameplay/ai/dynamic-tiled-navmesh.d.ts +4 -3
- package/dist/gameplay/ai/navigation.js +1 -1
- package/dist/gameplay/animation/anim-sm.d.ts +1 -1
- package/dist/gameplay/animation/retarget.d.ts +2 -1
- package/dist/gameplay/animation/root-motion.d.ts +2 -1
- package/dist/gameplay/event-graph/runtime-assets.d.ts +1 -1
- package/dist/gameplay/initiate.d.ts +5 -5
- package/dist/gameplay/inject.d.ts +1 -1
- package/dist/gameplay/net/browser/index.d.ts +3 -2
- package/dist/gameplay/net/browser/index.js +1 -1
- package/dist/gameplay/net/net-session.d.ts +2 -2
- package/dist/gameplay/services/asset-loader.js +1 -1
- package/dist/gameplay/services/game-time-scheduler.d.ts +1 -1
- package/dist/gameplay/services/physics/abstract-physics-system.d.ts +7 -7
- package/dist/gameplay/services/pointer-events.d.ts +2 -2
- package/dist/gameplay/services/pointer-events.js +1 -1
- package/dist/gameplay/services/world.d.ts +1 -1
- package/dist/gameplay/services/world.js +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/rendering/cluster-generator.d.ts +2 -1
- package/dist/rendering/fog/fog-volume-actor.d.ts +1 -1
- package/dist/rendering/fog/fog-volume-actor.js +1 -1
- package/dist/rendering/fog/fog-volume-object.d.ts +2 -1
- package/dist/rendering/fog/volumetric-fog-pass.d.ts +4 -2
- package/dist/rendering/fog/volumetric-fog-pass.js +1 -1
- package/dist/rendering/light-probes/light-volume-capture.d.ts +2 -1
- package/dist/rendering/motion-vector-node.d.ts +2 -1
- package/dist/rendering/node-material-webgpu-resolver.d.ts +2 -1
- package/dist/rendering/node-material-webgpu-resolver.js +1 -1
- package/dist/rendering/post-process-effect.d.ts +1 -1
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts +5 -4
- package/dist/scene/assets-provider.d.ts +2 -2
- package/dist/scene/batched-mesh-2.d.ts +1 -1
- package/dist/scene/bootstrap.d.ts +8 -7
- package/dist/scene/collision/collision-shape-import.d.ts +3 -3
- package/dist/scene/collision/collision-shape.d.ts +2 -1
- package/dist/scene/custom-param-deserialize.d.ts +1 -1
- package/dist/scene/custom-param-runtime-types.d.ts +2 -1
- package/dist/scene/landscape/landscape-manager.d.ts +6 -6
- package/dist/scene/landscape/landscape-manager.js +1 -1
- package/dist/scene/landscape/utils.d.ts +2 -2
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/materials/grass-foliage.d.ts +2 -2
- package/dist/scene/materials/grass.d.ts +1 -1
- package/dist/scene/materials/utils/material-painting.d.ts +2 -1
- package/dist/scene/materials/water.d.ts +1 -1
- package/dist/scene/model.d.ts +1 -1
- package/dist/scene/objects/prefab.d.ts +3 -3
- package/dist/scene/objects/shapes.d.ts +4 -2
- package/dist/scene/runtime-asset-service.d.ts +2 -2
- package/dist/scene/runtime-backend-service.d.ts +2 -2
- package/dist/scene/runtime-bundled-backend-service.d.ts +3 -3
- package/dist/scene/scatter/painted-scatter-manager.d.ts +1 -1
- package/dist/scene/scatter/surface-scatter-manager.d.ts +4 -4
- package/dist/scene/scene-data-service.d.ts +1 -1
- package/dist/scene/surface-query.d.ts +2 -2
- package/dist/scene/surface-query.js +1 -1
- package/dist/shader/builtin/decal-unlit-shader.js +1 -1
- package/dist/shader/builtin/index.d.ts +1 -1
- package/dist/shader/decal-shader.d.ts +3 -2
- package/dist/shader/graph/compiler.d.ts +1 -1
- package/dist/shader/parameter.d.ts +8 -8
- package/dist/shader/post-process-shader.d.ts +2 -1
- package/dist/shader/shader.d.ts +6 -5
- package/dist/shader/trail-shader.d.ts +3 -2
- package/dist/shader/trail-shader.js +1 -1
- package/dist/shader/uv-nodes.d.ts +2 -2
- package/dist/shader-nodes/bulge.d.ts +1 -1
- package/dist/shader-nodes/curve-sample.d.ts +2 -2
- package/dist/shader-nodes/depth.d.ts +3 -3
- package/dist/shader-nodes/dither.d.ts +1 -1
- package/dist/shader-nodes/effects.d.ts +1 -1
- package/dist/shader-nodes/glsl-node.d.ts +1 -1
- package/dist/shader-nodes/gradient-sample.d.ts +1 -1
- package/dist/shader-nodes/landscape.d.ts +1 -1
- package/dist/shader-nodes/layers.d.ts +1 -1
- package/dist/shader-nodes/material-flags.d.ts +1 -1
- package/dist/shader-nodes/particle.d.ts +1 -1
- package/dist/shader-nodes/pom.d.ts +2 -1
- package/dist/shader-nodes/pom.js +1 -1
- package/dist/shader-nodes/scene-sample.d.ts +2 -1
- package/dist/shader-nodes/shapes.d.ts +1 -1
- package/dist/shader-nodes/texture-sequence.d.ts +1 -1
- package/dist/shader-nodes/time.d.ts +1 -1
- package/dist/shader-nodes/voronoi.d.ts +1 -1
- package/dist/shader-nodes/wgsl-node.d.ts +1 -1
- package/dist/test/character-root-motion-constraint.test.d.ts +2 -0
- package/dist/test/character-root-motion-constraint.test.js +4 -0
- package/dist/test/node-material-webgpu-resolver.test.js +1 -1
- package/dist/utils/materials.d.ts +1 -1
- package/dist/utils/mesh.d.ts +1 -1
- package/dist/utils/obb-utils.d.ts +2 -1
- package/dist/utils/three/cleanup.d.ts +1 -1
- package/dist/utils/three/depth-pass.d.ts +1 -1
- package/dist/utils/three/traverse.d.ts +2 -1
- package/dist/worker/index.js +1 -1
- package/package.json +3 -2
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -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 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};/*
|
|
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{constrainRootMotionTargetApproach as q}from"./root-motion-constraint.js";import{DEFAULT_MAX_CLIENT_TIME_AHEAD as D,DEFAULT_LARGE_CORRECTION_THRESHOLD as b,DEFAULT_MAX_COMBINED_MOVE_DELTA_TIME as k,DEFAULT_MAX_MOVE_DELTA_TIME as z,DEFAULT_MAX_MOVES_PER_PACKET as I,DEFAULT_MAX_REPLAYED_MOVES as P,DEFAULT_MAX_SERVER_MOVES_PER_TICK as j,DEFAULT_MAX_SAVED_MOVES as O,DEFAULT_MAX_SERVER_MOVE_DELTA_TIME_SCALAR as G,DEFAULT_MAX_SERVER_MOVE_TIME_BUDGET as Y,DEFAULT_MAX_SUBSTEP_DELTA_TIME as N,DEFAULT_MOVE_SEND_INTERVAL as F,DEFAULT_SIMULATED_INTERPOLATION_DELAY as V,DEFAULT_SIMULATED_STATE_INTERVAL as U,DEFAULT_SMALL_CORRECTION_TOLERANCE as X,DEFAULT_TELEPORT_SNAP_THRESHOLD as E,MOVE_FLAG_CROUCH as L,MOVE_FLAG_JUMP as B,MOVE_FLAG_ROOT_MOTION as H,MOVE_FLAG_SLIDE_START as Z,MOVE_FLAG_SPRINT as Q,MOVE_FLAG_SPRINT_START as W,SNAPSHOT_FLAG_CROUCH_SUPPRESSED as $,SNAPSHOT_FLAG_CROUCHING as J,NetCharacterProxySmoother as K,NetCharacterSavedMoveBuffer as _,accrueNetCharacterServerMoveTime as tt,createNetCharacterMovementSnapshot as et,createNetCharacterServerMoveTimingState as it,consumeNetCharacterServerMoveTime as ot,decodeNetCharacterMoveBatch as st,decodeNetCharacterOwnerAck as nt,decodeNetCharacterOwnerCorrection as rt,decodeNetCharacterSimulatedState as at,encodeNetCharacterMoveBatch as ht,encodeNetCharacterOwnerAck as lt,encodeNetCharacterOwnerCorrection as ct,encodeNetCharacterSimulatedState as ut,validateNetCharacterMove as dt}from"./net-character-movement-protocol.js";import{NetMode as pt}from"../../../../net/net-session.js";import{setSlideJumpVelocity as mt,shouldContinueSlide as vt,shouldStartSlide as yt,updateSlideVelocity as St,updateSlideVelocityFromDisplacement as gt}from"./character-slide.js";export*from"./net-character-movement-protocol.js";const Mt=131070,ft=new h(0,1,0),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,zt=new h,It=new h,Pt=new h,jt=new h,Ot=new h(0,1,0),Gt=new h(0,-.05,0),Yt=new h,Nt=new a,Ft=new s.Euler,Vt=new h,Ut=new h,Xt=new h,Et=new h,Lt=new i.CharacterCollision;let Bt=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=U,this.maxSavedMoves=O,this.maxReplayedMoves=P,this.maxServerMovesPerTick=j,this.maxMovesPerPacket=I,this.maxMoveDeltaTime=z,this.maxCombinedMoveDeltaTime=k,this.maxServerMoveDeltaTimeScalar=G,this.maxClientTimeAhead=D,this.maxServerMoveTimeBudget=Y,this.maxSubstepDeltaTime=N,this.fallGraceTime=.1,this.correctionToleranceSq=X*X,this.largeCorrectionThreshold=b,this.teleportSnapThreshold=E,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 _(O),this.serverMoveTiming=it(),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:Tt,platformVelocity:Rt,outVelocity:Ct,rootMotionActive:!1,startedSprinting:!1},this.proxySmoother=new K(V,E),this.proxySample=et(),this.pendingSnapshot=et(),this.impulse=new h,this.prevRootMotionPos=new h,this.rootMotionOptions={},this.rootMotionTargetConstraints=new Set,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(Ht),this.registerMovementMode(Zt),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)}}addRootMotionTargetConstraint(t,e){const i={targetPosition:t,minimumHorizontalDistance:Math.max(0,e)};this.rootMotionTargetConstraints.add(i);let o=!1;return{dispose:()=>{o||(o=!0,this.rootMotionTargetConstraints.delete(i))}}}serverMove(t){const e=st(t);if(e.ok)for(const t of e.value.moves)dt(t,this.lastServerReceivedSequence,this.maxMoveDeltaTime)&&(this.lastServerReceivedSequence=t.sequence,this.serverMoveQueue.push(t))}clientMoveAck(t){const e=nt(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=rt(t);e.ok&&this.actor.netRole===m.autonomousProxy&&(this.debugCorrections&&(null==this.correctionDebug&&(this.correctionDebug=new Jt(_t(this.actor.object))),this.correctionDebug.update(this.state.position,e.value.snapshot)),this.applyCorrection(e.value.snapshot))}simulatedState(t){const e=at(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,te),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,te),this.resetToggleCrouchAfterSlide(i),e!==pt.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){tt(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=Xt.copy(this.actor.position);let n=!1;for(let t=0;t<o;t++){const t=this.serverMoveQueue.shift();if(null==t)break;if(!dt(t,this.lastServerProcessedSequence,this.maxMoveDeltaTime)){console.log("Net: Invalid move",t),this.sendOwnerCorrection(!0),e=!0;continue}const i=ot(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&=~H,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(lt(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);Et.subVectors(t,e);const i=Et.lengthSq();i>1e-8&&(i>this.listenServerNoSmoothUpdateDistance*this.listenServerNoSmoothUpdateDistance?this.visualSmoothingOffset.set(0,0,0):(i>this.listenServerMaxSmoothUpdateDistance*this.listenServerMaxSmoothUpdateDistance&&Et.setLength(this.listenServerMaxSmoothUpdateDistance),this.visualSmoothingOffset.add(Et)))}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(qt);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?B:0)|(l?Q:0)|(a?L:0)|(h&&this.slideEnabled?Z:0)|(c?W:0)|(qt.lengthSq()>0?H:0),d=function(t,e){e.set(t.x,0,t.y),e.lengthSq()>1&&e.normalize();return e}(this.directionInput.vector,Vt),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=qt.x,p.rootMotionY=qt.y,p.rootMotionZ=qt.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&Q)&&0===(t.flags&L);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|H:t.flags&~H,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&B),l=r||a;this.updateCrouchState(t,n,l,h),this.pressedJump=h,this.isSprinting=!1,this.updateRotation(t,e,r,a),this.resolvePlatformVelocity(Rt);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&L)&&0!==(t.flags&W);const i=u.update(c);"number"==typeof i&&(this.state.mode=i)}else Ct.set(0,0,0);if(a){Dt.copy(i).multiplyScalar(o).applyQuaternion(this.actor.quaternion),bt.copy(Dt).divideScalar(e),this.state.mode===A.walking?(Ct.x=bt.x+Rt.x,Ct.z=bt.z+Rt.z):(Ct.x=bt.x,Ct.z=bt.z);const t=Math.sqrt(bt.x*bt.x+bt.z*bt.z);t>.4&&(this.state.currentSpeed=t)}if(this.applyImpulseToVelocity(Ct,e),h&&this.isSprinting){const t=Math.max(0,this.maxSpeedSprint),e=Qt(Ct);if(e>t){const i=t/e;Ct.x*=i,Ct.z*=i,this.state.velocity.x*=i,this.state.velocity.z*=i}}this.state.mode===A.walking&&this.state.velocity.copy(Ct),this.applyMovement(Ct,e,s),this.state.mode===A.sliding&&(gt(this.state.velocity,At,Rt,this.slideSurfaceNormal,e),this.state.currentSpeed=Qt(this.state.velocity)),this.checkGrounded(this.state.position),this.state.grounded=this.isGrounded,this.updateModeAfterMove(Ct,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){xt.set(-t.inputX,0,t.inputY),xt.lengthSq()>1&&xt.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),Tt.set(0,0,0),i)this.state.lookYaw=t.yaw;else if(this.rotateToMovementDirection){if(xt.lengthSq()>0&&this.state.mode!==A.falling){const i=Ft.setFromQuaternion(this.actor.object.quaternion,"YXZ").y,o=Math.atan2(xt.x,xt.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(xt,e*this.rotationSpeed),this.state.lookYaw+=n,Tt.copy(this.actor.object.getWorldDirection(Vt).normalize())}}else o||(this.state.lookYaw+=n,this.actor.object.quaternion.multiply(Nt.setFromEuler(Ft.set(0,n,0))),xt.lengthSq()>0&&Tt.copy(xt).applyQuaternion(this.actor.object.quaternion).normalize())}applyMovement(t,e,i){if(t.lengthSq()>0||!this.state.grounded){if(wt.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()&&(wt.y=Math.max(0,Rt.y*e)),this.physicsSystem.getActorComputedMovement(this.actor,this.cc,wt,this.getCollisionGroup()),this.cc.computedCollision(0,Lt),null!=Lt.normal1)){const t=Vt.copy(Lt.normal1);Math.acos(r.clamp(t.dot(ft),-1,1))>this.cc.maxSlopeClimbAngle()&&(wt.y=.016*this.getEffectiveGravity()*.5)}At.copy(this.physicsSystem.getActorComputedMovement(this.actor,this.cc,wt,this.getCollisionGroup()))}else At.set(0,0,0);var o;this.suppressUncrouchLift&&(this.suppressUncrouchLift=!1,this.state.grounded&&this.state.mode===A.walking&&wt.y<=1e-6&&At.y>0&&(At.y=0)),this.state.position.add(At),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);Yt.set(e.normal2.x,e.normal2.y,e.normal2.z);const i=Yt.angleTo(ft);Yt.set(e.normal1.x,e.normal1.y,e.normal1.z);const o=Yt.angleTo(ft);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(ht(i))}sendOwnerCorrection(t){const e=this.toSnapshot(this.pendingSnapshot);t&&(e.horizontalSpeed=this.horizontalSpeed),this.sprintPolicy?.ack?.(e.sequence,!0),this.clientMoveCorrection(ct(e))}sendSimulatedState(t,e){this.simulatedStateAccumulator+=t,!e&&this.simulatedStateAccumulator<this.simulatedStateInterval||(this.simulatedStateAccumulator=0,this.simulatedState(ut(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&J)||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?J: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(ft))}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),zt.fromArray(e.evaluate(this.rootMotionAction.time)),t.subVectors(zt,this.prevRootMotionPos),this.prevRootMotionPos.copy(zt);if((this.rootMotionRootBone??this.rootMotionAction.getRoot()).getWorldScale(kt),t.multiply(kt),t.lengthSq()>0&&this.rootMotionTargetConstraints.size>0){Dt.copy(t).applyQuaternion(this.actor.quaternion);for(const t of this.rootMotionTargetConstraints)q(Dt,this.actor.position,t.targetPosition,t.minimumHorizontalDistance);t.copy(Dt).applyQuaternion(Nt.copy(this.actor.quaternion).invert())}return 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===pt.none||e!==m.authority||t>=pt.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=Mt,i}updateCrouchState(t,e,i,o){if(!(0!==(t.flags&L)))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(Ut);const s=this.slideOnLandingRequested&&this.state.mode===A.walking&&this.state.grounded,n=e&&0!==(t.flags&Z)||s;s&&(this.slideOnLandingRequested=!1);const r=Qt(this.state.velocity);this.state.mode===A.walking&&yt(this.slideEnabled,n,this.state.grounded,this.isWalkableSlideSurface(Ut),i,r,this.slideMinStartSpeed)&&(this.state.mode=A.sliding,this.slideSurfaceNormal.copy(Ut),this.state.velocity.projectOnPlane(this.slideSurfaceNormal),this.state.currentSpeed=Qt(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,Zt.update(t),A.falling;if(this.slideEnabled&&0!==(i.flags&L)&&!t.rootMotionActive&&0!==(i.flags&B))return mt(t.outVelocity,e.velocity,this.jumpVelocity),e.velocity.copy(t.outVelocity),e.currentSpeed=Qt(e.velocity),A.falling;if(!vt(this.slideEnabled,0!==(i.flags&L),e.grounded,o,t.rootMotionActive,s,this.slideMinExitSpeed))return e.mode=A.walking,Ht.update(t),A.walking;const n=St(e.velocity,e.velocity,this.slideSurfaceNormal,t.rotatedDirection,this.getEffectiveGravity(),t.deltaTime,this.slideDeceleration,this.slideGravityScale,this.slideSteeringRate);if(e.currentSpeed=Qt(e.velocity),n<Math.max(0,this.slideMinExitSpeed))return e.mode=A.walking,Ht.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(ft):(t.copy(this.rayTestResult.hitNormal).normalize(),t.dot(ft)<0&&t.multiplyScalar(-1),t)}isWalkableSlideSurface(t){return t.dot(ft)>=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){Gt.y=-Math.max(.05,this.cc.snapToGroundDistance()),this.physicsSystem.rayTest(Pt.addVectors(t,Ot.set(0,this.offset,0)),jt.addVectors(t,Gt),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:Mt}};t([T(),e("design:type",Number)],Bt.prototype,"colliderHeight",void 0),t([T(),e("design:type",Number)],Bt.prototype,"colliderRadius",void 0),t([T(),e("design:type",Number)],Bt.prototype,"crouchColliderHeight",void 0),t([T({optional:!0}),e("design:type",Number)],Bt.prototype,"crouchColliderRadius",void 0),t([S(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Bt.prototype,"serverMove",null),t([v(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Bt.prototype,"clientMoveAck",null),t([v(!0),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Bt.prototype,"clientMoveCorrection",null),t([y(!1),e("design:type",Function),e("design:paramtypes",[Uint8Array]),e("design:returntype",void 0)],Bt.prototype,"simulatedState",null),Bt=t([w({inEditor:!1}),e("design:paramtypes",[])],Bt);export{Bt as CharacterMovementComponent};const Ht={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&L)&&0!==(i.flags&Q)&&!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&B))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)}},Zt={mode:A.falling,update(t){const e=t.component,i=t.state,o=t.move;0!==(o.flags&B)&&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(ft,r.euclideanModulo(o.yaw-i.lookYaw+Math.PI,2*Math.PI)-Math.PI)}};function Qt(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 Jt{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();Kt.position.copy(t),Kt.setDirection(s),Kt.setLength(o);const n=_t(this.scene);n.add(Kt),setTimeout(()=>{n.remove(Kt)},1e3)}}const Kt=new n(new h(0,1,0),new h,1,16711680);function _t(t){return null==t.parent?t:_t(t.parent)}const te={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
|
*/
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Vector3 } from "three";
|
|
2
|
+
/**
|
|
3
|
+
* Removes only the portion of a world-space root-motion delta that would cross
|
|
4
|
+
* a target-relative horizontal minimum distance.
|
|
5
|
+
*/
|
|
6
|
+
export declare function constrainRootMotionTargetApproach(worldDelta: Vector3, actorPosition: Vector3, targetPosition: Vector3, minimumHorizontalDistance: number): Vector3;
|
|
7
|
+
//# sourceMappingURL=root-motion-constraint.d.ts.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export function constrainRootMotionTargetApproach(t,n,o,r){const a=o.x-n.x,x=o.z-n.z,c=a*a+x*x;if(c<=1e-8)return t;const e=Math.sqrt(c),i=a/e,s=x/e,h=t.x*i+t.z*s,u=Math.max(0,e-Math.max(0,r));if(h<=u)return t;const z=h-u;return t.x-=i*z,t.z-=s*z,t}/*
|
|
2
|
+
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
|
+
* See the LICENSE.md file for details.
|
|
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
|
|
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{__decorate as
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{Ball as n,Capsule as s,Cone as o,ConvexPolyhedron as i,Cuboid as r,Cylinder as a,Heightfield as l,ShapeType as c,TriMesh as h}from"@dimforge/rapier3d-simd-compat";import{init as p}from"@recast-navigation/core";import{DebugDrawer as u,getPositionsAndIndices as d}from"@recast-navigation/three";import{BehaviorSubject as m,Subject as f,debounceTime as w,filter as b,firstValueFrom as g,takeUntil as y}from"rxjs";import*as x from"three";import{BufferGeometryUtils as v,ConvexHull as M}from"three/examples/jsm/Addons.js";import{Actor as B,BaseActor as S,Parameter as z,PhysicsSystem as
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{Ball as n,Capsule as s,Cone as o,ConvexPolyhedron as i,Cuboid as r,Cylinder as a,Heightfield as l,ShapeType as c,TriMesh as h}from"@dimforge/rapier3d-simd-compat";import{init as p}from"@recast-navigation/core";import{DebugDrawer as u,getPositionsAndIndices as d}from"@recast-navigation/three";import{BehaviorSubject as m,Subject as f,debounceTime as w,filter as b,firstValueFrom as g,takeUntil as y}from"rxjs";import*as x from"three";import{BufferGeometryUtils as v,ConvexHull as M}from"three/examples/jsm/Addons.js";import{Actor as B,BaseActor as S,Parameter as z,PhysicsSystem as j,ViewController as A,World as k,attach as C,inject as P}from"../../index.js";import{sleepDelay as F}from"../../../utils/async.js";import{hasSharedArrayBufferSupport as I,toSharedFloat32Array as D,toSharedUint32Array as V}from"../../../utils/buffer.js";import{DynamicTiledNavMesh as G,MAX_NAV_MESH_WORKERS as N}from"../../ai/dynamic-tiled-navmesh.js";import{TriggerVolumeMesh as H}from"./components/volume-editor-component.js";var E;!function(e){e[e.none=0]="none",e[e.starting=1]="starting",e[e.started=2]="started"}(E||(E={}));let T=E.none,R=new m(!1);export async function safeRecastInit(){return T===E.none?(T=E.starting,p().then(()=>{R.next(!0),T=E.started})):g(R.pipe(b(e=>e)))}new x.Box3(new x.Vector3(-100,-100,-100),new x.Vector3(100,100,100));const U=Math.max(1,Math.min(N,(navigator.hardwareConcurrency??2)-1));let q=!1,O=class extends S{constructor(){super(...arguments),this.physics=P(j),this.view=P(A),this.world=P(k),this.editorVisualisation=C(H),this.debug=!0,this.refreshMs=4e3,this.tileSize=50,this.walkableClimb=.3,this.walkableSlopeAngle=45,this.walkableHeight=2,this.cellSize=.2,this.bounds=new x.Box3}async onInit(){q||(await safeRecastInit(),q=!0),setTimeout(()=>{this.init()},10),this.recreateInterval=setInterval(()=>{if("_hology_transform_group"===this.object.parent?.name)return;J.setFromCenterAndSize(this.position,this.object.scale).equals(this.bounds)||(this.disposed.next(!0),this.disposed=new f,this.init())},2e3)}onEndPlay(){clearInterval(this.recreateInterval)}applySceneParameters(e,t){return!(null==this.debugDrawer||!t.has("debug")||"boolean"!=typeof e.debug)&&(this.debugDrawer.visible=e.debug,!0)}init(){this.bounds.setFromCenterAndSize(this.position,this.object.scale);const e=this.bounds.max.x-this.bounds.min.x,t=this.bounds.max.z-this.bounds.min.z,n=Math.max(1,Math.min(e,t)),s=Math.min(400,Math.max(50,Math.ceil(n/2))),o=Math.max(this.cellSize,.01),i={tileSize:Math.max(32,Math.floor(s/o)),walkableClimb:this.walkableClimb/o,walkableSlopeAngle:this.walkableSlopeAngle,walkableRadius:2,walkableHeight:this.walkableHeight/o,detailSampleDist:1,minRegionArea:6,mergeRegionArea:400,cs:o,ch:o,maxSimplificationError:1.3,maxEdgeLen:200},r=new G({navMeshBounds:this.bounds,recastConfig:i,maxTiles:1024,workers:U,cacheId:"nav"+this.object.userData?.src?.id});this.navMesh=r.navMesh;const a=this.tileSize*i.cs*2,l=performance.now(),c=new Map,h=new u;h.userData.isDebugDrawer=!0,this.debugDrawer=h;r.navMesh;const p=this.bounds,m=()=>{const e=this.view.getCamera().getWorldPosition(new x.Vector3),t=new x.Box3((new x.Vector3).copy(e).subScalar(a),(new x.Vector3).copy(e).addScalar(a)),n=[],s=this.physics.world.bodies;if(null==s)return[];const o=new x.Box3;for(const e of s.getAll())for(let s=0,i=e.numColliders();s<i;s++){const i=e.collider(s);if(i.isSensor()||null!=i.parent().userData&&!0===i.parent().userData.ignoreForNavMesh)continue;const r=e.handle+","+s,a=c.get(r)?.mesh,l=a??X(i);if($(i,l),null!=l){o.copy(l.geometry.boundingBox),o.min.add(l.position),o.max.add(l.position);const e=o.intersectsBox(t)||!0,s=o.intersectsBox(this.bounds);c.set(r,{pos:i.translation(),mesh:l}),e&&s&&n.push(l)}}return n},f=new x.Box3,b=new Map,g=new Map;let v=!0,M=performance.now(),B=!1;const S=function(e,t){let n=!1;return(async()=>{for(;!n;)await e(),await F(t)})(),()=>{n=!0}}(async()=>{if(B)return;const e=new x.Box3,t=m();for(const n of t){const t=b.get(n);!0!==t?.equals(n.position)&&(null!=t&&e.expandByPoint(t),e.expandByObject(n),b.set(n,n.position.clone()))}e.min.subScalar(50),e.max.addScalar(50);const n=r.getTilesForBounds(e);n.length>500&&console.warn("Too many tiles to update. Consider increasing tile size");const s=n.slice(0,500);if(0!=s.length){const n=[];for(const s of t)f.setFromObject(s),f.intersectsBox(e)&&n.push(s);let[o,i]=d(n);i=function(e,t,n){const s=new x.Vector3,o=[];for(let i=0;i<t.length;i+=3){let r=!0;for(let o=0;o<3;o++){const a=3*t[i+o];if(s.fromArray(e,a),!n.containsPoint(s)){r=!1;break}}r&&o.push(t[i],t[i+1],t[i+2])}return new Uint32Array(o)}(o,i,p),I&&(o=D(o),i=V(i));const a=v;v=!1,await Promise.all(s.map(e=>(M=performance.now(),r.buildTile(o,i,e,a).then(()=>{const t=e[0]+","+e[1];g.set(t,(g.get(t)??0)+1),this.debug})))).then(()=>{this.debug,B=!1})}else B=!1},this.refreshMs??1e4);this.disposed.subscribe(()=>S()),r.onNavMeshUpdate.pipe(y(this.disposed),w(200)).subscribe(()=>{h.clear(),h.drawNavMesh(r.navMesh)}),console.log("Create navmesh with debug",this.debug),this.debug&&(this.object.rotation.set(0,0,0),this.object.updateMatrix(),this.object.updateMatrixWorld(),this.object.parent.add(h)),this.disposed.subscribe(()=>{r?.destroy(),h.removeFromParent(),h.dispose()});const z=performance.now()-l;z>1e3&&console.warn(`NavMesh update took ${z} ms. Consider changing tileSize or other parameter that may affect performance`)}};e([z(),t("design:type",Boolean)],O.prototype,"debug",void 0),e([z(),t("design:type",Number)],O.prototype,"walkableClimb",void 0),e([z({range:[0,89]}),t("design:type",Number)],O.prototype,"walkableSlopeAngle",void 0),e([z(),t("design:type",Number)],O.prototype,"walkableHeight",void 0),e([z({range:[.01,10]}),t("design:type",Number)],O.prototype,"cellSize",void 0),O=e([B()],O);export default O;const W=new Map,_=new WeakMap;function L(e){if(e.shape instanceof l)return function(e){const t=e.shape;if(t.type!==c.HeightField)throw new Error("The provided collider is not a height field.");let n=!1;const s=t,o=s.heights,i=s.nrows,r=s.ncols,a=s.scale.x,l=s.scale.z,h=s.scale.y,p=i+1,u=new x.PlaneGeometry(l,a,r,i);u.rotateX(-Math.PI/2);const d=u.attributes.position.array;let m=0;for(let e=0;e<p;e++)for(let t=0;t<p;t++)d[m+1]=o[t*p+e]*h,m+=3,0!=d[m+1]&&(n=!0);if(!n){const e=new x.PlaneGeometry(a,l,2,2);return e.rotateX(-Math.PI/2),e}return u}(e);if(e.shape instanceof n)return new x.SphereGeometry(e.shape.radius);if(e.shape instanceof r){const t=e.shape.halfExtents;return new x.BoxGeometry(2*t.x,2*t.y,2*t.z)}if(e.shape instanceof i){const t=function(e){const t=_.get(e);if(void 0!==t)return t;const n=new Uint32Array(e.buffer,e.byteOffset,e.byteLength>>>2);let s=2166136261;for(let e=0;e<n.length;e++)s=Math.imul(s^n[e],16777619)>>>0;return _.set(e,s),s}(e.shape.vertices);let n=W.get(t);return n||(n=function(e){const t=[];for(let n=0;n<e.length;n+=3)t.push(new x.Vector3(e[n],e[n+1],e[n+2]));const n=(new M).setFromPoints(t),s=[];n.faces.forEach(e=>{const t=e.edge.head().point,n=e.edge.next.head().point,o=e.edge.next.next.head().point;s.push(t.x,t.y,t.z),s.push(n.x,n.y,n.z),s.push(o.x,o.y,o.z)});const o=new x.BufferGeometry;return o.setAttribute("position",new x.Float32BufferAttribute(s,3)),o}(e.shape.vertices),W.set(t,n)),n}if(e.shape instanceof h){const t=e.shape.vertices,n=e.shape.indices;let s=new x.BufferGeometry;return s.setAttribute("position",new x.Float32BufferAttribute(t,3)),null!=n?s.setIndex(new x.Uint16BufferAttribute(n,1)):s=v.mergeVertices(s),s.computeVertexNormals(),s}if(e.shape instanceof a){const t=e.shape.halfHeight,n=e.shape.radius;return new x.CylinderGeometry(n,n,2*t)}if(e.shape instanceof o){const t=e.shape.halfHeight,n=e.shape.radius;return new x.ConeGeometry(n,2*t)}if(e.shape instanceof s){const t=e.shape.halfHeight,n=e.shape.radius;return new x.CapsuleGeometry(n,2*t)}return console.warn("Unsupported shape",e.shape.type,e),null}function X(e){const t=L(e);if(null==t)return null;const n=K,s=new x.Mesh(t,n);return s.geometry.computeBoundingBox(),s.geometry.scale(1.01,1.01,1.01),s}function $(e,t){const n=e.translation(),s=e.rotation();t.position.set(n.x,n.y,n.z),t.quaternion.set(s.x,s.y,s.z,s.w)}const J=new x.Box3,K=new x.MeshBasicMaterial({wireframe:!1,color:16711680,side:x.FrontSide});/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as t,__metadata as e}from"tslib";import{Actor as o,attach as i,BaseActor as p,Component as n,inject as r,Parameter as s}from"
|
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import{Actor as o,attach as i,BaseActor as p,Component as n,inject as r,Parameter as s}from"../../index.js";import{Texture as a}from"three";import{tonemapMappings as d}from"../../../rendering/tone-mapping.js";import{OBB as l}from"three/examples/jsm/math/OBB.js";import{Vector3 as g}from"three";import*as u from"three";import{RenderingView as y}from"../../../rendering.js";import{TriggerVolumeMesh as h}from"./components/volume-editor-component.js";import{ActorComponent as m}from"../../actors/component.js";const b=[0,2],v=[-1,1];function f(t,e){return{optional:!0,type:g,group:t,label:e,range:b,precision:3,stepSize:.01,defaultValue:new g(1,1,1),editorInput:"colorGrade"}}function c(t,e){return{optional:!0,type:g,group:t,label:e,range:v,precision:3,stepSize:.01,defaultValue:new g(0,0,0),editorInput:"colorGrade"}}let w=class extends m{};t([s({options:d,optional:!0,group:"Tone Mapping",label:"Tone Mapping"}),e("design:type",Number)],w.prototype,"tonemapMapping",void 0),t([s({optional:!0,group:"Tone Mapping",label:"Tone Mapping Exposure",defaultValue:1}),e("design:type",Number)],w.prototype,"tonemapExposure",void 0),t([s({optional:!0}),e("design:type",a)],w.prototype,"envTexture",void 0),t([s({optional:!0,defaultValue:1}),e("design:type",Number)],w.prototype,"envIntensity",void 0),t([s({optional:!0,group:"Lens",defaultValue:0}),e("design:type",Number)],w.prototype,"vignetteIntensity",void 0),t([s({optional:!0,group:"Color Correction",defaultValue:new u.Color(16777215)}),e("design:type",u.Color)],w.prototype,"colorTint",void 0),t([s({optional:!0,group:"Color Correction",defaultValue:0}),e("design:type",Number)],w.prototype,"colorTintIntensity",void 0),t([s({optional:!0,group:"Depth of Field"}),e("design:type",Number)],w.prototype,"depthFocus",void 0),t([s({optional:!0,group:"Depth of Field"}),e("design:type",Number)],w.prototype,"depthAperture",void 0),t([s({optional:!0,group:"Depth of Field"}),e("design:type",Number)],w.prototype,"depthMaxBlur",void 0),t([s({optional:!0,range:[1e3,4e4],precision:.1,group:"White Balance",defaultValue:6500}),e("design:type",Number)],w.prototype,"temperature",void 0),t([s({optional:!0,range:[-1,1],group:"White Balance",defaultValue:0}),e("design:type",Number)],w.prototype,"temperatureTint",void 0),t([s(f("Global","Saturation")),e("design:type",g)],w.prototype,"globalSaturation",void 0),t([s(f("Global","Contrast")),e("design:type",g)],w.prototype,"globalContrast",void 0),t([s(f("Global","Gamma")),e("design:type",g)],w.prototype,"globalGamma",void 0),t([s(f("Global","Gain")),e("design:type",g)],w.prototype,"globalGain",void 0),t([s(c("Global","Offset")),e("design:type",g)],w.prototype,"globalOffset",void 0),t([s(f("Shadows","Saturation")),e("design:type",g)],w.prototype,"shadowsSaturation",void 0),t([s(f("Shadows","Contrast")),e("design:type",g)],w.prototype,"shadowsContrast",void 0),t([s(f("Shadows","Gamma")),e("design:type",g)],w.prototype,"shadowsGamma",void 0),t([s(f("Shadows","Gain")),e("design:type",g)],w.prototype,"shadowsGain",void 0),t([s(c("Shadows","Offset")),e("design:type",g)],w.prototype,"shadowsOffset",void 0),t([s({optional:!0,group:"Shadows",label:"Max",range:[0,1],precision:3,stepSize:.01,defaultValue:.09}),e("design:type",Number)],w.prototype,"shadowsMax",void 0),t([s(f("Midtones","Saturation")),e("design:type",g)],w.prototype,"midtonesSaturation",void 0),t([s(f("Midtones","Contrast")),e("design:type",g)],w.prototype,"midtonesContrast",void 0),t([s(f("Midtones","Gamma")),e("design:type",g)],w.prototype,"midtonesGamma",void 0),t([s(f("Midtones","Gain")),e("design:type",g)],w.prototype,"midtonesGain",void 0),t([s(c("Midtones","Offset")),e("design:type",g)],w.prototype,"midtonesOffset",void 0),t([s(f("Highlights","Saturation")),e("design:type",g)],w.prototype,"highlightsSaturation",void 0),t([s(f("Highlights","Contrast")),e("design:type",g)],w.prototype,"highlightsContrast",void 0),t([s(f("Highlights","Gamma")),e("design:type",g)],w.prototype,"highlightsGamma",void 0),t([s(f("Highlights","Gain")),e("design:type",g)],w.prototype,"highlightsGain",void 0),t([s(c("Highlights","Offset")),e("design:type",g)],w.prototype,"highlightsOffset",void 0),t([s({optional:!0,group:"Highlights",label:"Min",range:[0,1],precision:3,stepSize:.01,defaultValue:.5}),e("design:type",Number)],w.prototype,"highlightsMin",void 0),t([s({label:"LUT",optional:!0,group:"LUT"}),e("design:type",a)],w.prototype,"lut",void 0),t([s({label:"LUT Intensity",range:[0,1],optional:!0,group:"LUT",defaultValue:0}),e("design:type",Number)],w.prototype,"lutIntensity",void 0),w=t([n()],w);export{w as PostProcessSettings};let G=class extends p{constructor(){super(),this.settings=i(w),this.bounded=!1,this.priority=0,this.blendWeight=1,this.blendRadius=0,this.box=new l(void 0,new u.Vector3(.5,.5,.5)),this.view=r(y),this.editorView=i(h),this.disposed.subscribe(()=>{this.view.removePostProcessVolume(this)})}onInit(){this.view.addPostProcessVolume(this),this.editorView.visible=this.bounded}containsPoint(t){return!this.bounded||(this.resetBox(),this.box.containsPoint(t))}distanceToPoint(t){return this.bounded?(this.resetBox(),this.box.clampPoint(t,S),S.distanceTo(t)):0}resetBox(){const t=this.box;t.center.set(0,0,0),t.halfSize.set(.5,.5,.5),t.rotation.copy(x.rotation),t.applyMatrix4(this.object.matrixWorld)}};t([s(),e("design:type",Boolean)],G.prototype,"bounded",void 0),t([s({precision:0}),e("design:type",Number)],G.prototype,"priority",void 0),t([s({range:[0,1]}),e("design:type",Number)],G.prototype,"blendWeight",void 0),t([s(),e("design:type",Number)],G.prototype,"blendRadius",void 0),G=t([o(),e("design:paramtypes",[])],G);export{G as PostProcessVolume};const x=new l,S=new g;/*
|
|
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
|
-
import { Constructable } from 'typedi';
|
|
2
|
-
import { BaseActor } from './actor.js';
|
|
1
|
+
import type { Constructable } from 'typedi';
|
|
2
|
+
import type { BaseActor } from './actor.js';
|
|
3
3
|
export { getComponentClassById, getComponentClassId, getRegisteredComponentClasses, } from './type-registry.js';
|
|
4
4
|
export type ActorComponentParams<T extends ActorComponent> = {
|
|
5
5
|
[K in Exclude<keyof T, keyof ActorComponent> as T[K] extends (...args: any[]) => any ? never : K]: T[K];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{BaseActor as o}from"../actor";export class ActorController extends o{constructor(){super(...arguments),this.isLocallyControlled=!1}}export class BasePlayerController extends ActorController{constructor(){super(...arguments),this.isLocallyControlled=!1}}export class BaseAIController extends ActorController{constructor(){super(...arguments),this.isLocallyControlled=!1}}/*
|
|
1
|
+
import{BaseActor as o}from"../actor.js";export class ActorController extends o{constructor(){super(...arguments),this.isLocallyControlled=!1}}export class BasePlayerController extends ActorController{constructor(){super(...arguments),this.isLocallyControlled=!1}}export class BaseAIController extends ActorController{constructor(){super(...arguments),this.isLocallyControlled=!1}}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -7,6 +7,7 @@ export { TriggerVolume, TriggerVolumeComponent } from './builtin/trigger-volume.
|
|
|
7
7
|
export { PositionalAudioActor, PositionalAudioComponent } from './builtin/positional-audio-actor.js';
|
|
8
8
|
export * from './builtin/components/mesh-component.js';
|
|
9
9
|
export * from './builtin/components/character/character-movement.js';
|
|
10
|
+
export * from './builtin/components/character/root-motion-constraint.js';
|
|
10
11
|
export * from './builtin/components/character/character-movement-policy.js';
|
|
11
12
|
export * from './builtin/components/character/old-character-movement.js';
|
|
12
13
|
export * from './builtin/components/character/character-movement-like.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{CameraActor}from"./builtin/camera-actor.js";export{CameraComponent}from"./camera/camera-component.js";export{FirstPersonCameraComponent}from"./camera/first-person-camera-component.js";export{ThirdPersonCameraComponent,ThirdPartyCameraComponent}from"./camera/third-person-camera-component.js";export{SpawnPoint}from"./builtin/spawn-point.js";export{TriggerVolume,TriggerVolumeComponent}from"./builtin/trigger-volume.js";export{PositionalAudioActor,PositionalAudioComponent}from"./builtin/positional-audio-actor.js";export*from"./builtin/components/mesh-component.js";export*from"./builtin/components/character/character-movement.js";export*from"./builtin/components/character/character-movement-policy.js";export*from"./builtin/components/character/old-character-movement.js";export*from"./builtin/components/character/character-movement-like.js";export*from"./builtin/components/character/modes.js";export*from"./builtin/components/character/character-animation.js";export*from"./controller/actor-controller.js";export{builtInComponents}from"./builtin/components/index.js";/*
|
|
1
|
+
export{CameraActor}from"./builtin/camera-actor.js";export{CameraComponent}from"./camera/camera-component.js";export{FirstPersonCameraComponent}from"./camera/first-person-camera-component.js";export{ThirdPersonCameraComponent,ThirdPartyCameraComponent}from"./camera/third-person-camera-component.js";export{SpawnPoint}from"./builtin/spawn-point.js";export{TriggerVolume,TriggerVolumeComponent}from"./builtin/trigger-volume.js";export{PositionalAudioActor,PositionalAudioComponent}from"./builtin/positional-audio-actor.js";export*from"./builtin/components/mesh-component.js";export*from"./builtin/components/character/character-movement.js";export*from"./builtin/components/character/root-motion-constraint.js";export*from"./builtin/components/character/character-movement-policy.js";export*from"./builtin/components/character/old-character-movement.js";export*from"./builtin/components/character/character-movement-like.js";export*from"./builtin/components/character/modes.js";export*from"./builtin/components/character/character-animation.js";export*from"./controller/actor-controller.js";export{builtInComponents}from"./builtin/components/index.js";/*
|
|
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 { BaseActor } from '../actor.js';
|
|
1
|
+
import type { BaseActor } from '../actor.js';
|
|
2
2
|
import { ActorComponent } from '../component.js';
|
|
3
3
|
export declare function initComponents(a: BaseActor | ActorComponent, actor: BaseActor, inEditor?: boolean): Promise<any[]>;
|
|
4
4
|
export declare function initComponentsSync(a: BaseActor | ActorComponent, actor: BaseActor, inEditor?: boolean): void;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ContainerInstance } from "typedi";
|
|
2
|
-
import { BaseActor } from '../actor.js';
|
|
1
|
+
import type { ContainerInstance } from "typedi";
|
|
2
|
+
import type { BaseActor } from '../actor.js';
|
|
3
3
|
export declare const containerRefMap: WeakMap<BaseActor, ContainerInstance>;
|
|
4
4
|
export declare const activeContainerInstance: {
|
|
5
5
|
value: any;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Vector3 } from "three";
|
|
2
|
-
import type { CharacterMovementLike } from "../../../gameplay/actors";
|
|
3
|
-
import { Navigation } from "../navigation";
|
|
4
|
-
import { LeafNode, NodeState } from "./bt";
|
|
2
|
+
import type { CharacterMovementLike } from "../../../gameplay/actors/index.js";
|
|
3
|
+
import type { Navigation } from "../navigation.js";
|
|
4
|
+
import { LeafNode, NodeState } from "./bt.js";
|
|
5
5
|
export declare class CharacterMoveToNode extends LeafNode {
|
|
6
6
|
private navigation;
|
|
7
7
|
private movement;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Vector3 as t}from"three";import{LeafNode as e,NodeState as o}from"./bt";export class CharacterMoveToNode extends e{constructor(t,e){super(),this.navigation=t,this.movement=e,this.distanceFrom=.5}tick(t){const e=this.movement.actor.object.position,i=null!=this.target?this.target():null;if(null==i)return this.movement.directionInput.vector.set(0,0),o.FAILURE;if(e.distanceTo(i)<this.distanceFrom)return this.movement.directionInput.vector.set(0,0),o.SUCCESS;const{success:
|
|
1
|
+
import{Vector3 as t}from"three";import{LeafNode as e,NodeState as o}from"./bt.js";export class CharacterMoveToNode extends e{constructor(t,e){super(),this.navigation=t,this.movement=e,this.distanceFrom=.5}tick(t){const e=this.movement.actor.object.position,i=null!=this.target?this.target():null;if(null==i)return this.movement.directionInput.vector.set(0,0),o.FAILURE;if(e.distanceTo(i)<this.distanceFrom)return this.movement.directionInput.vector.set(0,0),o.SUCCESS;const{success:s,path:r}=this.navigation.findPath(e,i);if(!s||r.length<2)return o.FAILURE;const c=r[1],a=n.subVectors(c,e);return a.y=0,a.normalize(),this.movement.rotationInput.rotation.y=Math.atan2(a.x,a.z),this.movement.directionInput.togglePositiveY(!0),o.RUNNING}}const n=new t;/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { RecastCompactHeightfield, RecastConfig, RecastContourSet, RecastHeightfield, UnsignedCharArray, Vector3Tuple } from '@recast-navigation/core';
|
|
2
|
+
import { RecastBuildContext } from '@recast-navigation/core';
|
|
2
3
|
type BuildConfigProps = {
|
|
3
4
|
recastConfig: RecastConfig;
|
|
4
5
|
navMeshBounds: [min: Vector3Tuple, max: Vector3Tuple];
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import
|
|
1
|
+
import type { RecastConfig, Vector3Tuple } from 'recast-navigation';
|
|
2
|
+
import { NavMesh } from 'recast-navigation';
|
|
3
|
+
import type * as THREE from 'three';
|
|
4
|
+
import type { BuildTileMeshProps } from './build-tile.js';
|
|
4
5
|
import { Subject } from 'rxjs';
|
|
5
6
|
export type DynamicTiledNavMeshProps = {
|
|
6
7
|
navMeshBounds: THREE.Box3;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{NavMeshQuery as n}from"recast-navigation";import{Vector3 as s}from"three";import{inject as r,Service as o,World as i}from"../";import u,{safeRecastInit as a}from"../actors/builtin/navmesh-actor";let h=class{constructor(){this.world=r(i),a().then(()=>{const e=this.world.actors.find(e=>e instanceof u);null!=e&&(this.navMeshActor=e,this.query=null),this.world.actorAdded.subscribe(e=>{e instanceof u&&(this.navMeshActor=e,this.query=null)}),this.world.actorRemoved.subscribe(e=>{e instanceof u&&e.id===this.navMeshActor?.id&&(this.navMeshActor=null,this.query=null)})})}ensureQuery(){null==this.query&&null!=this.navMeshActor&&null!=this.navMeshActor.navMesh&&(this.query=new n(this.navMeshActor.navMesh))}findPath(e,t){if(this.ensureQuery(),null==this.query)return d("NavMesh has not been generated yet"),c;const n=this.findClosestPoint(e);if(null==n)return d("Start point could not be found on NavMesh",e),c;const{success:r,error:o,path:i}=this.query.computePath(n,t);return r?{success:!0,path:i.map(e=>new s(e.x,e.y,e.z))}:(d("Failed to generate path",o),c)}findClosestPoint(e){if(this.ensureQuery(),null==this.query)return d("NavMesh has not been generated yet"),null;const{success:t,point:n}=this.query.findClosestPoint(e);return t?new s(n.x,n.y,n.z):null}findRandomPoint(){if(this.ensureQuery(),null==this.query)return d("NavMesh has not been generated yet"),null;const e=this.query.findRandomPoint();return{success:e.success,randomPoint:(new s).copy(e.randomPoint)}}findRandomPointAroundCircle(e,t){if(this.ensureQuery(),null==this.query)return d("NavMesh has not been generated yet"),null;const n=this.query.findRandomPointAroundCircle(e,t);return{success:n.success,randomPoint:(new s).copy(n.randomPoint)}}};h=e([o(),t("design:paramtypes",[])],h);export{h as Navigation};const c={success:!1,path:[]};let l=new Set;function d(e,...t){l.has(e)||(l.add(e),setTimeout(()=>l.delete(e),2e3),console.warn(e,...t))}/*
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{NavMeshQuery as n}from"recast-navigation";import{Vector3 as s}from"three";import{inject as r,Service as o,World as i}from"../index.js";import u,{safeRecastInit as a}from"../actors/builtin/navmesh-actor.js";let h=class{constructor(){this.world=r(i),a().then(()=>{const e=this.world.actors.find(e=>e instanceof u);null!=e&&(this.navMeshActor=e,this.query=null),this.world.actorAdded.subscribe(e=>{e instanceof u&&(this.navMeshActor=e,this.query=null)}),this.world.actorRemoved.subscribe(e=>{e instanceof u&&e.id===this.navMeshActor?.id&&(this.navMeshActor=null,this.query=null)})})}ensureQuery(){null==this.query&&null!=this.navMeshActor&&null!=this.navMeshActor.navMesh&&(this.query=new n(this.navMeshActor.navMesh))}findPath(e,t){if(this.ensureQuery(),null==this.query)return d("NavMesh has not been generated yet"),c;const n=this.findClosestPoint(e);if(null==n)return d("Start point could not be found on NavMesh",e),c;const{success:r,error:o,path:i}=this.query.computePath(n,t);return r?{success:!0,path:i.map(e=>new s(e.x,e.y,e.z))}:(d("Failed to generate path",o),c)}findClosestPoint(e){if(this.ensureQuery(),null==this.query)return d("NavMesh has not been generated yet"),null;const{success:t,point:n}=this.query.findClosestPoint(e);return t?new s(n.x,n.y,n.z):null}findRandomPoint(){if(this.ensureQuery(),null==this.query)return d("NavMesh has not been generated yet"),null;const e=this.query.findRandomPoint();return{success:e.success,randomPoint:(new s).copy(e.randomPoint)}}findRandomPointAroundCircle(e,t){if(this.ensureQuery(),null==this.query)return d("NavMesh has not been generated yet"),null;const n=this.query.findRandomPointAroundCircle(e,t);return{success:n.success,randomPoint:(new s).copy(n.randomPoint)}}};h=e([o(),t("design:paramtypes",[])],h);export{h as Navigation};const c={success:!1,path:[]};let l=new Set;function d(e,...t){l.has(e)||(l.add(e),setTimeout(()=>l.delete(e),2e3),console.warn(e,...t))}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Object3D } from 'three';
|
|
2
|
+
import { AnimationClip, Quaternion } from 'three';
|
|
2
3
|
import type { AnimationRetargetPose, AnimationRetargeterData, AnimationRigChain, AnimationRigData, Asset, AssetId } from '../../scene/model.js';
|
|
3
4
|
export declare const ANIMATION_RETARGET_GENERATOR_VERSION = 9;
|
|
4
5
|
export type ExtractedAnimationRig = Omit<AnimationRigData, 'previewMeshId'>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { VectorKeyframeTrack, Bone, Object3D } from "three";
|
|
2
|
+
import { AnimationClip } from "three";
|
|
2
3
|
export declare class RootMotionClip extends AnimationClip {
|
|
3
4
|
motionTrack: VectorKeyframeTrack;
|
|
4
5
|
displacement: number;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Euler, Vector3 } from 'three';
|
|
1
|
+
import type { Euler, Vector3 } from 'three';
|
|
2
2
|
import { PrefabInstance } from '../../scene/objects/prefab.js';
|
|
3
3
|
import { BaseActor } from '../actors/actor.js';
|
|
4
4
|
import type { AssetsProvider } from '../../scene/assets-provider.js';
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Constructable, ContainerInstance } from "typedi";
|
|
2
|
-
import { ShaderType, ActorType, ActorComponentType } from '../shader/shader.js';
|
|
1
|
+
import type { Constructable, ContainerInstance } from "typedi";
|
|
2
|
+
import type { ShaderType, ActorType, ActorComponentType } from '../shader/shader.js';
|
|
3
3
|
import { World } from './services/world.js';
|
|
4
4
|
import { type DynamicResolutionOptions, type ExperimentalWebGpuPostProcessingOptions, type RenderingBackend, type UpscalingOptions } from '../rendering.js';
|
|
5
|
-
import { Observable } from 'rxjs';
|
|
6
|
-
import { DetailTier } from "../scene/model.js";
|
|
7
|
-
import { NetSession } from "./net/net-session.js";
|
|
5
|
+
import type { Observable } from 'rxjs';
|
|
6
|
+
import type { DetailTier } from "../scene/model.js";
|
|
7
|
+
import type { NetSession } from "./net/net-session.js";
|
|
8
8
|
import type { ParameterType } from "../shader/parameter.js";
|
|
9
9
|
type GameClass<T> = Constructable<T>;
|
|
10
10
|
export type InitiateGameConfig = {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ContainerInstance } from 'typedi';
|
|
1
|
+
import type { ContainerInstance } from 'typedi';
|
|
2
2
|
type Constructable<T> = abstract new (...args: any[]) => T;
|
|
3
3
|
export declare function inject<T>(type: Constructable<T>): T;
|
|
4
4
|
export declare function withInjectionContext<T>(containerInstance: ContainerInstance, fn: (diContainer: ContainerInstance) => T): T;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { BehaviorSubject, Subject } from 'rxjs';
|
|
2
|
-
import { NetReceivedMessage, NetSession
|
|
3
|
-
import {
|
|
2
|
+
import type { NetReceivedMessage, NetSession } from '../net-session.js';
|
|
3
|
+
import { NetMode } from '../net-session.js';
|
|
4
|
+
import type { NetConnection } from '../net-connection.js';
|
|
4
5
|
export type BrowserNetSimulationOptions = {
|
|
5
6
|
/**
|
|
6
7
|
* Fixed one-way latency applied to outgoing messages from this session.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{BehaviorSubject as e,Subject as s}from"rxjs";import{NetMode as t}from"../net-session";const n=0,i=0,r=0,o=0;export class BrowserNetSession{get isClient(){return this.mode===t.client}get isServer(){return this.mode<t.client}get isDedicatedServer(){return this.mode===t.dedicatedServer}get clients(){return this.isServer?this.currentMembers().filter(e=>e.mode===t.client).map(e=>a(e)):[]}get server(){if(!this.isServer){const e=this.currentMembers().find(e=>e.mode<t.client);if(null!=e)return a(e)}return null}constructor(t,n,i,r={}){this.sessionId=n,this.localId=i,this.playerLeft=new s,this.playerJoined=new s,this.receivedMessageCount=new e(0),this.storageKey=`net_session_${this.sessionId}`,this.channelName=`net_session_${this.sessionId}`,this.connected=!1,this.storage=null,this.channel=null,this.heartbeatTimer=null,this.receivedMessages=[],this.knownMemberIds=new Set,this.pendingDeliveryTimers=new Set,this.reliableQueues=new Map,this.messageSequence=0,this.onStorage=e=>{if(e.key!==this.storageKey)return;const s=this.getLocalStorage();this.setMembers(s?.members??[],!0)},this.onChannelMessage=e=>{const s=e.data;if(function(e){if(null==e||"object"!=typeof e)return!1;const s=e.kind;return"join"===s||"leave"===s||"heartbeat"===s||"members-request"===s||"members"===s||"message"===s}(s)&&s.sessionId===this.sessionId&&s.sourceConnectionId!==this.localId)switch(s.kind){case"join":case"heartbeat":this.mergeMember(s.member,!0);break;case"leave":this.removeMember(s.member.connectionId,!0);break;case"members-request":this.broadcast({kind:"members",sessionId:this.sessionId,sourceConnectionId:this.localId,members:this.currentMembers()});break;case"members":this.setMembers([...this.currentMembers(),...s.members],!0);break;case"message":this.mergeMember(s.fromMember,!0),s.message.toConnectionId===this.localId&&this.enqueueReceivedMessage(s.message)}},this.onBeforeUnload=()=>{this.disconnect()},this.onUnload=()=>{this.disconnect()},this.mode=t,this.id=n,this.simulation=l(r),this.heartbeatIntervalMs=Math.max(0,r.heartbeatIntervalMs??2e3),this.memberTimeoutMs=Math.max(1,r.memberTimeoutMs??1e4),this.maxQueuedMessages=Math.max(1,r.maxQueuedMessages??1e4)}configureNetworkSimulation(e){this.simulation=l({...this.simulation,...e})}reconnect(){this.disconnect(),this.connect()}disconnect(){this.connected&&this.broadcast({kind:"leave",sessionId:this.sessionId,sourceConnectionId:this.localId,member:this.createLocalMember()}),this.stopHeartbeat(),this.cancelPendingDeliveries(),this.connected&&(window.removeEventListener("storage",this.onStorage),window.removeEventListener("beforeunload",this.onBeforeUnload),window.removeEventListener("unload",this.onUnload),this.channel?.removeEventListener("message",this.onChannelMessage),this.channel?.close(),this.channel=null,this.connected=!1);const e=this.getLocalStorage(),s=(e?.members??this.storage?.members??[]).filter(e=>e.connectionId!==this.localId);this.writeLocalStorage({members:this.activeMembers(s)}),this.storage=null,this.knownMemberIds.clear(),this.receivedMessages=[],this.receivedMessageCount.next(0)}sendMessage(e,s,t){const n=function(e){const s=(e.id,Number(e.id));return Number.isFinite(s)?s:null}(e);if(null==n)return void console.error(`BrowserNetSession can only send to numeric connection ids. Received ${e.id}`);const i={id:this.createMessageId(),fromConnectionId:this.localId,toConnectionId:n,reliable:s,sentAt:Date.now(),buffer:c(t)};this.sendOrSimulateMessage(i,s)}hasMessage(){return this.receivedMessages.length}readMessage(){const e=this.consumeMessage();if(null!=e){const s=this.connectionForMessage(e);return null==s?(console.error(`No connection found with id ${e.fromConnectionId}`),null):{from:s,buffer:e.buffer}}return null}connect(){if(this.connected)return;if("undefined"==typeof BroadcastChannel)throw new Error("BrowserNetSession requires BroadcastChannel support");this.channel=new BroadcastChannel(this.channelName),this.channel.addEventListener("message",this.onChannelMessage),window.addEventListener("storage",this.onStorage),window.addEventListener("beforeunload",this.onBeforeUnload),window.addEventListener("unload",this.onUnload),this.connected=!0;const e=this.getLocalStorage()??{members:[]},s=this.activeMembers([...e.members,this.createLocalMember()]);this.setMembers(s,!1),this.writeLocalStorage({members:s}),this.broadcast({kind:"join",sessionId:this.sessionId,sourceConnectionId:this.localId,member:this.createLocalMember()}),this.broadcast({kind:"members-request",sessionId:this.sessionId,sourceConnectionId:this.localId}),this.startHeartbeat()}sendOrSimulateMessage(e,s){if(this.shouldDropMessage(s))return;if(s)return void this.enqueueReliableDelivery(e);const t=this.simulatedDelayMs();if(t<=0)return void this.deliverMessage(e);const n=window.setTimeout(()=>{this.pendingDeliveryTimers.delete(n),this.deliverMessage(e)},t);this.pendingDeliveryTimers.add(n)}deliverMessage(e){e.toConnectionId!==this.localId?this.broadcast({kind:"message",sessionId:this.sessionId,sourceConnectionId:this.localId,fromMember:this.createLocalMember(),message:e}):this.enqueueReceivedMessage(e)}enqueueReceivedMessage(e){this.receivedMessages.length>=this.maxQueuedMessages&&this.receivedMessages.shift(),this.receivedMessages.push(e),this.receivedMessageCount.next(this.receivedMessages.length)}consumeMessage(){const e=this.receivedMessages.shift()??null;return this.receivedMessageCount.next(this.receivedMessages.length),e}connectionForMessage(e){const s=this.server;if(s?.id===e.fromConnectionId)return s;const t=this.clients.find(s=>s.id===e.fromConnectionId);if(null!=t)return t;const n=this.currentMembers().find(s=>s.connectionId===e.fromConnectionId);return null!=n?a(n):null}enqueueReliableDelivery(e){const s=this.simulatedDelayMs(),t=this.reliableQueues.get(e.toConnectionId);if((null==t||0===t.messages.length)&&s<=0)return void this.deliverMessage(e);const n=Date.now(),i=t??{messages:[],timer:null},r=i.messages[i.messages.length-1]?.deliveryAt??n,o=Math.max(n+s,r);i.messages.push({message:e,deliveryAt:o}),this.reliableQueues.set(e.toConnectionId,i),this.scheduleReliableDelivery(e.toConnectionId,i)}scheduleReliableDelivery(e,s){if(null!=s.timer||0===s.messages.length)return;const t=Math.max(0,s.messages[0].deliveryAt-Date.now()),n=window.setTimeout(()=>{this.pendingDeliveryTimers.delete(n),s.timer=null,this.flushReliableDelivery(e)},t);s.timer=n,this.pendingDeliveryTimers.add(n)}flushReliableDelivery(e){const s=this.reliableQueues.get(e);if(null==s)return;const t=Date.now();for(;s.messages.length>0&&s.messages[0].deliveryAt<=t+1;)this.deliverMessage(s.messages.shift().message);s.messages.length>0?this.scheduleReliableDelivery(e,s):this.reliableQueues.delete(e)}shouldDropMessage(e){const s=e?this.simulation.reliablePacketLoss:this.simulation.packetLoss;return s>0&&Math.random()<s}simulatedDelayMs(){const e=this.simulation.jitterMs>0?(2*Math.random()-1)*this.simulation.jitterMs:0;return Math.max(0,this.simulation.latencyMs+e)}startHeartbeat(){this.heartbeatIntervalMs<=0||null!=this.heartbeatTimer||(this.heartbeatTimer=window.setInterval(()=>{const e=this.activeMembers([...this.currentMembers(),this.createLocalMember()]);this.setMembers(e,!0),this.writeLocalStorage({members:e}),this.broadcast({kind:"heartbeat",sessionId:this.sessionId,sourceConnectionId:this.localId,member:this.createLocalMember()})},this.heartbeatIntervalMs))}stopHeartbeat(){null!=this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}cancelPendingDeliveries(){this.pendingDeliveryTimers.forEach(e=>clearTimeout(e)),this.pendingDeliveryTimers.clear(),this.reliableQueues.clear()}mergeMember(e,s){this.setMembers([...this.currentMembers(),e],s)}removeMember(e,s){this.setMembers(this.currentMembers().filter(s=>s.connectionId!==e),s)}setMembers(e,s){const t=this.storage?.members??[],n=this.activeMembers(this.connected?[...e,this.createLocalMember()]:e);if(s){const e=new Set(n.map(e=>e.connectionId));n.filter(e=>e.connectionId!==this.localId&&!this.knownMemberIds.has(e.connectionId)).forEach(e=>this.playerJoined.next(a(e))),this.knownMemberIds.forEach(s=>{if(s===this.localId||e.has(s))return;const n=t.find(e=>e.connectionId===s);null!=n&&this.playerLeft.next(a(n))})}this.storage={members:n},this.knownMemberIds.clear(),n.forEach(e=>this.knownMemberIds.add(e.connectionId))}currentMembers(){return this.activeMembers(this.storage?.members??this.getLocalStorage()?.members??[])}activeMembers(e){const s=Date.now();return function(e){const s=new Map;for(const t of e){if(!Number.isFinite(t.connectionId))continue;const e=s.get(t.connectionId);(null==e||(t.lastSeenAt??0)>=(e.lastSeenAt??0))&&s.set(t.connectionId,t)}return[...s.values()].sort((e,s)=>e.connectionId-s.connectionId)}(e).filter(e=>e.connectionId===this.localId||null!=e.lastSeenAt&&s-e.lastSeenAt<=this.memberTimeoutMs)}createLocalMember(){return{connectionId:this.localId,mode:this.mode,player:{id:this.localId.toString()},lastSeenAt:Date.now()}}createMessageId(){const e=window.crypto?.randomUUID;return"function"==typeof e?e.call(window.crypto):`${this.localId}-${Date.now()}-${this.messageSequence++}`}broadcast(e){this.channel?.postMessage(e)}getLocalStorage(){const e=localStorage.getItem(this.storageKey);if(null!=e)try{const s=JSON.parse(e);if(Array.isArray(s?.members))return{members:s.members}}catch(e){console.warn(`Failed to parse browser net session ${this.sessionId}`,e)}return null}writeLocalStorage(e){const s=this.activeMembers(e.members);0!==s.length?localStorage.setItem(this.storageKey,JSON.stringify({members:s})):localStorage.removeItem(this.storageKey)}}function a(e){return{id:e.connectionId,player:e.player}}function c(e){const s=new Uint8Array(e),t=new Uint8Array(s.byteLength);return t.set(s),t.buffer}function l(e){return{latencyMs:Math.max(0,e.latencyMs??n),jitterMs:Math.max(0,e.jitterMs??i),packetLoss:h(e.packetLoss??r),reliablePacketLoss:h(e.reliablePacketLoss??o)}}function h(e){return Math.min(1,Math.max(0,e))}/*
|
|
1
|
+
import{BehaviorSubject as e,Subject as s}from"rxjs";import{NetMode as t}from"../net-session.js";const n=0,i=0,r=0,o=0;export class BrowserNetSession{get isClient(){return this.mode===t.client}get isServer(){return this.mode<t.client}get isDedicatedServer(){return this.mode===t.dedicatedServer}get clients(){return this.isServer?this.currentMembers().filter(e=>e.mode===t.client).map(e=>a(e)):[]}get server(){if(!this.isServer){const e=this.currentMembers().find(e=>e.mode<t.client);if(null!=e)return a(e)}return null}constructor(t,n,i,r={}){this.sessionId=n,this.localId=i,this.playerLeft=new s,this.playerJoined=new s,this.receivedMessageCount=new e(0),this.storageKey=`net_session_${this.sessionId}`,this.channelName=`net_session_${this.sessionId}`,this.connected=!1,this.storage=null,this.channel=null,this.heartbeatTimer=null,this.receivedMessages=[],this.knownMemberIds=new Set,this.pendingDeliveryTimers=new Set,this.reliableQueues=new Map,this.messageSequence=0,this.onStorage=e=>{if(e.key!==this.storageKey)return;const s=this.getLocalStorage();this.setMembers(s?.members??[],!0)},this.onChannelMessage=e=>{const s=e.data;if(function(e){if(null==e||"object"!=typeof e)return!1;const s=e.kind;return"join"===s||"leave"===s||"heartbeat"===s||"members-request"===s||"members"===s||"message"===s}(s)&&s.sessionId===this.sessionId&&s.sourceConnectionId!==this.localId)switch(s.kind){case"join":case"heartbeat":this.mergeMember(s.member,!0);break;case"leave":this.removeMember(s.member.connectionId,!0);break;case"members-request":this.broadcast({kind:"members",sessionId:this.sessionId,sourceConnectionId:this.localId,members:this.currentMembers()});break;case"members":this.setMembers([...this.currentMembers(),...s.members],!0);break;case"message":this.mergeMember(s.fromMember,!0),s.message.toConnectionId===this.localId&&this.enqueueReceivedMessage(s.message)}},this.onBeforeUnload=()=>{this.disconnect()},this.onUnload=()=>{this.disconnect()},this.mode=t,this.id=n,this.simulation=l(r),this.heartbeatIntervalMs=Math.max(0,r.heartbeatIntervalMs??2e3),this.memberTimeoutMs=Math.max(1,r.memberTimeoutMs??1e4),this.maxQueuedMessages=Math.max(1,r.maxQueuedMessages??1e4)}configureNetworkSimulation(e){this.simulation=l({...this.simulation,...e})}reconnect(){this.disconnect(),this.connect()}disconnect(){this.connected&&this.broadcast({kind:"leave",sessionId:this.sessionId,sourceConnectionId:this.localId,member:this.createLocalMember()}),this.stopHeartbeat(),this.cancelPendingDeliveries(),this.connected&&(window.removeEventListener("storage",this.onStorage),window.removeEventListener("beforeunload",this.onBeforeUnload),window.removeEventListener("unload",this.onUnload),this.channel?.removeEventListener("message",this.onChannelMessage),this.channel?.close(),this.channel=null,this.connected=!1);const e=this.getLocalStorage(),s=(e?.members??this.storage?.members??[]).filter(e=>e.connectionId!==this.localId);this.writeLocalStorage({members:this.activeMembers(s)}),this.storage=null,this.knownMemberIds.clear(),this.receivedMessages=[],this.receivedMessageCount.next(0)}sendMessage(e,s,t){const n=function(e){const s=(e.id,Number(e.id));return Number.isFinite(s)?s:null}(e);if(null==n)return void console.error(`BrowserNetSession can only send to numeric connection ids. Received ${e.id}`);const i={id:this.createMessageId(),fromConnectionId:this.localId,toConnectionId:n,reliable:s,sentAt:Date.now(),buffer:c(t)};this.sendOrSimulateMessage(i,s)}hasMessage(){return this.receivedMessages.length}readMessage(){const e=this.consumeMessage();if(null!=e){const s=this.connectionForMessage(e);return null==s?(console.error(`No connection found with id ${e.fromConnectionId}`),null):{from:s,buffer:e.buffer}}return null}connect(){if(this.connected)return;if("undefined"==typeof BroadcastChannel)throw new Error("BrowserNetSession requires BroadcastChannel support");this.channel=new BroadcastChannel(this.channelName),this.channel.addEventListener("message",this.onChannelMessage),window.addEventListener("storage",this.onStorage),window.addEventListener("beforeunload",this.onBeforeUnload),window.addEventListener("unload",this.onUnload),this.connected=!0;const e=this.getLocalStorage()??{members:[]},s=this.activeMembers([...e.members,this.createLocalMember()]);this.setMembers(s,!1),this.writeLocalStorage({members:s}),this.broadcast({kind:"join",sessionId:this.sessionId,sourceConnectionId:this.localId,member:this.createLocalMember()}),this.broadcast({kind:"members-request",sessionId:this.sessionId,sourceConnectionId:this.localId}),this.startHeartbeat()}sendOrSimulateMessage(e,s){if(this.shouldDropMessage(s))return;if(s)return void this.enqueueReliableDelivery(e);const t=this.simulatedDelayMs();if(t<=0)return void this.deliverMessage(e);const n=window.setTimeout(()=>{this.pendingDeliveryTimers.delete(n),this.deliverMessage(e)},t);this.pendingDeliveryTimers.add(n)}deliverMessage(e){e.toConnectionId!==this.localId?this.broadcast({kind:"message",sessionId:this.sessionId,sourceConnectionId:this.localId,fromMember:this.createLocalMember(),message:e}):this.enqueueReceivedMessage(e)}enqueueReceivedMessage(e){this.receivedMessages.length>=this.maxQueuedMessages&&this.receivedMessages.shift(),this.receivedMessages.push(e),this.receivedMessageCount.next(this.receivedMessages.length)}consumeMessage(){const e=this.receivedMessages.shift()??null;return this.receivedMessageCount.next(this.receivedMessages.length),e}connectionForMessage(e){const s=this.server;if(s?.id===e.fromConnectionId)return s;const t=this.clients.find(s=>s.id===e.fromConnectionId);if(null!=t)return t;const n=this.currentMembers().find(s=>s.connectionId===e.fromConnectionId);return null!=n?a(n):null}enqueueReliableDelivery(e){const s=this.simulatedDelayMs(),t=this.reliableQueues.get(e.toConnectionId);if((null==t||0===t.messages.length)&&s<=0)return void this.deliverMessage(e);const n=Date.now(),i=t??{messages:[],timer:null},r=i.messages[i.messages.length-1]?.deliveryAt??n,o=Math.max(n+s,r);i.messages.push({message:e,deliveryAt:o}),this.reliableQueues.set(e.toConnectionId,i),this.scheduleReliableDelivery(e.toConnectionId,i)}scheduleReliableDelivery(e,s){if(null!=s.timer||0===s.messages.length)return;const t=Math.max(0,s.messages[0].deliveryAt-Date.now()),n=window.setTimeout(()=>{this.pendingDeliveryTimers.delete(n),s.timer=null,this.flushReliableDelivery(e)},t);s.timer=n,this.pendingDeliveryTimers.add(n)}flushReliableDelivery(e){const s=this.reliableQueues.get(e);if(null==s)return;const t=Date.now();for(;s.messages.length>0&&s.messages[0].deliveryAt<=t+1;)this.deliverMessage(s.messages.shift().message);s.messages.length>0?this.scheduleReliableDelivery(e,s):this.reliableQueues.delete(e)}shouldDropMessage(e){const s=e?this.simulation.reliablePacketLoss:this.simulation.packetLoss;return s>0&&Math.random()<s}simulatedDelayMs(){const e=this.simulation.jitterMs>0?(2*Math.random()-1)*this.simulation.jitterMs:0;return Math.max(0,this.simulation.latencyMs+e)}startHeartbeat(){this.heartbeatIntervalMs<=0||null!=this.heartbeatTimer||(this.heartbeatTimer=window.setInterval(()=>{const e=this.activeMembers([...this.currentMembers(),this.createLocalMember()]);this.setMembers(e,!0),this.writeLocalStorage({members:e}),this.broadcast({kind:"heartbeat",sessionId:this.sessionId,sourceConnectionId:this.localId,member:this.createLocalMember()})},this.heartbeatIntervalMs))}stopHeartbeat(){null!=this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}cancelPendingDeliveries(){this.pendingDeliveryTimers.forEach(e=>clearTimeout(e)),this.pendingDeliveryTimers.clear(),this.reliableQueues.clear()}mergeMember(e,s){this.setMembers([...this.currentMembers(),e],s)}removeMember(e,s){this.setMembers(this.currentMembers().filter(s=>s.connectionId!==e),s)}setMembers(e,s){const t=this.storage?.members??[],n=this.activeMembers(this.connected?[...e,this.createLocalMember()]:e);if(s){const e=new Set(n.map(e=>e.connectionId));n.filter(e=>e.connectionId!==this.localId&&!this.knownMemberIds.has(e.connectionId)).forEach(e=>this.playerJoined.next(a(e))),this.knownMemberIds.forEach(s=>{if(s===this.localId||e.has(s))return;const n=t.find(e=>e.connectionId===s);null!=n&&this.playerLeft.next(a(n))})}this.storage={members:n},this.knownMemberIds.clear(),n.forEach(e=>this.knownMemberIds.add(e.connectionId))}currentMembers(){return this.activeMembers(this.storage?.members??this.getLocalStorage()?.members??[])}activeMembers(e){const s=Date.now();return function(e){const s=new Map;for(const t of e){if(!Number.isFinite(t.connectionId))continue;const e=s.get(t.connectionId);(null==e||(t.lastSeenAt??0)>=(e.lastSeenAt??0))&&s.set(t.connectionId,t)}return[...s.values()].sort((e,s)=>e.connectionId-s.connectionId)}(e).filter(e=>e.connectionId===this.localId||null!=e.lastSeenAt&&s-e.lastSeenAt<=this.memberTimeoutMs)}createLocalMember(){return{connectionId:this.localId,mode:this.mode,player:{id:this.localId.toString()},lastSeenAt:Date.now()}}createMessageId(){const e=window.crypto?.randomUUID;return"function"==typeof e?e.call(window.crypto):`${this.localId}-${Date.now()}-${this.messageSequence++}`}broadcast(e){this.channel?.postMessage(e)}getLocalStorage(){const e=localStorage.getItem(this.storageKey);if(null!=e)try{const s=JSON.parse(e);if(Array.isArray(s?.members))return{members:s.members}}catch(e){console.warn(`Failed to parse browser net session ${this.sessionId}`,e)}return null}writeLocalStorage(e){const s=this.activeMembers(e.members);0!==s.length?localStorage.setItem(this.storageKey,JSON.stringify({members:s})):localStorage.removeItem(this.storageKey)}}function a(e){return{id:e.connectionId,player:e.player}}function c(e){const s=new Uint8Array(e),t=new Uint8Array(s.byteLength);return t.set(s),t.buffer}function l(e){return{latencyMs:Math.max(0,e.latencyMs??n),jitterMs:Math.max(0,e.jitterMs??i),packetLoss:h(e.packetLoss??r),reliablePacketLoss:h(e.reliablePacketLoss??o)}}function h(e){return Math.min(1,Math.max(0,e))}/*
|
|
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
|
-
import { Observable } from "rxjs";
|
|
2
|
-
import { NetConnection } from "./net-connection.js";
|
|
1
|
+
import type { Observable } from "rxjs";
|
|
2
|
+
import type { NetConnection } from "./net-connection.js";
|
|
3
3
|
export declare enum NetMode {
|
|
4
4
|
/**
|
|
5
5
|
* Game is played locally so it has authority but no other clients are connected.
|