@hology/core 0.0.235 → 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/effects/vfx/vfx-defs.d.ts +2 -0
- package/dist/effects/vfx/vfx-defs.js +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/index.d.ts +1 -0
- package/dist/gameplay/actors/index.js +1 -1
- package/dist/rendering/node-material-webgpu-resolver.js +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/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -121,6 +121,7 @@ declare class PositionCircleDef extends BaseIniDef<PositionCircleDef> {
|
|
|
121
121
|
position: ShapeParameterDef<Vector3>;
|
|
122
122
|
rotation: ShapeParameterDef<Vector3>;
|
|
123
123
|
radius: FloatParameterDef;
|
|
124
|
+
angle: FloatParameterDef;
|
|
124
125
|
};
|
|
125
126
|
bindingAdapter: VfxBindingAdapter<Position>;
|
|
126
127
|
make(params?: ParamsType<this>): Initializer;
|
|
@@ -131,6 +132,7 @@ declare class PositionRingDef extends BaseIniDef<PositionRingDef> {
|
|
|
131
132
|
rotation: ShapeParameterDef<Vector3>;
|
|
132
133
|
radius: FloatParameterDef;
|
|
133
134
|
thickness: FloatParameterDef;
|
|
135
|
+
angle: FloatParameterDef;
|
|
134
136
|
};
|
|
135
137
|
bindingAdapter: VfxBindingAdapter<Position>;
|
|
136
138
|
make(params?: ParamsType<this>): Initializer;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LoopOnce as e,LoopPingPong as t,LoopRepeat as s,MathUtils as n,Vector2 as r,Vector3 as a}from"three";import{Alpha as i,Attraction as o,BoxZone as c,CircleZone as p,Color as u,ease as d,Force as m,Gravity as l,Life as w,LineZone as f,Mass as h,Position as x,RadialVelocity as g,RandomDrift as b,Repulsion as y,Rotate as k,Vector3D as v}from"@hology/nebula";import{AnimationBehavior as A,AxisDirection as z,AxisPlane as R,Disperse as L,FollowParent as C,LinearDamping as D,MoveOverLife as S,OrientAlongVelocity as T,RotatePosition as V,Scale as j,ScaleComponents as Y}from"./behaviours.js";import{AdditiveVelocity as B,AlignRotation as F,alignRotationAxes as O,alignRotationModes as P,InitialScale as X,InitialScaleComponents as Z,RandomColor as I,RandomDirection as M,RandomRotation as K,randomRotationAxis as W,RandomScale as q,Rotation as E}from"./initializsers.js";import{PointZone as G,SphereZone as H}from"./zones.js";import{WorldCollisionBehaviour as J}from"./vfx-collision-behaviour.js";import{Curve2 as N}from"../../utils/curve.js";import{liveBindingAdapter as Q,spawnBindingAdapter as U}from"./vfx-binding-runtime.js";class ${build(e={}){const t=pe(e,this.parameters);return this.make(t)}}class _{build(e={}){const t=pe(e,this.parameters);return this.make(t)}}function ee(e,t,s){return{type:"number",default:e,float:!0,min:t,max:s}}function te(e,t,s,n){return{...ee(e,s,n),bindable:t}}function se(e){return{type:"boolean",default:e}}function ne(e){return{type:"vec3",default:(new a).fromArray(e)}}function re(e,t){return{...ne(e),bindable:t}}function ae(e){return{type:"color",default:e}}function ie(e,t){return{...ae(e),bindable:t}}function oe(e,t){return{type:"select",opts:e,default:t}}function ce(){return{type:"curve",default:N.linear()}}function pe(e,t){const s={};for(let n in t)null==e[n]?s[n]=t[n].default:s[n]=e[n];return s}function ue(e){return new v(e.x,e.y,e.z)}function de(e){return new a(n.degToRad(e.x),n.degToRad(e.y),n.degToRad(e.z))}function me(e){const{x:t,y:s,z:n}=e;return new G(t,s,n)}function le(e,t){const{x:s,y:n,z:r}=e,{x:a,y:i,z:o}=t;return new c(s,n,r,a,i,o)}function we(e,t,s=!1){const{x:n,y:r,z:a}=e;return new H(n,r,a,t,s)}function fe(e,t){return new f(e.x,e.y,e.z,t.x,t.y,t.z)}function he(e,t,s,r=0){return new p(e.x,e.y,e.z,s,r,n.degToRad(t.x),n.degToRad(t.y),n.degToRad(t.z))}function xe(e){return t=>e.getY(t)}const ge={lifetime:new class extends _{constructor(){super(...arguments),this.parameters={duration:te(1,"spawn",0,1e5)},this.bindingAdapter=U((e,t)=>{e.resetLife(t.duration)})}make(e={}){return new w(e.duration)}},randomLifetime:new class extends _{constructor(){super(...arguments),this.parameters={minDuration:te(1,"spawn",0,1e5),maxDuration:te(2,"spawn",0,1e5)},this.bindingAdapter=U((e,t)=>{e.resetLife(t.minDuration,t.maxDuration)})}make(e={}){return new w(e.minDuration,e.maxDuration)}},positionPoint:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn")},this.bindingAdapter=U((e,t)=>{e.reset(me(t.position))})}make(e={}){return new x(me(e.position))}},positionBox:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn"),dimensions:re([0,0,0],"spawn")},this.bindingAdapter=U((e,t)=>{e.reset(le(t.position,t.dimensions))})}make(e={}){return new x(le(e.position,e.dimensions))}},positionSphere:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn"),radius:te(1,"spawn"),surface:se(!1)},this.bindingAdapter=U((e,t)=>{e.reset(we(t.position,t.radius,t.surface))})}make(e={}){return new x(we(e.position,e.radius,e.surface))}},positionLine:new class extends _{constructor(){super(...arguments),this.parameters={a:re([0,0,0],"spawn"),b:re([0,0,1],"spawn")},this.bindingAdapter=U((e,t)=>{e.reset(fe(t.a,t.b))})}make(e={}){return new x(fe(e.a,e.b))}},positionCircle:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn"),rotation:re([0,0,0],"spawn"),radius:te(1,"spawn",0,1e4)},this.bindingAdapter=U((e,t)=>{e.reset(he(t.position,t.rotation,t.radius))})}make(e={}){return new x(he(e.position,e.rotation,e.radius))}},positionRing:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn"),rotation:re([0,0,0],"spawn"),radius:te(1,"spawn",0,1e4),thickness:te(.2,"spawn",0,1e4)},this.bindingAdapter=U((e,t)=>{e.reset(he(t.position,t.rotation,t.radius,Math.max(t.thickness,1e-4)))})}make(e={}){return new x(he(e.position,e.rotation,e.radius,Math.max(e.thickness,1e-4)))}},rotation:new class extends _{constructor(){super(...arguments),this.parameters={rotation:re([0,0,0],"spawn")},this.bindingAdapter=U((e,t)=>{e.setRotation(de(t.rotation))})}make(e={}){return new E(de(e.rotation))}},randomRotation:new class extends _{constructor(){super(...arguments),this.parameters={axis:oe(W,"XYZ")}}make(e={}){return new K(e.axis)}},scale:new class extends _{constructor(){super(...arguments),this.parameters={scale:te(1,"spawn")},this.bindingAdapter=U((e,t)=>{e.setScale(t.scale)})}make(e={}){return new X(e.scale)}},scaleComponents:new class extends _{constructor(){super(...arguments),this.parameters={scale:re([1,1,1],"spawn")},this.bindingAdapter=U((e,t)=>{e.setScaleComponents(t.scale)})}make(e={}){return new Z(e.scale)}},randomScale:new class extends _{constructor(){super(...arguments),this.parameters={min:te(1,"spawn"),max:te(1,"spawn")},this.bindingAdapter=U((e,t)=>{e.setRange(t.min,t.max)})}make(e={}){return new q(e.min,e.max)}},randomColor:new class extends _{constructor(){super(...arguments),this.parameters={a:ie("#ffffff","spawn"),b:ie("#ffffff","spawn")},this.bindingAdapter=U((e,t)=>{e.setRange(t.a,t.b)})}make(e={}){return new I(e.a,e.b)}},mass:new class extends _{constructor(){super(...arguments),this.parameters={min:te(1,"spawn")},this.bindingAdapter=U((e,t)=>{e.resetMass(t.min)})}make(e={}){return new h(e.min)}},velocity:new class extends _{constructor(){super(...arguments),this.parameters={velocity:re([0,0,0],"spawn")},this.bindingAdapter={buildBound:e=>new B(()=>e.get("velocity"))}}make(e={}){const{x:t,y:s,z:n}=e.velocity;return new B(new a(t,s,n))}},randomVelocity:new class extends _{constructor(){super(...arguments),this.parameters={min:re([0,0,0],"spawn"),max:re([0,0,0],"spawn")},this.bindingAdapter={buildBound:e=>new B(()=>e.get("min"),()=>e.get("max"))}}make(e={}){return new B(e.min,e.max)}},radialVelocity:new class extends _{constructor(){super(...arguments),this.parameters={speed:te(1,"spawn"),direction:re([0,1,0],"spawn"),spread:te(0,"spawn")},this.bindingAdapter=U((e,t)=>{e.resetRadialVelocity(t.speed,ue(t.direction),t.spread)})}make(e={}){return new g(e.speed,ue(e.direction),e.spread)}},randomDirection:new class extends _{constructor(){super(...arguments),this.parameters={speed:te(1,"spawn")},this.bindingAdapter=U((e,t)=>{e.setSpeed(t.speed)})}make(e={}){return new M(e.speed)}},alignRotation:new class extends _{constructor(){super(...arguments),this.parameters={mode:oe(P,"AwayFromCenter"),axis:oe(O,"+Y"),offset:ne([0,0,0]),center:ne([0,0,0])}}make(e={}){return new F(e.axis,e.mode,de(e.offset),e.center)}}},be={force:new class extends ${constructor(){super(...arguments),this.parameters={force:re([0,0,0],"live"),ease:ce()},this.bindingAdapter=Q((e,t)=>{const s=t.force;e.setForce(s.x,s.y,s.z)})}make(e={}){return new m(e.force.x,e.force.y,e.force.z,void 0,xe(e.ease))}},gravity:new class extends ${constructor(){super(...arguments),this.parameters={gravity:te(8,"live"),easing:ce()},this.bindingAdapter=Q((e,t)=>{e.setForce(0,-t.gravity,0)})}make(e={}){return new l(e.gravity,void 0,xe(e.easing))}},repulsion:new class extends ${constructor(){super(...arguments),this.parameters={target:re([0,0,0],"live"),force:te(1,"live"),radius:te(1,"live"),easing:ce()},this.bindingAdapter=Q((e,t)=>{e.resetAttraction(ue(t.target),t.force,t.radius)})}make(e={}){const t=ue(e.target);return new y(t,e.force,e.radius,void 0,xe(e.easing))}},attraction:new class extends ${constructor(){super(...arguments),this.parameters={target:re([0,0,0],"live"),force:te(1,"live"),radius:te(1,"live"),easing:ce()},this.bindingAdapter=Q((e,t)=>{e.resetAttraction(ue(t.target),t.force,t.radius)})}make(e={}){const t=ue(e.target);return new o(t,e.force,e.radius,void 0,xe(e.easing))}},scale:new class extends ${constructor(){super(...arguments),this.parameters={a:te(1,"spawn"),b:te(1,"spawn"),ease:ce()},this.bindingAdapter=U((e,t)=>{e.setScaleRange(t.a,t.b)})}make(e={}){return new j(e.a,e.b,xe(e.ease))}},scaleComponents:new class extends ${constructor(){super(...arguments),this.parameters={a:re([1,1,1],"spawn"),b:re([1,1,1],"spawn"),ease:ce()},this.bindingAdapter=U((e,t)=>{e.setScaleRange(t.a,t.b)})}make(e={}){return new Y(e.a,e.b,xe(e.ease))}},randomDrift:new class extends ${constructor(){super(...arguments),this.parameters={drift:re([1,1,1],"live"),delay:te(0,"live"),ease:ce()},this.bindingAdapter=Q((e,t)=>{const s=t.drift;e.setDrift(s.x,s.y,s.z,t.delay)})}make(e={}){return new b(e.drift.x,e.drift.y,e.drift.z,e.delay,void 0,xe(e.ease))}},disperse:new class extends ${constructor(){super(...arguments),this.parameters={distance:te(1,"spawn"),axis:oe(["XYZ","XZ","XY","YZ"],"XYZ"),ease:ce()},this.bindingAdapter=U((e,t)=>{e.setDistance(t.distance)})}make(e={}){return new L(e.distance,R[e.axis.toLowerCase()],xe(e.ease))}},rotate:new class extends ${constructor(){super(...arguments),this.parameters={rotation:re([0,0,0],"spawn"),ease:ce()},this.bindingAdapter=U((e,t)=>{const s=de(t.rotation);e.resetRotation(s.x,s.y,s.z)})}make(e={}){const t=de(e.rotation);return new k(t.x,t.y,t.z,void 0,xe(e.ease))}},rotateAdd:new class extends ${constructor(){super(...arguments),this.parameters={rotation:re([0,0,0],"spawn")},this.bindingAdapter=U((e,t)=>{const s=de(t.rotation);e.resetRotation(s.x,s.y,s.z)})}make(e={}){const t=de(e.rotation),s=new k(t.x,t.y,t.z,void 0);return s.rotationType="add",s}},changeColor:new class extends ${constructor(){super(...arguments),this.parameters={a:ie("#ffffff","spawn"),b:ie("#ffffff","spawn"),ease:ce()},this.bindingAdapter=U((e,t)=>{e.resetColor(t.a,t.b)})}make(e={}){return new u(e.a,e.b,void 0,xe(e.ease))}},changeOpacity:new class extends ${constructor(){super(...arguments),this.parameters={a:te(1,"spawn",0,1),b:te(0,"spawn",0,1),ease:ce()},this.bindingAdapter=U((e,t)=>{e.resetAlpha(t.a,t.b)})}make(e={}){return new i(e.a,e.b,void 0,xe(e.ease))}},vortex:new class extends ${constructor(){super(...arguments),this.parameters={axis:re([0,1,0],"live"),amount:te(1,"live")},this.bindingAdapter=Q((e,t)=>{e.setAxisAngle(t.axis,t.amount)})}make(e={}){return new V(e.axis,e.amount)}},moveTo:new class extends ${constructor(){super(...arguments),this.parameters={target:re([0,1,0],"live"),ease:ce()},this.bindingAdapter=Q((e,t)=>{const s=t.target;e.setTarget(s.x,s.y,s.z)})}make(e={}){return new S(e.target.x,e.target.y,e.target.z,xe(e.ease))}},linearDamping:new class extends ${constructor(){super(...arguments),this.parameters={factor:te(.1,"live",0,1e3)},this.bindingAdapter=Q((e,t)=>{e.setFactor(t.factor)})}make(e={}){return new D(e.factor)}},followParent:new class extends ${constructor(){super(...arguments),this.parameters={speed:te(0,"live")},this.bindingAdapter=Q((e,t)=>{e.setSpeed(t.speed)})}make(e={}){return new C(e.speed)}},worldCollision:new class extends ${constructor(){super(...arguments),this.parameters={friction:ee(1,0,1),bounce:ee(1,0,1),lifeLoss:ee(0,0)}}make(e={}){return new J(null,e.bounce,e.friction,e.lifeLoss)}},animation:new class extends ${constructor(){super(...arguments),this.parameters={clip:{type:"animationclip",default:null},timeScale:ee(1,0,10),weight:ee(1,0,1),loop:oe(["Once","Repeat","PingPong"],"Once"),clampWhenFinished:{...se(!0),requires:{loop:"Once"}}}}make(n={}){let r=e;return"Repeat"===n.loop?r=s:"PingPong"===n.loop&&(r=t),new A(n.clip,n.timeScale,n.weight,r,n.clampWhenFinished,d.easeLinear)}}};export const VfxInitializserLibrary=ge;export const VfxInitializserLibraryKeys=Object.keys(VfxInitializserLibrary);export const VfxBehaviourLibrary=be;export const VfxBehaviourLibraryKeys=Object.keys(VfxBehaviourLibrary);/*
|
|
1
|
+
import{LoopOnce as e,LoopPingPong as t,LoopRepeat as n,MathUtils as s,Vector2 as r,Vector3 as a}from"three";import{Alpha as i,Attraction as o,BoxZone as c,CircleZone as p,Color as d,ease as u,Force as l,Gravity as m,Life as w,LineZone as f,Mass as h,Position as x,RadialVelocity as g,RandomDrift as b,Repulsion as y,Rotate as k,Vector3D as v}from"@hology/nebula";import{AnimationBehavior as A,AxisDirection as z,AxisPlane as R,Disperse as L,FollowParent as C,LinearDamping as D,MoveOverLife as S,OrientAlongVelocity as T,RotatePosition as V,Scale as j,ScaleComponents as Y}from"./behaviours.js";import{AdditiveVelocity as B,AlignRotation as F,alignRotationAxes as O,alignRotationModes as P,InitialScale as X,InitialScaleComponents as Z,RandomColor as I,RandomDirection as M,RandomRotation as K,randomRotationAxis as W,RandomScale as q,Rotation as E}from"./initializsers.js";import{PointZone as G,SphereZone as H}from"./zones.js";import{WorldCollisionBehaviour as J}from"./vfx-collision-behaviour.js";import{Curve2 as N}from"../../utils/curve.js";import{liveBindingAdapter as Q,spawnBindingAdapter as U}from"./vfx-binding-runtime.js";class ${build(e={}){const t=pe(e,this.parameters);return this.make(t)}}class _{build(e={}){const t=pe(e,this.parameters);return this.make(t)}}function ee(e,t,n){return{type:"number",default:e,float:!0,min:t,max:n}}function te(e,t,n,s){return{...ee(e,n,s),bindable:t}}function ne(e){return{type:"boolean",default:e}}function se(e){return{type:"vec3",default:(new a).fromArray(e)}}function re(e,t){return{...se(e),bindable:t}}function ae(e){return{type:"color",default:e}}function ie(e,t){return{...ae(e),bindable:t}}function oe(e,t){return{type:"select",opts:e,default:t}}function ce(){return{type:"curve",default:N.linear()}}function pe(e,t){const n={};for(let s in t)null==e[s]?n[s]=t[s].default:n[s]=e[s];return n}function de(e){return new v(e.x,e.y,e.z)}function ue(e){return new a(s.degToRad(e.x),s.degToRad(e.y),s.degToRad(e.z))}function le(e){const{x:t,y:n,z:s}=e;return new G(t,n,s)}function me(e,t){const{x:n,y:s,z:r}=e,{x:a,y:i,z:o}=t;return new c(n,s,r,a,i,o)}function we(e,t,n=!1){const{x:s,y:r,z:a}=e;return new H(s,r,a,t,n)}function fe(e,t){return new f(e.x,e.y,e.z,t.x,t.y,t.z)}function he(e,t,n,r=0,a=360){return new p(e.x,e.y,e.z,n,r,s.degToRad(t.x),s.degToRad(t.y),s.degToRad(t.z),s.degToRad(a))}function xe(e){return t=>e.getY(t)}const ge={lifetime:new class extends _{constructor(){super(...arguments),this.parameters={duration:te(1,"spawn",0,1e5)},this.bindingAdapter=U((e,t)=>{e.resetLife(t.duration)})}make(e={}){return new w(e.duration)}},randomLifetime:new class extends _{constructor(){super(...arguments),this.parameters={minDuration:te(1,"spawn",0,1e5),maxDuration:te(2,"spawn",0,1e5)},this.bindingAdapter=U((e,t)=>{e.resetLife(t.minDuration,t.maxDuration)})}make(e={}){return new w(e.minDuration,e.maxDuration)}},positionPoint:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn")},this.bindingAdapter=U((e,t)=>{e.reset(le(t.position))})}make(e={}){return new x(le(e.position))}},positionBox:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn"),dimensions:re([0,0,0],"spawn")},this.bindingAdapter=U((e,t)=>{e.reset(me(t.position,t.dimensions))})}make(e={}){return new x(me(e.position,e.dimensions))}},positionSphere:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn"),radius:te(1,"spawn"),surface:ne(!1)},this.bindingAdapter=U((e,t)=>{e.reset(we(t.position,t.radius,t.surface))})}make(e={}){return new x(we(e.position,e.radius,e.surface))}},positionLine:new class extends _{constructor(){super(...arguments),this.parameters={a:re([0,0,0],"spawn"),b:re([0,0,1],"spawn")},this.bindingAdapter=U((e,t)=>{e.reset(fe(t.a,t.b))})}make(e={}){return new x(fe(e.a,e.b))}},positionCircle:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn"),rotation:re([0,0,0],"spawn"),radius:te(1,"spawn",0,1e4),angle:te(360,"spawn",0,360)},this.bindingAdapter=U((e,t)=>{e.reset(he(t.position,t.rotation,t.radius,0,t.angle))})}make(e={}){return new x(he(e.position,e.rotation,e.radius,0,e.angle))}},positionRing:new class extends _{constructor(){super(...arguments),this.parameters={position:re([0,0,0],"spawn"),rotation:re([0,0,0],"spawn"),radius:te(1,"spawn",0,1e4),thickness:te(.2,"spawn",0,1e4),angle:te(360,"spawn",0,360)},this.bindingAdapter=U((e,t)=>{e.reset(he(t.position,t.rotation,t.radius,Math.max(t.thickness,1e-4),t.angle))})}make(e={}){return new x(he(e.position,e.rotation,e.radius,Math.max(e.thickness,1e-4),e.angle))}},rotation:new class extends _{constructor(){super(...arguments),this.parameters={rotation:re([0,0,0],"spawn")},this.bindingAdapter=U((e,t)=>{e.setRotation(ue(t.rotation))})}make(e={}){return new E(ue(e.rotation))}},randomRotation:new class extends _{constructor(){super(...arguments),this.parameters={axis:oe(W,"XYZ")}}make(e={}){return new K(e.axis)}},scale:new class extends _{constructor(){super(...arguments),this.parameters={scale:te(1,"spawn")},this.bindingAdapter=U((e,t)=>{e.setScale(t.scale)})}make(e={}){return new X(e.scale)}},scaleComponents:new class extends _{constructor(){super(...arguments),this.parameters={scale:re([1,1,1],"spawn")},this.bindingAdapter=U((e,t)=>{e.setScaleComponents(t.scale)})}make(e={}){return new Z(e.scale)}},randomScale:new class extends _{constructor(){super(...arguments),this.parameters={min:te(1,"spawn"),max:te(1,"spawn")},this.bindingAdapter=U((e,t)=>{e.setRange(t.min,t.max)})}make(e={}){return new q(e.min,e.max)}},randomColor:new class extends _{constructor(){super(...arguments),this.parameters={a:ie("#ffffff","spawn"),b:ie("#ffffff","spawn")},this.bindingAdapter=U((e,t)=>{e.setRange(t.a,t.b)})}make(e={}){return new I(e.a,e.b)}},mass:new class extends _{constructor(){super(...arguments),this.parameters={min:te(1,"spawn")},this.bindingAdapter=U((e,t)=>{e.resetMass(t.min)})}make(e={}){return new h(e.min)}},velocity:new class extends _{constructor(){super(...arguments),this.parameters={velocity:re([0,0,0],"spawn")},this.bindingAdapter={buildBound:e=>new B(()=>e.get("velocity"))}}make(e={}){const{x:t,y:n,z:s}=e.velocity;return new B(new a(t,n,s))}},randomVelocity:new class extends _{constructor(){super(...arguments),this.parameters={min:re([0,0,0],"spawn"),max:re([0,0,0],"spawn")},this.bindingAdapter={buildBound:e=>new B(()=>e.get("min"),()=>e.get("max"))}}make(e={}){return new B(e.min,e.max)}},radialVelocity:new class extends _{constructor(){super(...arguments),this.parameters={speed:te(1,"spawn"),direction:re([0,1,0],"spawn"),spread:te(0,"spawn")},this.bindingAdapter=U((e,t)=>{e.resetRadialVelocity(t.speed,de(t.direction),t.spread)})}make(e={}){return new g(e.speed,de(e.direction),e.spread)}},randomDirection:new class extends _{constructor(){super(...arguments),this.parameters={speed:te(1,"spawn")},this.bindingAdapter=U((e,t)=>{e.setSpeed(t.speed)})}make(e={}){return new M(e.speed)}},alignRotation:new class extends _{constructor(){super(...arguments),this.parameters={mode:oe(P,"AwayFromCenter"),axis:oe(O,"+Y"),offset:se([0,0,0]),center:se([0,0,0])}}make(e={}){return new F(e.axis,e.mode,ue(e.offset),e.center)}}},be={force:new class extends ${constructor(){super(...arguments),this.parameters={force:re([0,0,0],"live"),ease:ce()},this.bindingAdapter=Q((e,t)=>{const n=t.force;e.setForce(n.x,n.y,n.z)})}make(e={}){return new l(e.force.x,e.force.y,e.force.z,void 0,xe(e.ease))}},gravity:new class extends ${constructor(){super(...arguments),this.parameters={gravity:te(8,"live"),easing:ce()},this.bindingAdapter=Q((e,t)=>{e.setForce(0,-t.gravity,0)})}make(e={}){return new m(e.gravity,void 0,xe(e.easing))}},repulsion:new class extends ${constructor(){super(...arguments),this.parameters={target:re([0,0,0],"live"),force:te(1,"live"),radius:te(1,"live"),easing:ce()},this.bindingAdapter=Q((e,t)=>{e.resetAttraction(de(t.target),t.force,t.radius)})}make(e={}){const t=de(e.target);return new y(t,e.force,e.radius,void 0,xe(e.easing))}},attraction:new class extends ${constructor(){super(...arguments),this.parameters={target:re([0,0,0],"live"),force:te(1,"live"),radius:te(1,"live"),easing:ce()},this.bindingAdapter=Q((e,t)=>{e.resetAttraction(de(t.target),t.force,t.radius)})}make(e={}){const t=de(e.target);return new o(t,e.force,e.radius,void 0,xe(e.easing))}},scale:new class extends ${constructor(){super(...arguments),this.parameters={a:te(1,"spawn"),b:te(1,"spawn"),ease:ce()},this.bindingAdapter=U((e,t)=>{e.setScaleRange(t.a,t.b)})}make(e={}){return new j(e.a,e.b,xe(e.ease))}},scaleComponents:new class extends ${constructor(){super(...arguments),this.parameters={a:re([1,1,1],"spawn"),b:re([1,1,1],"spawn"),ease:ce()},this.bindingAdapter=U((e,t)=>{e.setScaleRange(t.a,t.b)})}make(e={}){return new Y(e.a,e.b,xe(e.ease))}},randomDrift:new class extends ${constructor(){super(...arguments),this.parameters={drift:re([1,1,1],"live"),delay:te(0,"live"),ease:ce()},this.bindingAdapter=Q((e,t)=>{const n=t.drift;e.setDrift(n.x,n.y,n.z,t.delay)})}make(e={}){return new b(e.drift.x,e.drift.y,e.drift.z,e.delay,void 0,xe(e.ease))}},disperse:new class extends ${constructor(){super(...arguments),this.parameters={distance:te(1,"spawn"),axis:oe(["XYZ","XZ","XY","YZ"],"XYZ"),ease:ce()},this.bindingAdapter=U((e,t)=>{e.setDistance(t.distance)})}make(e={}){return new L(e.distance,R[e.axis.toLowerCase()],xe(e.ease))}},rotate:new class extends ${constructor(){super(...arguments),this.parameters={rotation:re([0,0,0],"spawn"),ease:ce()},this.bindingAdapter=U((e,t)=>{const n=ue(t.rotation);e.resetRotation(n.x,n.y,n.z)})}make(e={}){const t=ue(e.rotation);return new k(t.x,t.y,t.z,void 0,xe(e.ease))}},rotateAdd:new class extends ${constructor(){super(...arguments),this.parameters={rotation:re([0,0,0],"spawn")},this.bindingAdapter=U((e,t)=>{const n=ue(t.rotation);e.resetRotation(n.x,n.y,n.z)})}make(e={}){const t=ue(e.rotation),n=new k(t.x,t.y,t.z,void 0);return n.rotationType="add",n}},changeColor:new class extends ${constructor(){super(...arguments),this.parameters={a:ie("#ffffff","spawn"),b:ie("#ffffff","spawn"),ease:ce()},this.bindingAdapter=U((e,t)=>{e.resetColor(t.a,t.b)})}make(e={}){return new d(e.a,e.b,void 0,xe(e.ease))}},changeOpacity:new class extends ${constructor(){super(...arguments),this.parameters={a:te(1,"spawn",0,1),b:te(0,"spawn",0,1),ease:ce()},this.bindingAdapter=U((e,t)=>{e.resetAlpha(t.a,t.b)})}make(e={}){return new i(e.a,e.b,void 0,xe(e.ease))}},vortex:new class extends ${constructor(){super(...arguments),this.parameters={axis:re([0,1,0],"live"),amount:te(1,"live")},this.bindingAdapter=Q((e,t)=>{e.setAxisAngle(t.axis,t.amount)})}make(e={}){return new V(e.axis,e.amount)}},moveTo:new class extends ${constructor(){super(...arguments),this.parameters={target:re([0,1,0],"live"),ease:ce()},this.bindingAdapter=Q((e,t)=>{const n=t.target;e.setTarget(n.x,n.y,n.z)})}make(e={}){return new S(e.target.x,e.target.y,e.target.z,xe(e.ease))}},linearDamping:new class extends ${constructor(){super(...arguments),this.parameters={factor:te(.1,"live",0,1e3)},this.bindingAdapter=Q((e,t)=>{e.setFactor(t.factor)})}make(e={}){return new D(e.factor)}},followParent:new class extends ${constructor(){super(...arguments),this.parameters={speed:te(0,"live")},this.bindingAdapter=Q((e,t)=>{e.setSpeed(t.speed)})}make(e={}){return new C(e.speed)}},worldCollision:new class extends ${constructor(){super(...arguments),this.parameters={friction:ee(1,0,1),bounce:ee(1,0,1),lifeLoss:ee(0,0)}}make(e={}){return new J(null,e.bounce,e.friction,e.lifeLoss)}},animation:new class extends ${constructor(){super(...arguments),this.parameters={clip:{type:"animationclip",default:null},timeScale:ee(1,0,10),weight:ee(1,0,1),loop:oe(["Once","Repeat","PingPong"],"Once"),clampWhenFinished:{...ne(!0),requires:{loop:"Once"}}}}make(s={}){let r=e;return"Repeat"===s.loop?r=n:"PingPong"===s.loop&&(r=t),new A(s.clip,s.timeScale,s.weight,r,s.clampWhenFinished,u.easeLinear)}}};export const VfxInitializserLibrary=ge;export const VfxInitializserLibraryKeys=Object.keys(VfxInitializserLibrary);export const VfxBehaviourLibrary=be;export const VfxBehaviourLibraryKeys=Object.keys(VfxBehaviourLibrary);/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -3,6 +3,7 @@ import type { ActionInput, AxisInput, RotationInput } from "../../../../../gamep
|
|
|
3
3
|
import type { BaseActor } from "../../../actor.js";
|
|
4
4
|
import type { RootMotionActionOptions } from "./old-character-movement.js";
|
|
5
5
|
import type { CharacterMovementMode } from "./modes.js";
|
|
6
|
+
import type { RootMotionConstraintHandle } from "./character-movement.js";
|
|
6
7
|
export type CharacterMovementLike = {
|
|
7
8
|
readonly actor: BaseActor;
|
|
8
9
|
readonly directionInput: AxisInput;
|
|
@@ -22,6 +23,7 @@ export type CharacterMovementLike = {
|
|
|
22
23
|
readonly slideSurfaceNormal?: Vector3;
|
|
23
24
|
applyImpulse(impulse: Vector3): void;
|
|
24
25
|
setRootMotionAction(action: AnimationAction, options?: RootMotionActionOptions): void;
|
|
26
|
+
addRootMotionTargetConstraint?(targetPosition: Vector3, minimumHorizontalDistance: number): RootMotionConstraintHandle;
|
|
25
27
|
readonly isDefaultCharacterMovementComponent?: boolean;
|
|
26
28
|
};
|
|
27
29
|
export declare function getCharacterMovementLike(actor: BaseActor): CharacterMovementLike | undefined;
|
|
@@ -36,6 +36,13 @@ export type NetCharacterMovementRuntimeState = {
|
|
|
36
36
|
prevInputDirection: Vector3;
|
|
37
37
|
prevRotateToMovementDirection: boolean;
|
|
38
38
|
};
|
|
39
|
+
export type RootMotionTargetConstraint = {
|
|
40
|
+
readonly targetPosition: Vector3;
|
|
41
|
+
readonly minimumHorizontalDistance: number;
|
|
42
|
+
};
|
|
43
|
+
export type RootMotionConstraintHandle = {
|
|
44
|
+
dispose(): void;
|
|
45
|
+
};
|
|
39
46
|
export declare class CharacterMovementComponent extends ActorComponent {
|
|
40
47
|
readonly isDefaultCharacterMovementComponent = true;
|
|
41
48
|
readonly directionInput: AxisInput;
|
|
@@ -152,6 +159,7 @@ export declare class CharacterMovementComponent extends ActorComponent {
|
|
|
152
159
|
private rootMotionInterpolant;
|
|
153
160
|
private rootMotionRootBone;
|
|
154
161
|
private rootMotionOptions;
|
|
162
|
+
private readonly rootMotionTargetConstraints;
|
|
155
163
|
private resetRootMotion;
|
|
156
164
|
private nextMoveSequence;
|
|
157
165
|
private clientMoveTime;
|
|
@@ -175,6 +183,11 @@ export declare class CharacterMovementComponent extends ActorComponent {
|
|
|
175
183
|
getEffectiveGravity(): number;
|
|
176
184
|
get isGrounded(): boolean;
|
|
177
185
|
setRootMotionAction(action: AnimationAction, options?: RootMotionActionOptions): void;
|
|
186
|
+
/**
|
|
187
|
+
* Prevent root motion from approaching a moving target closer than the
|
|
188
|
+
* requested horizontal distance.
|
|
189
|
+
*/
|
|
190
|
+
addRootMotionTargetConstraint(targetPosition: Vector3, minimumHorizontalDistance: number): RootMotionConstraintHandle;
|
|
178
191
|
serverMove(payload: Uint8Array): void;
|
|
179
192
|
clientMoveAck(payload: Uint8Array): void;
|
|
180
193
|
clientMoveCorrection(payload: Uint8Array): void;
|
|
@@ -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
|
+
*/
|
|
@@ -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*as e from"three";import{compileNodeWebGpuFullscreen as a,compileNodeShaderMaterialForWebGpu as t,NodeShaderMaterial as n,webGpuRendererBindings as i,textureSampler2d as s}from"three-shader-graph";import{StandardShader as o}from"../shader/builtin/standard-shader.js";import{LambertShader as r}from"../shader/builtin/lambert-shader.js";import{ToonShader as l}from"../shader/builtin/toon-shader.js";import{UnlitShader as u}from"../shader/builtin/unlit-shader.js";import{SpriteShader as p}from"../shader/sprite-shader.js";import{elapsedTimeUniformName as m}from"../shader-nodes/time.js";import{depthUniformName as c,farUniformName as h,nearUniformName as d,resolutionUniformName as f,sceneNormalUniformName as M}from"../shader-nodes/depth.js";import{sceneMapUniformName as v}from"../shader-nodes/scene-sample.js";const y={...i,uniformExpressions:{...i.uniformExpressions,[m]:{type:"float",expression:"rendererElapsedTime()"},[d]:{type:"float",expression:"rendererCameraNear()"},[h]:{type:"float",expression:"rendererCameraFar()"},[f]:{type:"vec2",expression:"rendererCamera.viewportAndTime.xy"}},sceneTextures:{[v]:{semantic:"sceneColor",sampleType:"float"},[c]:{semantic:"sceneDepth",sampleType:"depth"}},attributes:{material:{shaderLocation:6,format:"float32x4",defaultValue:[0,0,0,0]},material2:{shaderLocation:7,format:"float32x4",defaultValue:[0,0,0,0]},hole:{shaderLocation:8,format:"float32",defaultValue:[0]},offset:{shaderLocation:9,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},velocity:{shaderLocation:10,format:"float32x4",stepMode:"instance",defaultValue:[0,0,0,0]},size:{shaderLocation:11,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},rotation:{shaderLocation:12,format:"float32",stepMode:"instance",defaultValue:[0]},particleData:{shaderLocation:13,format:"float32x3",stepMode:"instance",defaultValue:[1,1,0]},particleColor:{shaderLocation:14,format:"float32x4",stepMode:"instance",defaultValue:[1,1,1,1]}}};export function setMaterialUniformValuesAutoUpdate(e,a){e.uniformValuesAutoUpdate=a}export function markMaterialUniformValuesNeedUpdate(e){const a=e;"uniformValuesNeedsUpdate"in a?a.uniformValuesNeedsUpdate=!0:a.uniformValuesAutoVersion=(a.uniformValuesAutoVersion??0)+1}function g(e){return!1!==e.uniformValuesAutoUpdate}function V(e){return e.uniformValuesAutoVersion??0}export function withThreeDefaultVertexAttributeValues(e){return e.map(e=>"uv1"===e.name&&null==e.defaultValue?{...e,defaultValue:[0,0]}:e)}const w=new WeakMap,I=new WeakMap;export function createNodeMaterialSignature(e){const a=I.get(e);if(null!=a)return a;const t=JSON.stringify({version:e.version,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,alphaTest:e.alphaTest,alphaToCoverage:e.alphaToCoverage,blending:e.blending,colorWrite:e.colorWrite,depthFunc:e.depthFunc,depthTest:e.depthTest,depthWrite:e.depthWrite,polygonOffset:e.polygonOffset,polygonOffsetFactor:e.polygonOffsetFactor,polygonOffsetUnits:e.polygonOffsetUnits,premultipliedAlpha:e.premultipliedAlpha,side:e.side,stencilWrite:e.stencilWrite,transparent:e.transparent,wireframe:e.wireframe});return I.set(e,t),t}export class NodeMaterialWebGpuResolver{constructor(e,a){this.webGpu=e,this.mrtResolver=a,this.cache=new WeakMap,this.failedSignatures=new WeakMap,this.mappedMaterialsCache=new WeakMap,this.mappedMaterialsSignatures=new WeakMap,this.observedNodeMaterials=new Map,this.worldEnvironmentMaterials=new WeakSet,this.worldEnvironment=null,this.worldEnvironmentTexture=null,this.worldEnvironmentIntensity=0,this.worldEnvironmentRevision=0,this.cacheValues=new Set}setWorldEnvironment(e){const a=e?.texture??null,t=e?.intensity??0;if(this.worldEnvironmentTexture!==a||this.worldEnvironmentIntensity!==t){if(this.worldEnvironmentTexture!==a)this.worldEnvironmentRevision++;else if(null!=e)for(const e of this.cacheValues)e.inheritsWorldEnvironment&&null!=e.material.uniforms.envMapIntensity&&(e.material.uniforms.envMapIntensity.value=t,e.material.uniformValuesNeedsUpdate=!0);this.worldEnvironment=e,this.worldEnvironmentTexture=a,this.worldEnvironmentIntensity=t}}resolve(e,a=void 0){let i,s=!1;if(e instanceof n)i=e,this.observeNodeMaterial(i);else{const a=this.getOrCreateMappedNodeMaterial(e);if(null==a)return;i=a,s=!0}i.visible=e.visible,s&&(i.userData.receiveDecals=e.userData.receiveDecals);const o=a??"default",r=this.cache.get(i),l=r?.get(o);if(s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision){const a=g(e),t=V(e);return l.material.uniformValuesAutoUpdate=a,this.syncInheritedWorldEnvironmentSource(i,l),a||l.sourceUniformValuesAutoVersion!==t?(W(e,i),l.compiled.syncLiveUniforms(l.material.uniforms),x(i,l.material.uniforms),T(i,l.material),l.sourceUniformValuesAutoVersion=t,a||(l.material.uniformValuesNeedsUpdate=!0),l.material):l.material}if(!s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision&&E(i,l.compiled))return this.syncInheritedWorldEnvironmentSource(i,l),S(i,l),l.material;s&&W(e,i);const u=this.prepareWorldEnvironment(i),p=this.getNodeMaterialSignature(i,u);if(l?.signature===p&&E(i,l.compiled))return s?(l.material.uniformValuesAutoUpdate=g(e),l.compiled.syncLiveUniforms(l.material.uniforms),x(i,l.material.uniforms),T(i,l.material),l.sourceUniformValuesAutoVersion=V(e),l.material.uniformValuesAutoUpdate||(l.material.uniformValuesNeedsUpdate=!0)):S(i,l,!0),l.sourceVersion=e.version,l.worldEnvironmentRevision=this.worldEnvironmentRevision,l.material;try{const n=this.mrtResolver?.(i,a),m=t(i,y,n),c=new this.webGpu.WGSLShaderMaterial({vertexShader:m.vertexShader,fragmentShader:m.fragmentShader,depthVertexShader:m.depthVertexShader,depthFragmentShader:m.depthFragmentShader,pointShadowVertexShader:m.pointShadowVertexShader,pointShadowFragmentShader:m.pointShadowFragmentShader,uniforms:m.uniforms,textures:m.textures,sceneTextures:m.sceneTextures,graphTextures:m.graphTextures,vertexAttributes:withThreeDefaultVertexAttributeValues(m.vertexAttributes),uniformValuesAutoUpdate:s?g(e):i.uniformValuesAutoUpdate,transparent:m.renderState?.transparent,alphaTest:m.renderState?.alphaTest,depthTest:m.renderState?.depthTest,depthWrite:m.renderState?.depthWrite,side:m.renderState?.side,wireframe:i.wireframe});c.uniformValuesAutoUpdate=s?g(e):i.uniformValuesAutoUpdate,function(e,a){if(null==e)return;Object.assign(a,e)}(m.renderState,c),null!=l&&(l.material.dispose(),this.cacheValues.delete(l));const h={signature:p,compiled:m,material:c,inheritsWorldEnvironment:u,sourceVersion:e.version,sourceUniformValuesAutoVersion:s?V(e):i.uniformValuesAutoVersion,worldEnvironmentRevision:this.worldEnvironmentRevision},d=r??new Map;return d.set(o,h),this.cache.set(i,d),this.cacheValues.add(h),x(i,c.uniforms),T(i,c),c}catch(e){let a=this.failedSignatures.get(i);if(null==a&&(a=new Map,this.failedSignatures.set(i,a)),a.get(o)!==p){a.set(o,p);const t=e instanceof Error?e.message:String(e),n=i.name||i.uuid;console.warn(`[Hology WebGPU experiment] Falling back for NodeShaderMaterial "${n}": ${t}`,{material:i,error:e})}return}}compileFullscreen(e){const t=a({color:e.outputColor,wgslBindings:{...y,uniformExpressions:{},graphTextures:{...y.graphTextures,[M]:{resource:"hologyNormalRoughness",dimension:"2d",sampleType:"float",sampler:"filtering"}}}}),n=t.syncLiveUniforms;return{...t,syncLiveUniforms(a){n(a),x(e,a)}}}getOrCreateMappedNodeMaterial(a){const t=function(a){const t=[a.vertexColors,a.transparent,a.alphaTest,a.side,a.depthTest,a.depthWrite,a.wireframe??!1];a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.roughnessMap?a.roughnessMap.uuid:null,a.metalnessMap?a.metalnessMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshLambertMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshToonMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.gradientMap?a.gradientMap.uuid:null):a instanceof e.MeshBasicMaterial?t.push(a.map?a.map.uuid:null,a.aoMap?a.aoMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshPhongMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.SpriteMaterial&&t.push(a.map?a.map.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.sizeAttenuation);return t.join(",")}(a),n=this.mappedMaterialsCache.get(a),i=this.mappedMaterialsSignatures.get(a);if(null!=n&&i===t)return n;if(null!=n){n.dispose();const e=this.cache.get(n);if(null!=e){for(const a of e.values())a.material.dispose(),this.cacheValues.delete(a);this.cache.delete(n)}}const m=function(a){if(a instanceof e.SpriteMaterial){const e=new p;e.color=a.color,e.opacity=a.opacity,e.rotation=a.rotation,e.screenSpaceSize=a.sizeAttenuation?0:1,e.alphaTest=a.alphaTest,a.map&&(e.map=a.map),a.alphaMap&&(e.alphaMap=a.alphaMap);const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t}if(a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial){const e=new o;e.color=a.color,e.opacity=a.opacity,e.roughness=a.roughness,e.metalness=a.metalness,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.roughnessMap&&(e.roughnessMap=s(a.roughnessMap)),a.metalnessMap&&(e.metalnessMap=s(a.metalnessMap)),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.envMapIntensity=a.envMapIntensity,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshLambertMaterial){const e=new r;e.color=a.color,e.opacity=a.opacity,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshToonMaterial){const e=new l;e.color=a.color,e.opacity=a.opacity,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshBasicMaterial||a instanceof e.LineBasicMaterial){const t=new u;t.color=a.color,t.opacity=a.opacity,t.vertexColor=a.vertexColors,a instanceof e.MeshBasicMaterial&&(a.map&&(t.map=s(a.map)),a.aoMap&&(t.aoMap=s(a.aoMap),t.aoMapIntensity=a.aoMapIntensity),a.lightMap&&(t.lightMap=s(a.lightMap),t.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(t.alphaMap=s(a.alphaMap)),t.envMap=a.envMap),t.alphaTest=a.alphaTest;const n=t.build();return n.transparent=a.transparent,n.side=a.side,n.depthTest=a.depthTest,n.depthWrite=a.depthWrite,n.wireframe=a instanceof e.MeshBasicMaterial&&a.wireframe,n}if(a instanceof e.MeshPhongMaterial){const e=new o;e.color=a.color,e.opacity=a.opacity,e.roughness=Math.max(0,1-a.shininess/100),e.metalness=0,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}return null}(a);return null==m?null:(m.wireframe=a.wireframe??!1,this.mappedMaterialsCache.set(a,m),this.mappedMaterialsSignatures.set(a,t),a.addEventListener("dispose",()=>{const e=this.mappedMaterialsCache.get(a);if(null!=e){e.dispose(),this.mappedMaterialsCache.delete(a),this.mappedMaterialsSignatures.delete(a);const t=this.cache.get(e);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}}}),m)}canResolve(e){return null!=this.resolve(e)}dispose(){for(const[e,a]of this.observedNodeMaterials)e.removeEventListener("dispose",a);this.observedNodeMaterials.clear();for(const e of this.cacheValues)e.material.dispose();this.cacheValues.clear()}syncInheritedWorldEnvironmentSource(e,a){a.inheritsWorldEnvironment&&null!=this.worldEnvironment&&(e.uniforms.envMap.value=this.worldEnvironment.texture,e.uniforms.envMapIntensity.value=this.worldEnvironment.intensity)}getNodeMaterialSignature(e,a){const t=`${createNodeMaterialSignature(e)}|receiveDecals:${!1!==e.userData.receiveDecals}`;return a?`${t}|worldEnvironment:${this.worldEnvironmentRevision}`:t}prepareWorldEnvironment(a){var t,n,i;return null!=a.envMap?(this.worldEnvironmentMaterials.has(a)&&(a.uniforms.envMap={value:a.envMap},a.uniforms.envMapIntensity={value:1},a.uniforms.envMapRotation={value:new e.Matrix3},this.worldEnvironmentMaterials.delete(a)),!1):null==this.worldEnvironment?(this.worldEnvironmentMaterials.has(a)&&(delete a.uniforms.envMap,delete a.uniforms.envMapIntensity,delete a.uniforms.envMapRotation,this.worldEnvironmentMaterials.delete(a)),!1):((t=a.uniforms).envMap??(t.envMap={value:this.worldEnvironment.texture}),a.uniforms.envMap.value=this.worldEnvironment.texture,(n=a.uniforms).envMapIntensity??(n.envMapIntensity={value:this.worldEnvironment.intensity}),a.uniforms.envMapIntensity.value=this.worldEnvironment.intensity,(i=a.uniforms).envMapRotation??(i.envMapRotation={value:new e.Matrix3}),this.worldEnvironmentMaterials.add(a),!0)}observeNodeMaterial(e){if(this.observedNodeMaterials.has(e))return;const a=()=>{e.removeEventListener("dispose",a),this.observedNodeMaterials.delete(e);const t=this.cache.get(e);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}this.failedSignatures.delete(e),I.delete(e)};this.observedNodeMaterials.set(e,a),e.addEventListener("dispose",a)}}function S(e,a,t=!1){const n=a.material;n.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,(t||e.uniformValuesAutoUpdate||a.sourceUniformValuesAutoVersion!==e.uniformValuesAutoVersion)&&(a.compiled.syncLiveUniforms(n.uniforms),x(e,n.uniforms),T(e,n),a.sourceUniformValuesAutoVersion=e.uniformValuesAutoVersion,n.uniformValuesAutoUpdate||(n.uniformValuesNeedsUpdate=!0))}function x(e,a){let t=w.get(a);if(null==t){t=[];for(const e in a){const n=a[e],i=n.value,s=!0===i?.isVector2?2:!0===i?.isVector3?3:!0===i?.isVector4?4:!0===i?.isColor?5:0;t.push({name:e,target:n,copyKind:s})}w.set(a,t)}const n=e.uniforms;for(let e=0;e<t.length;e++){const a=t[e],i=n[a.name];if(null==i)continue;const s=i.value,o=a.target.value;if(s!==o){if(0!==a.copyKind){const e=s,t=o;if((2===a.copyKind?!0===e?.isVector2:3===a.copyKind?!0===e?.isVector3:4===a.copyKind?!0===e?.isVector4:!0===e?.isColor)&&"function"==typeof t?.copy){t.copy(s);continue}}a.target.value=s}}}function T(a,t){const n=a.uniforms.envMapIntensity,i=t.uniforms.envMapIntensity;null!=n&&null!=i&&(i.value=n.value);const s=a.uniforms.envMapRotation?.value,o=t.uniforms.envMapRotation?.value;s instanceof e.Matrix3&&o instanceof e.Matrix3&&o.copy(s)}function E(e,a){for(const t in a.textures){const n=a.textures[t],i=e.uniforms[t]?.value;if(C(i)&&i!==n)return!1}return!0}function C(e){return!0===e?.isTexture}function W(a,t){if(a instanceof e.SpriteMaterial){const n=t;t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),n.rotation=a.rotation,n.screenSpaceSize=a.sizeAttenuation?0:1}else a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.roughness&&(t.uniforms.roughness.value=a.roughness),t.uniforms.metalness&&(t.uniforms.metalness.value=a.metalness),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity),t.uniforms.envMapIntensity&&(t.uniforms.envMapIntensity.value=a.envMapIntensity)):a instanceof e.MeshLambertMaterial||a instanceof e.MeshToonMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity)):a instanceof e.MeshBasicMaterial||a instanceof e.LineBasicMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),a instanceof e.MeshBasicMaterial&&(t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity))):a instanceof e.MeshPhongMaterial&&(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.roughness&&(t.uniforms.roughness.value=Math.max(0,1-a.shininess/100)),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity))}/*
|
|
1
|
+
import*as e from"three";import{compileNodeWebGpuFullscreen as a,compileNodeShaderMaterialForWebGpu as t,NodeShaderMaterial as n,webGpuRendererBindings as i,textureSampler2d as s}from"three-shader-graph";import{StandardShader as o}from"../shader/builtin/standard-shader.js";import{LambertShader as r}from"../shader/builtin/lambert-shader.js";import{ToonShader as l}from"../shader/builtin/toon-shader.js";import{UnlitShader as u}from"../shader/builtin/unlit-shader.js";import{SpriteShader as p}from"../shader/sprite-shader.js";import{elapsedTimeUniformName as m}from"../shader-nodes/time.js";import{depthUniformName as c,farUniformName as h,nearUniformName as d,resolutionUniformName as f,sceneNormalUniformName as M}from"../shader-nodes/depth.js";import{sceneMapUniformName as v}from"../shader-nodes/scene-sample.js";const y={...i,uniformExpressions:{...i.uniformExpressions,[m]:{type:"float",expression:"rendererElapsedTime()"},[d]:{type:"float",expression:"rendererCameraNear()"},[h]:{type:"float",expression:"rendererCameraFar()"},[f]:{type:"vec2",expression:"rendererViewportSize()"}},sceneTextures:{[v]:{semantic:"sceneColor",sampleType:"float"},[c]:{semantic:"sceneDepth",sampleType:"depth"}},attributes:{material:{shaderLocation:6,format:"float32x4",defaultValue:[0,0,0,0]},material2:{shaderLocation:7,format:"float32x4",defaultValue:[0,0,0,0]},hole:{shaderLocation:8,format:"float32",defaultValue:[0]},offset:{shaderLocation:9,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},velocity:{shaderLocation:10,format:"float32x4",stepMode:"instance",defaultValue:[0,0,0,0]},size:{shaderLocation:11,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},rotation:{shaderLocation:12,format:"float32",stepMode:"instance",defaultValue:[0]},particleData:{shaderLocation:13,format:"float32x3",stepMode:"instance",defaultValue:[1,1,0]},particleColor:{shaderLocation:14,format:"float32x4",stepMode:"instance",defaultValue:[1,1,1,1]}}};export function setMaterialUniformValuesAutoUpdate(e,a){e.uniformValuesAutoUpdate=a}export function markMaterialUniformValuesNeedUpdate(e){const a=e;"uniformValuesNeedsUpdate"in a?a.uniformValuesNeedsUpdate=!0:a.uniformValuesAutoVersion=(a.uniformValuesAutoVersion??0)+1}function g(e){return!1!==e.uniformValuesAutoUpdate}function V(e){return e.uniformValuesAutoVersion??0}export function withThreeDefaultVertexAttributeValues(e){return e.map(e=>"uv1"===e.name&&null==e.defaultValue?{...e,defaultValue:[0,0]}:e)}const w=new WeakMap,I=new WeakMap;export function createNodeMaterialSignature(e){const a=I.get(e);if(null!=a)return a;const t=JSON.stringify({version:e.version,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,alphaTest:e.alphaTest,alphaToCoverage:e.alphaToCoverage,blending:e.blending,colorWrite:e.colorWrite,depthFunc:e.depthFunc,depthTest:e.depthTest,depthWrite:e.depthWrite,polygonOffset:e.polygonOffset,polygonOffsetFactor:e.polygonOffsetFactor,polygonOffsetUnits:e.polygonOffsetUnits,premultipliedAlpha:e.premultipliedAlpha,side:e.side,stencilWrite:e.stencilWrite,transparent:e.transparent,wireframe:e.wireframe});return I.set(e,t),t}export class NodeMaterialWebGpuResolver{constructor(e,a){this.webGpu=e,this.mrtResolver=a,this.cache=new WeakMap,this.failedSignatures=new WeakMap,this.mappedMaterialsCache=new WeakMap,this.mappedMaterialsSignatures=new WeakMap,this.observedNodeMaterials=new Map,this.worldEnvironmentMaterials=new WeakSet,this.worldEnvironment=null,this.worldEnvironmentTexture=null,this.worldEnvironmentIntensity=0,this.worldEnvironmentRevision=0,this.cacheValues=new Set}setWorldEnvironment(e){const a=e?.texture??null,t=e?.intensity??0;if(this.worldEnvironmentTexture!==a||this.worldEnvironmentIntensity!==t){if(this.worldEnvironmentTexture!==a)this.worldEnvironmentRevision++;else if(null!=e)for(const e of this.cacheValues)e.inheritsWorldEnvironment&&null!=e.material.uniforms.envMapIntensity&&(e.material.uniforms.envMapIntensity.value=t,e.material.uniformValuesNeedsUpdate=!0);this.worldEnvironment=e,this.worldEnvironmentTexture=a,this.worldEnvironmentIntensity=t}}resolve(e,a=void 0){let i,s=!1;if(e instanceof n)i=e,this.observeNodeMaterial(i);else{const a=this.getOrCreateMappedNodeMaterial(e);if(null==a)return;i=a,s=!0}i.visible=e.visible,s&&(i.userData.receiveDecals=e.userData.receiveDecals);const o=a??"default",r=this.cache.get(i),l=r?.get(o);if(s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision){const a=g(e),t=V(e);return l.material.uniformValuesAutoUpdate=a,this.syncInheritedWorldEnvironmentSource(i,l),a||l.sourceUniformValuesAutoVersion!==t?(W(e,i),l.compiled.syncLiveUniforms(l.material.uniforms),x(i,l.material.uniforms),T(i,l.material),l.sourceUniformValuesAutoVersion=t,a||(l.material.uniformValuesNeedsUpdate=!0),l.material):l.material}if(!s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision&&E(i,l.compiled))return this.syncInheritedWorldEnvironmentSource(i,l),S(i,l),l.material;s&&W(e,i);const u=this.prepareWorldEnvironment(i),p=this.getNodeMaterialSignature(i,u);if(l?.signature===p&&E(i,l.compiled))return s?(l.material.uniformValuesAutoUpdate=g(e),l.compiled.syncLiveUniforms(l.material.uniforms),x(i,l.material.uniforms),T(i,l.material),l.sourceUniformValuesAutoVersion=V(e),l.material.uniformValuesAutoUpdate||(l.material.uniformValuesNeedsUpdate=!0)):S(i,l,!0),l.sourceVersion=e.version,l.worldEnvironmentRevision=this.worldEnvironmentRevision,l.material;try{const n=this.mrtResolver?.(i,a),m=t(i,y,n),c=new this.webGpu.WGSLShaderMaterial({vertexShader:m.vertexShader,fragmentShader:m.fragmentShader,depthVertexShader:m.depthVertexShader,depthFragmentShader:m.depthFragmentShader,pointShadowVertexShader:m.pointShadowVertexShader,pointShadowFragmentShader:m.pointShadowFragmentShader,uniforms:m.uniforms,textures:m.textures,sceneTextures:m.sceneTextures,graphTextures:m.graphTextures,vertexAttributes:withThreeDefaultVertexAttributeValues(m.vertexAttributes),uniformValuesAutoUpdate:s?g(e):i.uniformValuesAutoUpdate,transparent:m.renderState?.transparent,alphaTest:m.renderState?.alphaTest,depthTest:m.renderState?.depthTest,depthWrite:m.renderState?.depthWrite,side:m.renderState?.side,wireframe:i.wireframe});c.uniformValuesAutoUpdate=s?g(e):i.uniformValuesAutoUpdate,function(e,a){if(null==e)return;Object.assign(a,e)}(m.renderState,c),null!=l&&(l.material.dispose(),this.cacheValues.delete(l));const h={signature:p,compiled:m,material:c,inheritsWorldEnvironment:u,sourceVersion:e.version,sourceUniformValuesAutoVersion:s?V(e):i.uniformValuesAutoVersion,worldEnvironmentRevision:this.worldEnvironmentRevision},d=r??new Map;return d.set(o,h),this.cache.set(i,d),this.cacheValues.add(h),x(i,c.uniforms),T(i,c),c}catch(e){let a=this.failedSignatures.get(i);if(null==a&&(a=new Map,this.failedSignatures.set(i,a)),a.get(o)!==p){a.set(o,p);const t=e instanceof Error?e.message:String(e),n=i.name||i.uuid;console.warn(`[Hology WebGPU experiment] Falling back for NodeShaderMaterial "${n}": ${t}`,{material:i,error:e})}return}}compileFullscreen(e){const t=a({color:e.outputColor,wgslBindings:{...y,uniformExpressions:{},graphTextures:{...y.graphTextures,[M]:{resource:"hologyNormalRoughness",dimension:"2d",sampleType:"float",sampler:"filtering"}}}}),n=t.syncLiveUniforms;return{...t,syncLiveUniforms(a){n(a),x(e,a)}}}getOrCreateMappedNodeMaterial(a){const t=function(a){const t=[a.vertexColors,a.transparent,a.alphaTest,a.side,a.depthTest,a.depthWrite,a.wireframe??!1];a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.roughnessMap?a.roughnessMap.uuid:null,a.metalnessMap?a.metalnessMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshLambertMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshToonMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.gradientMap?a.gradientMap.uuid:null):a instanceof e.MeshBasicMaterial?t.push(a.map?a.map.uuid:null,a.aoMap?a.aoMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshPhongMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.SpriteMaterial&&t.push(a.map?a.map.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.sizeAttenuation);return t.join(",")}(a),n=this.mappedMaterialsCache.get(a),i=this.mappedMaterialsSignatures.get(a);if(null!=n&&i===t)return n;if(null!=n){n.dispose();const e=this.cache.get(n);if(null!=e){for(const a of e.values())a.material.dispose(),this.cacheValues.delete(a);this.cache.delete(n)}}const m=function(a){if(a instanceof e.SpriteMaterial){const e=new p;e.color=a.color,e.opacity=a.opacity,e.rotation=a.rotation,e.screenSpaceSize=a.sizeAttenuation?0:1,e.alphaTest=a.alphaTest,a.map&&(e.map=a.map),a.alphaMap&&(e.alphaMap=a.alphaMap);const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t}if(a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial){const e=new o;e.color=a.color,e.opacity=a.opacity,e.roughness=a.roughness,e.metalness=a.metalness,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.roughnessMap&&(e.roughnessMap=s(a.roughnessMap)),a.metalnessMap&&(e.metalnessMap=s(a.metalnessMap)),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.envMapIntensity=a.envMapIntensity,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshLambertMaterial){const e=new r;e.color=a.color,e.opacity=a.opacity,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshToonMaterial){const e=new l;e.color=a.color,e.opacity=a.opacity,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshBasicMaterial||a instanceof e.LineBasicMaterial){const t=new u;t.color=a.color,t.opacity=a.opacity,t.vertexColor=a.vertexColors,a instanceof e.MeshBasicMaterial&&(a.map&&(t.map=s(a.map)),a.aoMap&&(t.aoMap=s(a.aoMap),t.aoMapIntensity=a.aoMapIntensity),a.lightMap&&(t.lightMap=s(a.lightMap),t.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(t.alphaMap=s(a.alphaMap)),t.envMap=a.envMap),t.alphaTest=a.alphaTest;const n=t.build();return n.transparent=a.transparent,n.side=a.side,n.depthTest=a.depthTest,n.depthWrite=a.depthWrite,n.wireframe=a instanceof e.MeshBasicMaterial&&a.wireframe,n}if(a instanceof e.MeshPhongMaterial){const e=new o;e.color=a.color,e.opacity=a.opacity,e.roughness=Math.max(0,1-a.shininess/100),e.metalness=0,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}return null}(a);return null==m?null:(m.wireframe=a.wireframe??!1,this.mappedMaterialsCache.set(a,m),this.mappedMaterialsSignatures.set(a,t),a.addEventListener("dispose",()=>{const e=this.mappedMaterialsCache.get(a);if(null!=e){e.dispose(),this.mappedMaterialsCache.delete(a),this.mappedMaterialsSignatures.delete(a);const t=this.cache.get(e);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}}}),m)}canResolve(e){return null!=this.resolve(e)}dispose(){for(const[e,a]of this.observedNodeMaterials)e.removeEventListener("dispose",a);this.observedNodeMaterials.clear();for(const e of this.cacheValues)e.material.dispose();this.cacheValues.clear()}syncInheritedWorldEnvironmentSource(e,a){a.inheritsWorldEnvironment&&null!=this.worldEnvironment&&(e.uniforms.envMap.value=this.worldEnvironment.texture,e.uniforms.envMapIntensity.value=this.worldEnvironment.intensity)}getNodeMaterialSignature(e,a){const t=`${createNodeMaterialSignature(e)}|receiveDecals:${!1!==e.userData.receiveDecals}`;return a?`${t}|worldEnvironment:${this.worldEnvironmentRevision}`:t}prepareWorldEnvironment(a){var t,n,i;return null!=a.envMap?(this.worldEnvironmentMaterials.has(a)&&(a.uniforms.envMap={value:a.envMap},a.uniforms.envMapIntensity={value:1},a.uniforms.envMapRotation={value:new e.Matrix3},this.worldEnvironmentMaterials.delete(a)),!1):null==this.worldEnvironment?(this.worldEnvironmentMaterials.has(a)&&(delete a.uniforms.envMap,delete a.uniforms.envMapIntensity,delete a.uniforms.envMapRotation,this.worldEnvironmentMaterials.delete(a)),!1):((t=a.uniforms).envMap??(t.envMap={value:this.worldEnvironment.texture}),a.uniforms.envMap.value=this.worldEnvironment.texture,(n=a.uniforms).envMapIntensity??(n.envMapIntensity={value:this.worldEnvironment.intensity}),a.uniforms.envMapIntensity.value=this.worldEnvironment.intensity,(i=a.uniforms).envMapRotation??(i.envMapRotation={value:new e.Matrix3}),this.worldEnvironmentMaterials.add(a),!0)}observeNodeMaterial(e){if(this.observedNodeMaterials.has(e))return;const a=()=>{e.removeEventListener("dispose",a),this.observedNodeMaterials.delete(e);const t=this.cache.get(e);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}this.failedSignatures.delete(e),I.delete(e)};this.observedNodeMaterials.set(e,a),e.addEventListener("dispose",a)}}function S(e,a,t=!1){const n=a.material;n.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,(t||e.uniformValuesAutoUpdate||a.sourceUniformValuesAutoVersion!==e.uniformValuesAutoVersion)&&(a.compiled.syncLiveUniforms(n.uniforms),x(e,n.uniforms),T(e,n),a.sourceUniformValuesAutoVersion=e.uniformValuesAutoVersion,n.uniformValuesAutoUpdate||(n.uniformValuesNeedsUpdate=!0))}function x(e,a){let t=w.get(a);if(null==t){t=[];for(const e in a){const n=a[e],i=n.value,s=!0===i?.isVector2?2:!0===i?.isVector3?3:!0===i?.isVector4?4:!0===i?.isColor?5:0;t.push({name:e,target:n,copyKind:s})}w.set(a,t)}const n=e.uniforms;for(let e=0;e<t.length;e++){const a=t[e],i=n[a.name];if(null==i)continue;const s=i.value,o=a.target.value;if(s!==o){if(0!==a.copyKind){const e=s,t=o;if((2===a.copyKind?!0===e?.isVector2:3===a.copyKind?!0===e?.isVector3:4===a.copyKind?!0===e?.isVector4:!0===e?.isColor)&&"function"==typeof t?.copy){t.copy(s);continue}}a.target.value=s}}}function T(a,t){const n=a.uniforms.envMapIntensity,i=t.uniforms.envMapIntensity;null!=n&&null!=i&&(i.value=n.value);const s=a.uniforms.envMapRotation?.value,o=t.uniforms.envMapRotation?.value;s instanceof e.Matrix3&&o instanceof e.Matrix3&&o.copy(s)}function E(e,a){for(const t in a.textures){const n=a.textures[t],i=e.uniforms[t]?.value;if(C(i)&&i!==n)return!1}return!0}function C(e){return!0===e?.isTexture}function W(a,t){if(a instanceof e.SpriteMaterial){const n=t;t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),n.rotation=a.rotation,n.screenSpaceSize=a.sizeAttenuation?0:1}else a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.roughness&&(t.uniforms.roughness.value=a.roughness),t.uniforms.metalness&&(t.uniforms.metalness.value=a.metalness),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity),t.uniforms.envMapIntensity&&(t.uniforms.envMapIntensity.value=a.envMapIntensity)):a instanceof e.MeshLambertMaterial||a instanceof e.MeshToonMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity)):a instanceof e.MeshBasicMaterial||a instanceof e.LineBasicMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),a instanceof e.MeshBasicMaterial&&(t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity))):a instanceof e.MeshPhongMaterial&&(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.roughness&&(t.uniforms.roughness.value=Math.max(0,1-a.shininess/100)),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity))}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{describe as o,expect as e,it as t}from"vitest";import{Vector3 as n}from"three";import{constrainRootMotionTargetApproach as r}from"../gameplay/actors/builtin/components/character/root-motion-constraint.js";o("constrainRootMotionTargetApproach",()=>{t("stops approaching at the minimum target distance",()=>{const o=new n(0,0,2);r(o,new n(0,0,0),new n(0,0,1.5),.9),e(o.x).toBeCloseTo(0),e(o.z).toBeCloseTo(.6)}),t("preserves lateral and vertical motion while clamping approach",()=>{const o=new n(.75,.4,1);r(o,new n(0,0,0),new n(0,0,1.2),.9),e(o.x).toBeCloseTo(.75),e(o.y).toBeCloseTo(.4),e(o.z).toBeCloseTo(.3)}),t("preserves retreating motion when already inside the minimum distance",()=>{const o=new n(0,0,-.5);r(o,new n(0,0,0),new n(0,0,.5),.9),e(o.z).toBeCloseTo(-.5)})});/*
|
|
2
|
+
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
|
+
* See the LICENSE.md file for details.
|
|
4
|
+
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{describe as e,expect as t,it as o}from"vitest";import{DataTexture as a,Material as r,MeshStandardMaterial as n,RGBAFormat as s,SpriteMaterial as i,Vector4 as l}from"three";import{batchingUniformVec4 as d,float as h,NodeShaderMaterial as p,rgb as u,rgba as m,standardMaterial as c,translateX as f,uniformFloat as v,uniformVec4 as S,uniformSampler2d as g,varyingAttributes as w,vec3 as x,vec4 as y}from"three-shader-graph";import{createNodeMaterialSignature as C,markMaterialUniformValuesNeedUpdate as B,NodeMaterialWebGpuResolver as M,setMaterialUniformValuesAutoUpdate as T,withThreeDefaultVertexAttributeValues as W}from"../rendering/node-material-webgpu-resolver.js";import{LandscapeCompositeShader as L}from"../shader/builtin/landscape-composite-shader.js";import{DecalUnlitShader as b}from"../shader/builtin/decal-unlit-shader.js";import{getSpritePosition as _}from"../shader/sprite-shader.js";import{depthNormal as G,depthWorldPosition as A,fragmentLinearEyeDepth as U,sampleSceneDepth as V,screenUV as j}from"../shader-nodes/depth.js";import{sampleSceneColor as E}from"../shader-nodes/scene-sample.js";import{applyDithering as F}from"../shader-nodes/dither.js";import{parallaxOcclusionMapping as O}from"../shader-nodes/pom.js";import{elapsedTimeUniformName as q}from"../shader-nodes/time.js";import{Trail as I}from"../effects/vfx/trail-renderer.js";import{particleUniforms as D}from"../shader-nodes/particle.js";class P extends r{set uniformValuesNeedsUpdate(e){e&&this.uniformValuesAutoVersion++}constructor(e){super(),this.disposed=!1,this.uniformValuesAutoUpdate=!0,this.uniformValuesAutoVersion=0,this.vertexShader=e.vertexShader,this.fragmentShader=e.fragmentShader,this.depthVertexShader=e.depthVertexShader??null,this.depthFragmentShader=e.depthFragmentShader??null,this.pointShadowVertexShader=e.pointShadowVertexShader??null,this.pointShadowFragmentShader=e.pointShadowFragmentShader??null,this.uniforms=e.uniforms,this.sceneTextures=e.sceneTextures??{},this.graphTextures=e.graphTextures??{},this.vertexAttributes=e.vertexAttributes??[],this.transparent=e.transparent??!1,this.alphaTest=e.alphaTest??0,this.depthTest=e.depthTest??!0,this.depthWrite=e.depthWrite??!0,this.side=e.side??this.side}dispose(){this.disposed=!0,super.dispose()}}e("NodeMaterialWebGpuResolver",()=>{o("compiles decal surface rejection without undefined WGSL expressions",()=>{const e=(new b).build(),o=new M({WGSLShaderMaterial:P}).resolve(e);t(o?.fragmentShader).not.toContain("undefined"),t(o?.fragmentShader).toContain("hology_scene_mapTexture")}),o("recompiles an opaque variant when receiveDecals changes",()=>{const e=new p({color:m(16777215)});e.userData.receiveDecals=!0;const o=new M({WGSLShaderMaterial:P},e=>[m(16777215,!1===e.userData.receiveDecals?0:2)]),a=o.resolve(e,"opaque");e.userData.receiveDecals=!1,e.needsUpdate=!0;const r=o.resolve(e,"opaque");t(r).not.toBe(a),t(a.disposed).toBe(!0),t(a.fragmentShader).not.toBe(r.fragmentShader)}),o("maps Hology elapsed time to the renderer frame clock",()=>{const e=v(q),o=new p({color:m(x(e)),transform:f(e)}),a=new M({WGSLShaderMaterial:P}).resolve(o);t(a?.vertexShader).toContain("rendererElapsedTime()"),t(a?.fragmentShader).toContain("rendererElapsedTime()"),t(a?.depthVertexShader).toContain("rendererElapsedTime()"),t(a?.pointShadowVertexShader).toContain("rendererElapsedTime()"),t(a?.uniforms).not.toHaveProperty(q)}),o("compiles the native sprite billboard position without a GLSL fallback",()=>{const e=new p({color:m(16777215),position:_(v("rotation",.25),v("screenSpaceSize",0),v("lockYAxis",1))}),o=new M({WGSLShaderMaterial:P}).resolve(e);t(o).toBeInstanceOf(P),t(o?.vertexShader).toContain("cos("),t(o?.vertexShader).toContain("sin("),t(o?.vertexShader).toContain("materialUniforms.lockYAxis"),t(o?.vertexShader).not.toContain("customFunction_")}),o("uses the per-instance rotation attribute for instanced sprites",()=>{const e=new p({color:m(16777215),position:_(v("rotation",0),void 0,void 0,!0)}),o=new M({WGSLShaderMaterial:P}).resolve(e);t(o?.vertexAttributes).toEqual(t.arrayContaining([t.objectContaining({name:"rotation",format:"float32",stepMode:"instance"})])),t(o?.vertexShader).toContain("input.rotation"),t(o?.vertexShader).not.toContain("materialUniforms.rotation")}),o("uses per-instance particle opacity in WebGPU fragment shaders",()=>{const e=new p({color:m(u(16777215),D.opacity)}),o=new M({WGSLShaderMaterial:P}).resolve(e);t(o?.vertexAttributes).toEqual(t.arrayContaining([t.objectContaining({name:"particleData",format:"float32x3",stepMode:"instance"})])),t(o?.fragmentShader).toContain(".x"),t(o?.fragmentShader).toContain("> 0.5")}),o("maps THREE.SpriteMaterial to the native sprite shader",()=>{const e=new a(new Uint8Array([255,255,255,255]),1,1,s),o=new i({map:e,color:8429760,opacity:.6,rotation:.25,sizeAttenuation:!1,alphaTest:.2,transparent:!0}),r=new M({WGSLShaderMaterial:P}),n=r.resolve(o);t(n).toBeInstanceOf(P),t(n?.vertexShader).toContain("materialUniforms.rotation"),t(n?.vertexShader).toContain("materialUniforms.screenSpaceSize"),t(n?.fragmentShader).toContain("textureSample("),t(n?.alphaTest).toBe(.2),t(n?.transparent).toBe(!0),t(n?.uniforms.rotation.value).toBe(.25),t(n?.uniforms.screenSpaceSize.value).toBe(1),o.rotation=.75;const l=r.resolve(o);t(l).toBe(n),t(l?.uniforms.rotation.value).toBe(.75)}),o("memoizes node-material signatures for repeated lookups",()=>{const e=["version","vertexShader","fragmentShader","alphaTest","alphaToCoverage","blending","colorWrite","depthFunc","depthTest","depthWrite","polygonOffset","polygonOffsetFactor","polygonOffsetUnits","premultipliedAlpha","side","stencilWrite","transparent"],o=new Map([["version",1],["vertexShader","#vertex"],["fragmentShader","#fragment"],["alphaTest",0],["alphaToCoverage",!1],["blending",1],["colorWrite",!0],["depthFunc",3],["depthTest",!0],["depthWrite",!0],["polygonOffset",!1],["polygonOffsetFactor",0],["polygonOffsetUnits",0],["premultipliedAlpha",!1],["side",0],["stencilWrite",!1],["transparent",!1]]);let a=0;const r=new Proxy({},{get:(t,r)=>"string"==typeof r&&e.includes(r)?(a+=1,o.get(r)):Reflect.get(t,r)});C(r),C(r),t(a).toBe(e.length)}),o("adapts a NodeShaderMaterial without replacing its scene material",()=>{const e=v("intensity",.75),o=new p({color:c({color:u(5210052).multiplyScalar(e),roughness:.42,metalness:.18}),transparent:!0,alphaTest:.25}),a=new M({WGSLShaderMaterial:P}),r=a.resolve(o);t(r).toBeInstanceOf(P),t(r).not.toBe(o),t(r?.transparent).toBe(!0),t(r?.alphaTest).toBe(.25),t(r?.fragmentShader).toContain("rendererPointLightForLight"),t(o.isShaderMaterial).toBe(!0),e.value=.25,t(a.resolve(o)).toBe(r),t(r?.uniforms.intensity?.value).toBe(.25)}),o("syncs direct NodeShaderMaterial uniform mutations to the resolved material",()=>{const e=S("trailTint",new l(0,0,0,0)),o=v("hology_particle_energy",1),a=new p({color:e.multiplyScalar(o)}),r=new M({WGSLShaderMaterial:P});a.uniforms.trailTint.value=new l(1,.25,.5,.75),a.uniforms.hology_particle_energy.value=.4;const n=r.resolve(a);t(n?.uniforms.trailTint.value).toEqual(new l(1,.25,.5,.75)),t(n?.uniforms.hology_particle_energy.value).toBe(.4),a.uniforms.trailTint.value.set(.2,.4,.6,.8),a.uniforms.hology_particle_energy.value=.1,t(r.resolve(a)).toBe(n),t(n?.uniforms.trailTint.value).toEqual(new l(.2,.4,.6,.8)),t(n?.uniforms.hology_particle_energy.value).toBe(.1)}),o("only syncs explicitly invalidated uniforms when auto update is disabled",()=>{const e=v("intensity",.75),o=new p({color:m(x(e))});o.uniformValuesAutoUpdate=!1;const a=new M({WGSLShaderMaterial:P}),r=a.resolve(o),n=r.uniformValuesAutoVersion;e.value=.25,t(a.resolve(o)).toBe(r),t(r?.uniforms.intensity.value).toBe(.75),t(r?.uniformValuesAutoVersion).toBe(n),o.uniformValuesNeedsUpdate=!0,t(a.resolve(o)).toBe(r),t(r?.uniforms.intensity.value).toBe(.25),t(r?.uniformValuesAutoVersion).toBe(n+1)}),o("supports explicit invalidation for mapped Three.js materials",()=>{const e=new n({roughness:.8});T(e,!1);const o=new M({WGSLShaderMaterial:P}),a=o.resolve(e);e.roughness=.2,t(o.resolve(e)).toBe(a),t(a?.uniforms.roughness.value).toBe(.8),B(e),t(o.resolve(e)).toBe(a),t(a?.uniforms.roughness.value).toBe(.2)}),o("binds uniforms referenced only by an MRT material output",()=>{const e=v("roughness",.7),o=new p({color:m(5601177),alphaTest:.1});o.outputRoughness=e;const a=new M({WGSLShaderMaterial:P},e=>[e.outputColor,y(x(0,0,1),e.outputRoughness)]).resolve(o);t(a?.fragmentShader).toContain("materialUniforms.roughness"),t(a?.fragmentShader).not.toContain("graphColor"),t(a?.fragmentShader).toMatch(/if \(.+ < 0\.1\) \{ discard; \}/),t(a?.uniforms.roughness?.value).toBe(.7)}),o("compiles a landscape composite built from node material semantic outputs",()=>{const e=new M({WGSLShaderMaterial:P}),o=new p({color:c({color:u(5147450),roughness:.82,metalness:0})}),a=new p({color:c({color:u(7432286),roughness:.6,metalness:.05})}),r=new L;r.layers=[o,a];const n=e.resolve(r.build());t(n).toBeInstanceOf(P),t(n?.fragmentShader).toContain("rendererDirectionalLightForLight"),t(n?.vertexShader).toContain("@location(6) material: vec4<f32>"),t(n?.vertexShader).toContain("@location(8) hole: f32")}),o("allocates the trail's authored vertex attributes",()=>{const e=new M({WGSLShaderMaterial:P}).resolve(I.createBaseMaterial());t(e).toBeInstanceOf(P),t(e?.vertexAttributes).toEqual(t.arrayContaining([t.objectContaining({name:"nodeID",shaderLocation:6,format:"float32"}),t.objectContaining({name:"nodeCenter",shaderLocation:7,format:"float32x3"})]))}),o("uses Three's default value when a geometry has no uv1 attribute",()=>{const e=W([{name:"uv1",shaderLocation:6,format:"float32x2"},{name:"custom",shaderLocation:7,format:"float32"}]);t(e).toEqual(t.arrayContaining([t.objectContaining({name:"uv1",defaultValue:[0,0]}),t.objectContaining({name:"custom"})])),t(e[1]).not.toHaveProperty("defaultValue")}),o("compiles the foliage transform and named texture-uniform pattern",()=>{const e=new M({WGSLShaderMaterial:P}),o=new a(new Uint8Array([255,255,255,255]),1,1,s),r=new p({color:g("map").sample(w.uv),transform:f(v("windOffset",.25)),uniforms:{map:{value:o}},alphaTest:.5}),n=e.resolve(r);t(n).toBeInstanceOf(P),t(n?.vertexShader).toContain("rendererClipPosition(_ng_localPosition"),t(n?.depthVertexShader).toContain("materialUniforms.windOffset"),t(n?.depthFragmentShader).toContain("textureSample("),t(n?.depthFragmentShader).toContain("< 0.5) { discard;"),t(n?.pointShadowFragmentShader).toContain("distanceToLight")}),o("rebuilds cached materials when scene-local texture bindings change",()=>{const e=new M({WGSLShaderMaterial:P}),o=new a(new Uint8Array([255,255,255,255]),1,1,s),r=new a(new Uint8Array([32,64,128,255]),1,1,s),n=new p({color:g("map").sample(w.uv),uniforms:{map:{value:o}},alphaTest:.5}),i=e.resolve(n);n.uniforms.map.value=r;const l=e.resolve(n);t(l).not.toBe(i),t(i.disposed).toBe(!0),n.dispose();const d=e.resolve(n);t(d).not.toBe(l),t(l.disposed).toBe(!0)}),o("uses the renderer batch id without Three’s batchingIdTexture",()=>{const e=new M({WGSLShaderMaterial:P}),o=new a(new Uint8Array([255,96,24,255]),1,1,s),r=new p({color:m(d("vp0")),uniforms:{vp0:{value:o}}}),n=e.resolve(r);t(n).toBeInstanceOf(P),t(n?.vertexShader).toContain("rendererBatchingId(input.instanceIndex)")}),o("compiles depth nodes that use fragment-coordinate expressions",()=>{const e=new M({WGSLShaderMaterial:P}),o=new p({color:m(x(j.x,j.y,U))}),a=e.resolve(o);t(a).toBeInstanceOf(P),t(a?.fragmentShader).toContain("input.position.xy"),t(a?.fragmentShader).toContain("input.position.z"),t(a?.fragmentShader).toContain("rendererCamera.viewportAndTime.xy"),t(a?.fragmentShader).not.toContain("gl_FragCoord")}),o("maps scene color and depth nodes to renderer-owned textures",()=>{const e=new M({WGSLShaderMaterial:P}),o=new p({color:E(j).multiplyScalar(V(j))}),a=e.resolve(o);t(a.sceneTextures).toEqual({hology_scene_map:"sceneColor",hology_depth_map:"sceneDepth"}),t(a.graphTextures).toEqual({}),t(a.fragmentShader).toContain("hology_scene_mapTexture"),t(a.fragmentShader).toContain("hology_depth_mapTexture"),t(a.fragmentShader).toContain("vec4<f32>(textureSample(hology_depth_mapTexture")}),o("caches distinct material variants for opaque and late draw stages",()=>{const e=new M({WGSLShaderMaterial:P},(e,t)=>"opaque"===t?[m(x(1)),m(x(0))]:void 0),o=new p({color:m(x(1))}),a=e.resolve(o,"opaque"),r=e.resolve(o,"late");t(a).not.toBe(r),t(e.resolve(o,"opaque")).toBe(a),t(e.resolve(o,"late")).toBe(r),t(a?.fragmentShader).toContain("@location(1)"),t(r?.fragmentShader).not.toContain("@location(1)")}),o("reconstructs WebGPU depth positions with inverted NDC Y",()=>{const e=new M({WGSLShaderMaterial:P}),o=new p({color:m(A.add(G.multiplyScalar(0)))}),a=e.resolve(o);t(a.fragmentShader).toContain("vec2<f32>(2.0, -2.0)"),t(a.fragmentShader).toMatch(/-\(float_op_\d+\)/)}),o("emits dither and parallax nodes without GLSL custom functions",()=>{const e=new M({WGSLShaderMaterial:P}),o=new a(new Uint8Array([128,128,128,255]),1,1,s),r=O(w.uv,g("heightMap",o),h(.03)),n=new p({color:y(r.x,r.y,F(x(.2,.4,.8)).z,1)}),i=e.resolve(n);t(i).toBeInstanceOf(P),t(i?.fragmentShader).toContain("textureSampleLevel(heightMapTexture, heightMapSampler"),t(i?.fragmentShader).toMatch(/= -dpdy\(-pom_\d+ViewPosition\)/),t(i?.fragmentShader).toMatch(/= -dpdy\(pom_\d+Uv\)/),t(i?.fragmentShader).not.toContain("customFunction_"),t(i?.fragmentShader).not.toContain("gl_FragCoord")}),o("inherits, updates, and clears the WebGPU world environment",()=>{const e=new a(new Uint8Array([255,255,255,255]),1,1,s),o=new p({color:c({color:u(8421504),roughness:.5,metalness:.1})}),r=new M({WGSLShaderMaterial:P});r.setWorldEnvironment({texture:e,intensity:.75});const n=r.resolve(o);t(n.fragmentShader).toContain("envMapTexture"),t(n.uniforms.envMapIntensity?.value).toBe(.75),t(o.envMap).toBeUndefined(),r.setWorldEnvironment({texture:e,intensity:.25});const i=r.resolve(o);t(i).toBe(n),t(i.uniforms.envMapIntensity?.value).toBe(.25),r.setWorldEnvironment(null);const l=r.resolve(o);t(l).not.toBe(n),t(n.disposed).toBe(!0),t(l.fragmentShader).not.toContain("envMapTexture")}),o("keeps an authored material environment ahead of the world environment",()=>{const e=new a(new Uint8Array([255,255,255,255]),1,1,s),o=new a(new Uint8Array([64,96,128,255]),1,1,s),r=new p({color:c({color:u(8421504),roughness:.5,metalness:.1}),envMap:o}),n=new M({WGSLShaderMaterial:P});n.setWorldEnvironment({texture:e,intensity:.2}),n.resolve(r),t(r.uniforms.envMap.value).toBe(o),t(r.envMap).toBe(o)})});/*
|
|
1
|
+
import{describe as e,expect as t,it as o}from"vitest";import{DataTexture as a,Material as r,MeshStandardMaterial as n,RGBAFormat as s,SpriteMaterial as i,Vector4 as l}from"three";import{batchingUniformVec4 as d,float as h,NodeShaderMaterial as p,rgb as u,rgba as m,standardMaterial as c,translateX as f,uniformFloat as v,uniformVec4 as S,uniformSampler2d as g,varyingAttributes as w,vec3 as x,vec4 as y}from"three-shader-graph";import{createNodeMaterialSignature as C,markMaterialUniformValuesNeedUpdate as B,NodeMaterialWebGpuResolver as M,setMaterialUniformValuesAutoUpdate as T,withThreeDefaultVertexAttributeValues as W}from"../rendering/node-material-webgpu-resolver.js";import{LandscapeCompositeShader as L}from"../shader/builtin/landscape-composite-shader.js";import{DecalUnlitShader as b}from"../shader/builtin/decal-unlit-shader.js";import{getSpritePosition as _}from"../shader/sprite-shader.js";import{depthNormal as G,depthWorldPosition as U,fragmentLinearEyeDepth as A,sampleSceneDepth as V,screenUV as j}from"../shader-nodes/depth.js";import{sampleSceneColor as E}from"../shader-nodes/scene-sample.js";import{applyDithering as F}from"../shader-nodes/dither.js";import{parallaxOcclusionMapping as O}from"../shader-nodes/pom.js";import{elapsedTimeUniformName as q}from"../shader-nodes/time.js";import{Trail as I}from"../effects/vfx/trail-renderer.js";import{particleUniforms as D}from"../shader-nodes/particle.js";class P extends r{set uniformValuesNeedsUpdate(e){e&&this.uniformValuesAutoVersion++}constructor(e){super(),this.disposed=!1,this.uniformValuesAutoUpdate=!0,this.uniformValuesAutoVersion=0,this.vertexShader=e.vertexShader,this.fragmentShader=e.fragmentShader,this.depthVertexShader=e.depthVertexShader??null,this.depthFragmentShader=e.depthFragmentShader??null,this.pointShadowVertexShader=e.pointShadowVertexShader??null,this.pointShadowFragmentShader=e.pointShadowFragmentShader??null,this.uniforms=e.uniforms,this.sceneTextures=e.sceneTextures??{},this.graphTextures=e.graphTextures??{},this.vertexAttributes=e.vertexAttributes??[],this.transparent=e.transparent??!1,this.alphaTest=e.alphaTest??0,this.depthTest=e.depthTest??!0,this.depthWrite=e.depthWrite??!0,this.side=e.side??this.side}dispose(){this.disposed=!0,super.dispose()}}e("NodeMaterialWebGpuResolver",()=>{o("compiles decal surface rejection without undefined WGSL expressions",()=>{const e=(new b).build(),o=new M({WGSLShaderMaterial:P}).resolve(e);t(o?.fragmentShader).not.toContain("undefined"),t(o?.fragmentShader).toContain("hology_scene_mapTexture")}),o("recompiles an opaque variant when receiveDecals changes",()=>{const e=new p({color:m(16777215)});e.userData.receiveDecals=!0;const o=new M({WGSLShaderMaterial:P},e=>[m(16777215,!1===e.userData.receiveDecals?0:2)]),a=o.resolve(e,"opaque");e.userData.receiveDecals=!1,e.needsUpdate=!0;const r=o.resolve(e,"opaque");t(r).not.toBe(a),t(a.disposed).toBe(!0),t(a.fragmentShader).not.toBe(r.fragmentShader)}),o("maps Hology elapsed time to the renderer frame clock",()=>{const e=v(q),o=new p({color:m(x(e)),transform:f(e)}),a=new M({WGSLShaderMaterial:P}).resolve(o);t(a?.vertexShader).toContain("rendererElapsedTime()"),t(a?.fragmentShader).toContain("rendererElapsedTime()"),t(a?.depthVertexShader).toContain("rendererElapsedTime()"),t(a?.pointShadowVertexShader).toContain("rendererElapsedTime()"),t(a?.uniforms).not.toHaveProperty(q)}),o("compiles the native sprite billboard position without a GLSL fallback",()=>{const e=new p({color:m(16777215),position:_(v("rotation",.25),v("screenSpaceSize",0),v("lockYAxis",1))}),o=new M({WGSLShaderMaterial:P}).resolve(e);t(o).toBeInstanceOf(P),t(o?.vertexShader).toContain("cos("),t(o?.vertexShader).toContain("sin("),t(o?.vertexShader).toContain("materialUniforms.lockYAxis"),t(o?.vertexShader).not.toContain("customFunction_")}),o("uses the per-instance rotation attribute for instanced sprites",()=>{const e=new p({color:m(16777215),position:_(v("rotation",0),void 0,void 0,!0)}),o=new M({WGSLShaderMaterial:P}).resolve(e);t(o?.vertexAttributes).toEqual(t.arrayContaining([t.objectContaining({name:"rotation",format:"float32",stepMode:"instance"})])),t(o?.vertexShader).toContain("input.rotation"),t(o?.vertexShader).not.toContain("materialUniforms.rotation")}),o("uses per-instance particle opacity in WebGPU fragment shaders",()=>{const e=new p({color:m(u(16777215),D.opacity)}),o=new M({WGSLShaderMaterial:P}).resolve(e);t(o?.vertexAttributes).toEqual(t.arrayContaining([t.objectContaining({name:"particleData",format:"float32x3",stepMode:"instance"})])),t(o?.fragmentShader).toContain(".x"),t(o?.fragmentShader).toContain("> 0.5")}),o("maps THREE.SpriteMaterial to the native sprite shader",()=>{const e=new a(new Uint8Array([255,255,255,255]),1,1,s),o=new i({map:e,color:8429760,opacity:.6,rotation:.25,sizeAttenuation:!1,alphaTest:.2,transparent:!0}),r=new M({WGSLShaderMaterial:P}),n=r.resolve(o);t(n).toBeInstanceOf(P),t(n?.vertexShader).toContain("materialUniforms.rotation"),t(n?.vertexShader).toContain("materialUniforms.screenSpaceSize"),t(n?.fragmentShader).toContain("textureSample("),t(n?.alphaTest).toBe(.2),t(n?.transparent).toBe(!0),t(n?.uniforms.rotation.value).toBe(.25),t(n?.uniforms.screenSpaceSize.value).toBe(1),o.rotation=.75;const l=r.resolve(o);t(l).toBe(n),t(l?.uniforms.rotation.value).toBe(.75)}),o("memoizes node-material signatures for repeated lookups",()=>{const e=["version","vertexShader","fragmentShader","alphaTest","alphaToCoverage","blending","colorWrite","depthFunc","depthTest","depthWrite","polygonOffset","polygonOffsetFactor","polygonOffsetUnits","premultipliedAlpha","side","stencilWrite","transparent"],o=new Map([["version",1],["vertexShader","#vertex"],["fragmentShader","#fragment"],["alphaTest",0],["alphaToCoverage",!1],["blending",1],["colorWrite",!0],["depthFunc",3],["depthTest",!0],["depthWrite",!0],["polygonOffset",!1],["polygonOffsetFactor",0],["polygonOffsetUnits",0],["premultipliedAlpha",!1],["side",0],["stencilWrite",!1],["transparent",!1]]);let a=0;const r=new Proxy({},{get:(t,r)=>"string"==typeof r&&e.includes(r)?(a+=1,o.get(r)):Reflect.get(t,r)});C(r),C(r),t(a).toBe(e.length)}),o("adapts a NodeShaderMaterial without replacing its scene material",()=>{const e=v("intensity",.75),o=new p({color:c({color:u(5210052).multiplyScalar(e),roughness:.42,metalness:.18}),transparent:!0,alphaTest:.25}),a=new M({WGSLShaderMaterial:P}),r=a.resolve(o);t(r).toBeInstanceOf(P),t(r).not.toBe(o),t(r?.transparent).toBe(!0),t(r?.alphaTest).toBe(.25),t(r?.fragmentShader).toContain("rendererPointLightForLight"),t(o.isShaderMaterial).toBe(!0),e.value=.25,t(a.resolve(o)).toBe(r),t(r?.uniforms.intensity?.value).toBe(.25)}),o("syncs direct NodeShaderMaterial uniform mutations to the resolved material",()=>{const e=S("trailTint",new l(0,0,0,0)),o=v("hology_particle_energy",1),a=new p({color:e.multiplyScalar(o)}),r=new M({WGSLShaderMaterial:P});a.uniforms.trailTint.value=new l(1,.25,.5,.75),a.uniforms.hology_particle_energy.value=.4;const n=r.resolve(a);t(n?.uniforms.trailTint.value).toEqual(new l(1,.25,.5,.75)),t(n?.uniforms.hology_particle_energy.value).toBe(.4),a.uniforms.trailTint.value.set(.2,.4,.6,.8),a.uniforms.hology_particle_energy.value=.1,t(r.resolve(a)).toBe(n),t(n?.uniforms.trailTint.value).toEqual(new l(.2,.4,.6,.8)),t(n?.uniforms.hology_particle_energy.value).toBe(.1)}),o("only syncs explicitly invalidated uniforms when auto update is disabled",()=>{const e=v("intensity",.75),o=new p({color:m(x(e))});o.uniformValuesAutoUpdate=!1;const a=new M({WGSLShaderMaterial:P}),r=a.resolve(o),n=r.uniformValuesAutoVersion;e.value=.25,t(a.resolve(o)).toBe(r),t(r?.uniforms.intensity.value).toBe(.75),t(r?.uniformValuesAutoVersion).toBe(n),o.uniformValuesNeedsUpdate=!0,t(a.resolve(o)).toBe(r),t(r?.uniforms.intensity.value).toBe(.25),t(r?.uniformValuesAutoVersion).toBe(n+1)}),o("supports explicit invalidation for mapped Three.js materials",()=>{const e=new n({roughness:.8});T(e,!1);const o=new M({WGSLShaderMaterial:P}),a=o.resolve(e);e.roughness=.2,t(o.resolve(e)).toBe(a),t(a?.uniforms.roughness.value).toBe(.8),B(e),t(o.resolve(e)).toBe(a),t(a?.uniforms.roughness.value).toBe(.2)}),o("binds uniforms referenced only by an MRT material output",()=>{const e=v("roughness",.7),o=new p({color:m(5601177),alphaTest:.1});o.outputRoughness=e;const a=new M({WGSLShaderMaterial:P},e=>[e.outputColor,y(x(0,0,1),e.outputRoughness)]).resolve(o);t(a?.fragmentShader).toContain("materialUniforms.roughness"),t(a?.fragmentShader).not.toContain("graphColor"),t(a?.fragmentShader).toMatch(/if \(.+ < 0\.1\) \{ discard; \}/),t(a?.uniforms.roughness?.value).toBe(.7)}),o("compiles a landscape composite built from node material semantic outputs",()=>{const e=new M({WGSLShaderMaterial:P}),o=new p({color:c({color:u(5147450),roughness:.82,metalness:0})}),a=new p({color:c({color:u(7432286),roughness:.6,metalness:.05})}),r=new L;r.layers=[o,a];const n=e.resolve(r.build());t(n).toBeInstanceOf(P),t(n?.fragmentShader).toContain("rendererDirectionalLightForLight"),t(n?.vertexShader).toContain("@location(6) material: vec4<f32>"),t(n?.vertexShader).toContain("@location(8) hole: f32")}),o("allocates the trail's authored vertex attributes",()=>{const e=new M({WGSLShaderMaterial:P}).resolve(I.createBaseMaterial());t(e).toBeInstanceOf(P),t(e?.vertexAttributes).toEqual(t.arrayContaining([t.objectContaining({name:"nodeID",shaderLocation:6,format:"float32"}),t.objectContaining({name:"nodeCenter",shaderLocation:7,format:"float32x3"})]))}),o("uses Three's default value when a geometry has no uv1 attribute",()=>{const e=W([{name:"uv1",shaderLocation:6,format:"float32x2"},{name:"custom",shaderLocation:7,format:"float32"}]);t(e).toEqual(t.arrayContaining([t.objectContaining({name:"uv1",defaultValue:[0,0]}),t.objectContaining({name:"custom"})])),t(e[1]).not.toHaveProperty("defaultValue")}),o("compiles the foliage transform and named texture-uniform pattern",()=>{const e=new M({WGSLShaderMaterial:P}),o=new a(new Uint8Array([255,255,255,255]),1,1,s),r=new p({color:g("map").sample(w.uv),transform:f(v("windOffset",.25)),uniforms:{map:{value:o}},alphaTest:.5}),n=e.resolve(r);t(n).toBeInstanceOf(P),t(n?.vertexShader).toContain("rendererClipPosition(_ng_localPosition"),t(n?.depthVertexShader).toContain("materialUniforms.windOffset"),t(n?.depthFragmentShader).toContain("textureSample("),t(n?.depthFragmentShader).toContain("< 0.5) { discard;"),t(n?.pointShadowFragmentShader).toContain("distanceToLight")}),o("rebuilds cached materials when scene-local texture bindings change",()=>{const e=new M({WGSLShaderMaterial:P}),o=new a(new Uint8Array([255,255,255,255]),1,1,s),r=new a(new Uint8Array([32,64,128,255]),1,1,s),n=new p({color:g("map").sample(w.uv),uniforms:{map:{value:o}},alphaTest:.5}),i=e.resolve(n);n.uniforms.map.value=r;const l=e.resolve(n);t(l).not.toBe(i),t(i.disposed).toBe(!0),n.dispose();const d=e.resolve(n);t(d).not.toBe(l),t(l.disposed).toBe(!0)}),o("uses the renderer batch id without Three’s batchingIdTexture",()=>{const e=new M({WGSLShaderMaterial:P}),o=new a(new Uint8Array([255,96,24,255]),1,1,s),r=new p({color:m(d("vp0")),uniforms:{vp0:{value:o}}}),n=e.resolve(r);t(n).toBeInstanceOf(P),t(n?.vertexShader).toContain("rendererBatchingId(input.instanceIndex)")}),o("compiles depth nodes that use fragment-coordinate expressions",()=>{const e=new M({WGSLShaderMaterial:P}),o=new p({color:m(x(j.x,j.y,A))}),a=e.resolve(o);t(a).toBeInstanceOf(P),t(a?.fragmentShader).toContain("input.position.xy"),t(a?.fragmentShader).toContain("input.position.z"),t(a?.fragmentShader).toContain("rendererViewportSize()"),t(a?.fragmentShader).not.toContain("gl_FragCoord")}),o("maps scene color and depth nodes to renderer-owned textures",()=>{const e=new M({WGSLShaderMaterial:P}),o=new p({color:E(j).multiplyScalar(V(j))}),a=e.resolve(o);t(a.sceneTextures).toEqual({hology_scene_map:"sceneColor",hology_depth_map:"sceneDepth"}),t(a.graphTextures).toEqual({}),t(a.fragmentShader).toContain("hology_scene_mapTexture"),t(a.fragmentShader).toContain("hology_depth_mapTexture"),t(a.fragmentShader).toContain("vec4<f32>(textureSample(hology_depth_mapTexture")}),o("caches distinct material variants for opaque and late draw stages",()=>{const e=new M({WGSLShaderMaterial:P},(e,t)=>"opaque"===t?[m(x(1)),m(x(0))]:void 0),o=new p({color:m(x(1))}),a=e.resolve(o,"opaque"),r=e.resolve(o,"late");t(a).not.toBe(r),t(e.resolve(o,"opaque")).toBe(a),t(e.resolve(o,"late")).toBe(r),t(a?.fragmentShader).toContain("@location(1)"),t(r?.fragmentShader).not.toContain("@location(1)")}),o("reconstructs WebGPU depth positions with inverted NDC Y",()=>{const e=new M({WGSLShaderMaterial:P}),o=new p({color:m(U.add(G.multiplyScalar(0)))}),a=e.resolve(o);t(a.fragmentShader).toContain("vec2<f32>(2.0, -2.0)"),t(a.fragmentShader).toMatch(/-\(float_op_\d+\)/)}),o("emits dither and parallax nodes without GLSL custom functions",()=>{const e=new M({WGSLShaderMaterial:P}),o=new a(new Uint8Array([128,128,128,255]),1,1,s),r=O(w.uv,g("heightMap",o),h(.03)),n=new p({color:y(r.x,r.y,F(x(.2,.4,.8)).z,1)}),i=e.resolve(n);t(i).toBeInstanceOf(P),t(i?.fragmentShader).toContain("textureSampleLevel(heightMapTexture, heightMapSampler"),t(i?.fragmentShader).toMatch(/= -dpdy\(-pom_\d+ViewPosition\)/),t(i?.fragmentShader).toMatch(/= -dpdy\(pom_\d+Uv\)/),t(i?.fragmentShader).not.toContain("customFunction_"),t(i?.fragmentShader).not.toContain("gl_FragCoord")}),o("inherits, updates, and clears the WebGPU world environment",()=>{const e=new a(new Uint8Array([255,255,255,255]),1,1,s),o=new p({color:c({color:u(8421504),roughness:.5,metalness:.1})}),r=new M({WGSLShaderMaterial:P});r.setWorldEnvironment({texture:e,intensity:.75});const n=r.resolve(o);t(n.fragmentShader).toContain("envMapTexture"),t(n.uniforms.envMapIntensity?.value).toBe(.75),t(o.envMap).toBeUndefined(),r.setWorldEnvironment({texture:e,intensity:.25});const i=r.resolve(o);t(i).toBe(n),t(i.uniforms.envMapIntensity?.value).toBe(.25),r.setWorldEnvironment(null);const l=r.resolve(o);t(l).not.toBe(n),t(n.disposed).toBe(!0),t(l.fragmentShader).not.toContain("envMapTexture")}),o("keeps an authored material environment ahead of the world environment",()=>{const e=new a(new Uint8Array([255,255,255,255]),1,1,s),o=new a(new Uint8Array([64,96,128,255]),1,1,s),r=new p({color:c({color:u(8421504),roughness:.5,metalness:.1}),envMap:o}),n=new M({WGSLShaderMaterial:P});n.setWorldEnvironment({texture:e,intensity:.2}),n.resolve(r),t(r.uniforms.envMap.value).toBe(o),t(r.envMap).toBe(o)})});/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hology/core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.236",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -198,7 +198,7 @@
|
|
|
198
198
|
"dependencies": {
|
|
199
199
|
"@babel/runtime": "^7.24.8",
|
|
200
200
|
"@dimforge/rapier3d-simd-compat": "^0.19.3",
|
|
201
|
-
"@hology/nebula": "^0.0.
|
|
201
|
+
"@hology/nebula": "^0.0.160",
|
|
202
202
|
"@plumier/reflect": "^1.1.0",
|
|
203
203
|
"@recast-navigation/three": "0.39.0",
|
|
204
204
|
"recast-navigation": "0.39.0",
|