@hology/core 0.0.98 → 0.0.99
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/behaviours.d.ts.map +1 -1
- package/dist/effects/vfx/behaviours.js +1 -1
- package/dist/effects/vfx/vfx-defs.js +1 -1
- package/dist/effects/vfx/vfx-materializer.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/effects/vfx/vfx-renderers.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-renderers.js +1 -1
- package/dist/gameplay/services/physics/physics-system.d.ts +7 -0
- package/dist/gameplay/services/physics/physics-system.d.ts.map +1 -1
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/rendering.d.ts.map +1 -1
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts +1 -0
- package/dist/scene/asset-resource-loader.d.ts.map +1 -1
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/materializer.d.ts.map +1 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/storage/storage.d.ts +2 -0
- package/dist/scene/storage/storage.d.ts.map +1 -1
- package/dist/scene/storage/storage.js +1 -1
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"behaviours.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/behaviours.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAY,OAAO,EAAE,QAAQ,EAAmB,MAAM,gBAAgB,CAAA;AACxF,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAG9B,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAA;AAElD;;GAEG;AACH,qBAAa,cAAe,SAAQ,SAAS;IAE/B,OAAO,CAAC,IAAI;IAAiB,OAAO,CAAC,KAAK;gBAAlC,IAAI,EAAE,KAAK,CAAC,OAAO,EAAU,K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,CAAS;IAC7B,OAAO,CAAC,OAAO,CAAS;gBAEJ,CAAC,EAAE,MAAM,EAAU,CAAC,EAAE,MAAM,EAAU,CAAC,EAAE,MAAM,EAAE,MAAM,GAAE,cAAgC;IAM7G,UAAU,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI;IAMpC,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;CAyBtE"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{Behaviour as t,Vector3D as s,ease as
|
1
|
+
import{Vector3 as i}from"three";import{Behaviour as t,Vector3D as s,ease as e,MathUtils as o}from"@hology/nebula";import*as n from"three";export class RotatePosition extends t{constructor(i,t){super(),this.axis=i,this.angle=t,this.axis3D=new s(this.axis.x,this.axis.y,this.axis.z)}mutate(i,t,s){this.energize(i,t),null!=i.old&&0!=i.old.position.lengthSq()&&(a.copy(i.old.position),a.sub(i.parent.position),a.applyAxisAngle(this.axis3D,this.angle*t),a.add(i.parent.position),a.sub(i.old.position).divideScalar(t),i.velocity.sub(a)),a.copy(i.position),a.sub(i.parent.position),a.applyAxisAngle(this.axis3D,this.angle*t),a.add(i.parent.position),a.sub(i.position).divideScalar(t),i.velocity.add(a)}}const a=new i;export var AxisDirection;!function(i){i[i.x=0]="x",i[i.y=1]="y",i[i.z=2]="z",i[i.mx=3]="mx",i[i.my=4]="my",i[i.mz=5]="mz"}(AxisDirection||(AxisDirection={}));export class OrientAlongVelocity extends t{constructor(i){super(),this.axisDirection=i}initialize(i){i.transform.orientAlongVelocity=!0}mutate(i,t,s){i.target,n.Object3D}}export class FollowParent extends t{constructor(i){super(),this.speed=i}initialize(i){}mutate(i,t,s){const e=i.parent.parentParticle??i.parent;if(0===this.speed)return i.position.copy(e.old.position),i.acceleration.copy(e.acceleration),void i.velocity.copy(e.velocity);const o=r.copy(e.position).sub(i.position),n=(o.length(),o.normalize());l.copy(n).multiplyScalar(this.speed),i.velocity.copy(l)}}export class Scale extends t{constructor(i,t,s){super(void 0,s),this.scaleA=i,this.scaleB=t}initialize(i){i.transform.scaleA=i.scale*this.scaleA,i.transform.scaleB=i.scale*this.scaleB,i.transform.oldRadius=i.radius}mutate(i,t,s){this.energize(i,t),i.scale=o.lerp(i.transform.scaleA,i.transform.scaleB,this.energy),i.scale<5e-4&&(i.scale=0),i.radius=i.transform.oldRadius*i.scale}}export class LinearDamping extends t{constructor(i){super(),this.factor=i}mutate(i,t,s){this.energize(i,t);const e=r.copy(i.velocity).multiplyScalar(-this.factor*t);i.velocity.add(e)}}const r=new s,l=new s;export var AxisPlane;!function(i){i[i.xy=0]="xy",i[i.xz=1]="xz",i[i.yz=2]="yz",i[i.xyz=3]="xyz"}(AxisPlane||(AxisPlane={}));export class Disperse extends t{constructor(i,t,s=e.easeLinear){super(void 0,s,void 0,!0),this.distance=i,this.plane=t}initialize(i){i.transform.initialPos=i.position.clone();const t=c.copy(i.transform.initialPos).sub(i.parent.position).normalize();switch(this.plane){case AxisPlane.xy:t.setComponent(2,0);break;case AxisPlane.xz:t.setComponent(1,0);break;case AxisPlane.yz:t.setComponent(0,0)}i.transform.displacement=t.clone().multiplyScalar(this.distance),i.transform.prevEnergy=1}mutate(i,t,s){this.energize(i,t);i.transform.initialPos;const e=i.transform.displacement,o=i.transform.prevEnergy-this.energy;i.transform.prevEnergy=this.energy;i.position.x+=e.x*o,i.position.y+=e.y*o,i.position.z+=e.z*o}}export class MoveOverLife extends t{constructor(i,t,s,o=e.easeLinear){super(void 0,o,void 0,!0),this.x=i,this.y=t,this.z=s}initialize(i){i.transform.initialPos=i.position.clone()}mutate(i,t,s){this.energize(i,t);const e=i.transform.initialPos,o=1-this.energy;i.position.x=e.x+this.x*o,i.position.y=e.y+this.y*o,i.position.z=e.z+this.z*o}}const c=new s;/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{MathUtils as e,Vector2 as r,Vector3 as t}from"three";import{Alpha as s,Attraction as n,BoxZone as a,CircleZone as o,Color as i,ease as c,Force as u,Gravity as d,Life as m,LineZone as p,Mass as l,Position as w,RadialVelocity as x,RandomDrift as f,Repulsion as h,Rotate as y,Vector3D as g}from"@hology/nebula";import{AxisDirection as k,AxisPlane as v,Disperse as z,FollowParent as b,LinearDamping as R,MoveOverLife as T,OrientAlongVelocity as L,RotatePosition as V,Scale as j}from"./behaviours.js";import{AdditiveVelocity as D,InitialScale as C,InitialScaleComponents as B,RandomDirection as I,RandomRotation as O,randomRotationAxis as A,RandomScale as K,Rotation as P}from"./initializsers.js";import{PointZone as S,SphereZone as Y}from"./zones.js";import{WorldCollisionBehaviour as M}from"./vfx-collision-behaviour.js";import{Curve2 as X}from"../../utils/curve.js";class Z{build(e={}){const r=N(e,this.parameters);return this.make(r)}}class q{build(e={}){const r=N(e,this.parameters);return this.make(r)}}function E(e,r,t){return{type:"number",default:e,float:!0,min:r,max:t}}function F(e){return{type:"vec3",default:(new t).fromArray(e)}}function G(e){return{type:"color",default:e}}function H(e,r){return{type:"select",opts:e,default:r}}function J(){return{type:"curve",default:X.linear()}}function N(e,r){const t={};for(let s in r)null==e[s]?t[s]=r[s].default:t[s]=e[s];return t}function Q(e){return r=>e.getY(r)}const U={lifetime:new class extends q{constructor(){super(...arguments),this.parameters={duration:E(1,0,1e5)}}make(e={}){return new m(e.duration)}},randomLifetime:new class extends q{constructor(){super(...arguments),this.parameters={minDuration:E(1,0,1e5),maxDuration:E(2,0,1e5)}}make(e={}){return new m(e.minDuration,e.maxDuration)}},positionPoint:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0])}}make(e={}){const{x:r,y:t,z:s}=e.position;return new w(new S(r,t,s))}},positionBox:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0]),dimensions:F([0,0,0])}}make(e={}){const{x:r,y:t,z:s}=e.position,{x:n,y:o,z:i}=e.dimensions;return new w(new a(r,t,s,n,o,i))}},positionSphere:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0]),radius:E(1)}}make(e={}){const{x:r,y:t,z:s}=e.position;return new w(new Y(r,t,s,e.radius))}},positionLine:new class extends q{constructor(){super(...arguments),this.parameters={a:F([0,0,0]),b:F([0,0,1])}}make(e={}){const{x:r,y:t,z:s}=e.a,{x:n,y:a,z:o}=e.b;return new w(new p(r,t,s,n,a,o))}},positionCircle:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0]),rotation:F([0,0,0]),radius:E(1,0,1e4)}}make(r={}){const{x:t,y:s,z:n}=r.position,{x:a,y:i,z:c}=r.rotation;return new w(new o(t,s,n,r.radius,0,e.degToRad(a),e.degToRad(i),e.degToRad(c)))}},positionRing:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0]),rotation:F([0,0,0]),radius:E(1,0,1e4),thickness:E(.2,0,1e4)}}make(r={}){const{x:t,y:s,z:n}=r.position,{x:a,y:i,z:c}=r.rotation;return new w(new o(t,s,n,r.radius,Math.max(r.thickness,1e-4),e.degToRad(a),e.degToRad(i),e.degToRad(c)))}},rotation:new class extends q{constructor(){super(...arguments),this.parameters={rotation:F([0,0,0])}}make(r={}){const{x:s,y:n,z:a}=r.rotation;return new P(new t(e.degToRad(s),e.degToRad(n),e.degToRad(a)))}},randomRotation:new class extends q{constructor(){super(...arguments),this.parameters={axis:H(A,"XYZ")}}make(e={}){return new O(e.axis)}},scale:new class extends q{constructor(){super(...arguments),this.parameters={scale:E(1)}}make(e={}){return new C(e.scale)}},scaleComponents:new class extends q{constructor(){super(...arguments),this.parameters={scale:F([1,1,1])}}make(e={}){return new B(e.scale)}},randomScale:new class extends q{constructor(){super(...arguments),this.parameters={min:E(1),max:E(1)}}make(e={}){return new K(e.min,e.max)}},mass:new class extends q{constructor(){super(...arguments),this.parameters={min:E(1)}}make(e={}){return new l(e.min)}},velocity:new class extends q{constructor(){super(...arguments),this.parameters={velocity:F([0,0,0])}}make(e={}){const{x:r,y:s,z:n}=e.velocity;return new D(new t(r,s,n))}},randomVelocity:new class extends q{constructor(){super(...arguments),this.parameters={min:F([0,0,0]),max:F([0,0,0])}}make(e={}){return new D(e.min,e.max)}},radialVelocity:new class extends q{constructor(){super(...arguments),this.parameters={speed:E(1),direction:F([0,1,0]),spread:E(0)}}make(e={}){return new x(e.speed,new g(e.direction.x,e.direction.y,e.direction.z),e.spread)}},randomDirection:new class extends q{constructor(){super(...arguments),this.parameters={speed:E(1)}}make(e={}){return new I(e.speed)}}},W={force:new class extends Z{constructor(){super(...arguments),this.parameters={force:F([0,0,0]),ease:J()}}make(e={}){return new u(e.force.x,e.force.y,e.force.z,void 0,Q(e.ease))}},gravity:new class extends Z{constructor(){super(...arguments),this.parameters={gravity:E(8),easing:J()}}make(e={}){return new d(e.gravity,void 0,Q(e.easing))}},repulsion:new class extends Z{constructor(){super(...arguments),this.parameters={target:F([0,0,0]),force:E(1),radius:E(1),easing:J()}}make(e={}){const r=new g(e.target.x,e.target.y,e.target.z);return new h(r,e.force,e.radius,void 0,Q(e.easing))}},attraction:new class extends Z{constructor(){super(...arguments),this.parameters={target:F([0,0,0]),force:E(1),radius:E(1),easing:J()}}make(e={}){const r=new g(e.target.x,e.target.y,e.target.z);return new n(r,e.force,e.radius,void 0,Q(e.easing))}},scale:new class extends Z{constructor(){super(...arguments),this.parameters={a:E(1),b:E(1),ease:J()}}make(e={}){return new j(e.a,e.b,Q(e.ease))}},randomDrift:new class extends Z{constructor(){super(...arguments),this.parameters={drift:F([1,1,1]),delay:E(0),ease:J()}}make(e={}){return new f(e.drift.x,e.drift.y,e.drift.z,e.delay,void 0,Q(e.ease))}},rotate:new class extends Z{constructor(){super(...arguments),this.parameters={rotation:F([0,0,0]),ease:J()}}make(r={}){const{x:t,y:s,z:n}=r.rotation;return new y(e.degToRad(t),e.degToRad(s),e.degToRad(n),void 0,Q(r.ease))}},rotateAdd:new class extends Z{constructor(){super(...arguments),this.parameters={rotation:F([0,0,0])}}make(r={}){const{x:t,y:s,z:n}=r.rotation,a=new y(e.degToRad(t),e.degToRad(s),e.degToRad(n),void 0);return a.rotationType="add",a}},changeColor:new class extends Z{constructor(){super(...arguments),this.parameters={a:G("#ffffff"),b:G("#ffffff"),ease:J()}}make(e={}){return new i(e.a,e.b,void 0,Q(e.ease))}},changeOpacity:new class extends Z{constructor(){super(...arguments),this.parameters={a:E(1,0,1),b:E(0,0,1),ease:J()}}make(e={}){return new s(e.a,e.b,void 0,Q(e.ease))}},vortex:new class extends Z{constructor(){super(...arguments),this.parameters={axis:F([0,1,0]),amount:E(1)}}make(e={}){return new V(e.axis,e.amount)}},moveTo:new class extends Z{constructor(){super(...arguments),this.parameters={target:F([0,1,0]),ease:J()}}make(e={}){return new T(e.target.x,e.target.y,e.target.z,Q(e.ease))}},linearDamping:new class extends Z{constructor(){super(...arguments),this.parameters={factor:E(.1,0,1e3)}}make(e={}){return new R(e.factor)}},followParent:new class extends Z{constructor(){super(...arguments),this.parameters={speed:E(
|
1
|
+
import{MathUtils as e,Vector2 as r,Vector3 as t}from"three";import{Alpha as s,Attraction as n,BoxZone as a,CircleZone as o,Color as i,ease as c,Force as u,Gravity as d,Life as m,LineZone as p,Mass as l,Position as w,RadialVelocity as x,RandomDrift as f,Repulsion as h,Rotate as y,Vector3D as g}from"@hology/nebula";import{AxisDirection as k,AxisPlane as v,Disperse as z,FollowParent as b,LinearDamping as R,MoveOverLife as T,OrientAlongVelocity as L,RotatePosition as V,Scale as j}from"./behaviours.js";import{AdditiveVelocity as D,InitialScale as C,InitialScaleComponents as B,RandomDirection as I,RandomRotation as O,randomRotationAxis as A,RandomScale as K,Rotation as P}from"./initializsers.js";import{PointZone as S,SphereZone as Y}from"./zones.js";import{WorldCollisionBehaviour as M}from"./vfx-collision-behaviour.js";import{Curve2 as X}from"../../utils/curve.js";class Z{build(e={}){const r=N(e,this.parameters);return this.make(r)}}class q{build(e={}){const r=N(e,this.parameters);return this.make(r)}}function E(e,r,t){return{type:"number",default:e,float:!0,min:r,max:t}}function F(e){return{type:"vec3",default:(new t).fromArray(e)}}function G(e){return{type:"color",default:e}}function H(e,r){return{type:"select",opts:e,default:r}}function J(){return{type:"curve",default:X.linear()}}function N(e,r){const t={};for(let s in r)null==e[s]?t[s]=r[s].default:t[s]=e[s];return t}function Q(e){return r=>e.getY(r)}const U={lifetime:new class extends q{constructor(){super(...arguments),this.parameters={duration:E(1,0,1e5)}}make(e={}){return new m(e.duration)}},randomLifetime:new class extends q{constructor(){super(...arguments),this.parameters={minDuration:E(1,0,1e5),maxDuration:E(2,0,1e5)}}make(e={}){return new m(e.minDuration,e.maxDuration)}},positionPoint:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0])}}make(e={}){const{x:r,y:t,z:s}=e.position;return new w(new S(r,t,s))}},positionBox:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0]),dimensions:F([0,0,0])}}make(e={}){const{x:r,y:t,z:s}=e.position,{x:n,y:o,z:i}=e.dimensions;return new w(new a(r,t,s,n,o,i))}},positionSphere:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0]),radius:E(1)}}make(e={}){const{x:r,y:t,z:s}=e.position;return new w(new Y(r,t,s,e.radius))}},positionLine:new class extends q{constructor(){super(...arguments),this.parameters={a:F([0,0,0]),b:F([0,0,1])}}make(e={}){const{x:r,y:t,z:s}=e.a,{x:n,y:a,z:o}=e.b;return new w(new p(r,t,s,n,a,o))}},positionCircle:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0]),rotation:F([0,0,0]),radius:E(1,0,1e4)}}make(r={}){const{x:t,y:s,z:n}=r.position,{x:a,y:i,z:c}=r.rotation;return new w(new o(t,s,n,r.radius,0,e.degToRad(a),e.degToRad(i),e.degToRad(c)))}},positionRing:new class extends q{constructor(){super(...arguments),this.parameters={position:F([0,0,0]),rotation:F([0,0,0]),radius:E(1,0,1e4),thickness:E(.2,0,1e4)}}make(r={}){const{x:t,y:s,z:n}=r.position,{x:a,y:i,z:c}=r.rotation;return new w(new o(t,s,n,r.radius,Math.max(r.thickness,1e-4),e.degToRad(a),e.degToRad(i),e.degToRad(c)))}},rotation:new class extends q{constructor(){super(...arguments),this.parameters={rotation:F([0,0,0])}}make(r={}){const{x:s,y:n,z:a}=r.rotation;return new P(new t(e.degToRad(s),e.degToRad(n),e.degToRad(a)))}},randomRotation:new class extends q{constructor(){super(...arguments),this.parameters={axis:H(A,"XYZ")}}make(e={}){return new O(e.axis)}},scale:new class extends q{constructor(){super(...arguments),this.parameters={scale:E(1)}}make(e={}){return new C(e.scale)}},scaleComponents:new class extends q{constructor(){super(...arguments),this.parameters={scale:F([1,1,1])}}make(e={}){return new B(e.scale)}},randomScale:new class extends q{constructor(){super(...arguments),this.parameters={min:E(1),max:E(1)}}make(e={}){return new K(e.min,e.max)}},mass:new class extends q{constructor(){super(...arguments),this.parameters={min:E(1)}}make(e={}){return new l(e.min)}},velocity:new class extends q{constructor(){super(...arguments),this.parameters={velocity:F([0,0,0])}}make(e={}){const{x:r,y:s,z:n}=e.velocity;return new D(new t(r,s,n))}},randomVelocity:new class extends q{constructor(){super(...arguments),this.parameters={min:F([0,0,0]),max:F([0,0,0])}}make(e={}){return new D(e.min,e.max)}},radialVelocity:new class extends q{constructor(){super(...arguments),this.parameters={speed:E(1),direction:F([0,1,0]),spread:E(0)}}make(e={}){return new x(e.speed,new g(e.direction.x,e.direction.y,e.direction.z),e.spread)}},randomDirection:new class extends q{constructor(){super(...arguments),this.parameters={speed:E(1)}}make(e={}){return new I(e.speed)}}},W={force:new class extends Z{constructor(){super(...arguments),this.parameters={force:F([0,0,0]),ease:J()}}make(e={}){return new u(e.force.x,e.force.y,e.force.z,void 0,Q(e.ease))}},gravity:new class extends Z{constructor(){super(...arguments),this.parameters={gravity:E(8),easing:J()}}make(e={}){return new d(e.gravity,void 0,Q(e.easing))}},repulsion:new class extends Z{constructor(){super(...arguments),this.parameters={target:F([0,0,0]),force:E(1),radius:E(1),easing:J()}}make(e={}){const r=new g(e.target.x,e.target.y,e.target.z);return new h(r,e.force,e.radius,void 0,Q(e.easing))}},attraction:new class extends Z{constructor(){super(...arguments),this.parameters={target:F([0,0,0]),force:E(1),radius:E(1),easing:J()}}make(e={}){const r=new g(e.target.x,e.target.y,e.target.z);return new n(r,e.force,e.radius,void 0,Q(e.easing))}},scale:new class extends Z{constructor(){super(...arguments),this.parameters={a:E(1),b:E(1),ease:J()}}make(e={}){return new j(e.a,e.b,Q(e.ease))}},randomDrift:new class extends Z{constructor(){super(...arguments),this.parameters={drift:F([1,1,1]),delay:E(0),ease:J()}}make(e={}){return new f(e.drift.x,e.drift.y,e.drift.z,e.delay,void 0,Q(e.ease))}},rotate:new class extends Z{constructor(){super(...arguments),this.parameters={rotation:F([0,0,0]),ease:J()}}make(r={}){const{x:t,y:s,z:n}=r.rotation;return new y(e.degToRad(t),e.degToRad(s),e.degToRad(n),void 0,Q(r.ease))}},rotateAdd:new class extends Z{constructor(){super(...arguments),this.parameters={rotation:F([0,0,0])}}make(r={}){const{x:t,y:s,z:n}=r.rotation,a=new y(e.degToRad(t),e.degToRad(s),e.degToRad(n),void 0);return a.rotationType="add",a}},changeColor:new class extends Z{constructor(){super(...arguments),this.parameters={a:G("#ffffff"),b:G("#ffffff"),ease:J()}}make(e={}){return new i(e.a,e.b,void 0,Q(e.ease))}},changeOpacity:new class extends Z{constructor(){super(...arguments),this.parameters={a:E(1,0,1),b:E(0,0,1),ease:J()}}make(e={}){return new s(e.a,e.b,void 0,Q(e.ease))}},vortex:new class extends Z{constructor(){super(...arguments),this.parameters={axis:F([0,1,0]),amount:E(1)}}make(e={}){return new V(e.axis,e.amount)}},moveTo:new class extends Z{constructor(){super(...arguments),this.parameters={target:F([0,1,0]),ease:J()}}make(e={}){return new T(e.target.x,e.target.y,e.target.z,Q(e.ease))}},linearDamping:new class extends Z{constructor(){super(...arguments),this.parameters={factor:E(.1,0,1e3)}}make(e={}){return new R(e.factor)}},followParent:new class extends Z{constructor(){super(...arguments),this.parameters={speed:E(0)}}make(e={}){return new b(e.speed)}},worldCollision:new class extends Z{constructor(){super(...arguments),this.parameters={friction:E(1,0,1),bounce:E(1,0,1),lifeLoss:E(0,0)}}make(e={}){return new M(null,e.bounce,e.friction,e.lifeLoss)}}};export const VfxInitializserLibrary=U;export const VfxInitializserLibraryKeys=Object.keys(VfxInitializserLibrary);export const VfxBehaviourLibrary=W;export const VfxBehaviourLibraryKeys=Object.keys(VfxBehaviourLibrary);/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"vfx-materializer.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/vfx-materializer.ts"],"names":[],"mappings":"AAAA,OAAO,MAAiE,MAAM,gBAAgB,CAAC;AAC/F,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAGjC,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAExE,OAAO,EAAE,KAAK,EAAuB,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAa5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAK5E,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;IACzC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;IACnD,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;IACjD,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;CACtD,CAAA;AAGD,wBAAsB,cAAc,CAAC,KAAK,EAAE,QAA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C;IAEpC;;;OAGG;IACH,GAAG,IAAI,CAAC;IAQR;;;OAGG;IACH,OAAO,CAAC,QAAQ,EAAE,CAAC;IAMnB,OAAO;CAGR"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import e,{Behaviour as t,Body as i,Emitter as n,Rate as s}from"@hology/nebula";import*as a from"three";import{Object3D as o}from"three";import{AttributeVec3Node as r,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as m,UniformFloatNode as u,UniformVec3Node as p,Vec3ExpressionNode as h,Vec4Node as d,attributeFloat as f,attributeVec3 as y,attributeVec4 as g,attributes as w,float as v,glslFunction as x,lambertMaterial as A,log as b,pow as E,rgb as M,rgba as P,saturate as I,standardMaterial as T,textureSampler2d as B,transformed as R,uniformFloat as j,uniforms as C,varying as S,varyingAttributes as k,varyingVec3 as z,varyingVec4 as V}from"three-shader-graph";import{prepareClassParameters as D,prepareShapeParameters as F}from"../../scene/materializer.js";import{SerializedParamType as Q}from"../../scene/model.js";import{ShapeLibrary as U}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as W,linearEyeDepth as L}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as q,particleTimeUniformName as H,particleUniforms as G,particleVelcoityUniformName as J}from"../../shader-nodes/particle.js";import{sampleFlipbook as O}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as N}from"./initializsers.js";import{DelayRate as K,OnceRate as X}from"./rates.js";import{StretchedSprite as Y}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as _,VfxInitializserLibrary as $}from"./vfx-defs.js";import{MultiRenderer as ee}from"./vfx-renderers.js";import{WorldCollisionBehaviour as te}from"./vfx-collision-behaviour.js";import{SpriteNodeShaderMaterial as ie}from"../../shader/sprite-shader.js";export async function materializeVfx(t,i,n,s,r,l){let c=i;for(;null!=c.parent;)c=c.parent;const m=new o;m.name="particle system local",i.add(m);const u=new o;u.name="particle system world",c.add(u);const p=new ee(u,m,a,s),h=new e;return(await Promise.all(t.vfx.emitters.map((async e=>{const t=await ne(e,n,h,r,l);return t.setParentRecursive(h),t.emit()})))).forEach((e=>h.addEmitter(e))),h.addRenderer(p).emit({onEnd:()=>{}}),{container:u,system:h,dispose:()=>{u.removeFromParent(),m.removeFromParent(),p.dispose()}}}async function ne(e,t,n,m,z){const D=function(e){let t;switch(e.rate.type){case"continuous":t=new K(e.rate.delay??0,e.rate.count,e.rate.time);break;case"once":t=new X(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new s(0,1/0)}return t}(e);let q;switch(e.output.type){case"sprite":q=new i(await async function(e,t,i){let n=null;n=null!=e.shader?await ae(e,t,i):await async function(e,t){const i=null!=e.texture?await t.getTexture(e.texture):se,n=B(i);let s=n.sample(k.uv);e.flipbook?.enabled&&(s=O(n,w.uv,e.flipbook.columns,e.flipbook.rows,G.time,e.flipbook.fps,e.flipbook.mode));const o=new u("rotation",0),r=new p("color").rgb,l=j("opacity",1),c=L.subtract(W).divide(L);let m=s.x.multiply(l);if("number"==typeof e.softness&&e.softness>0){const t=E(c,v(e.softness));m=m.multiply(t)}const h=x(d,{position:R.position,modelViewMatrix:C.modelViewMatrix,rotation:o},"\n vec2 center = vec2(0.5, 0.5);\n vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n // Using scale form instance matrix instead of modelMatrix\n vec2 scale;\n scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\n // This times 2 on scale seem to make it appear like when using regular sprites. \n // Not sure if this is correct though.\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * (scale);\n\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\n mvPosition.xy += rotatedPosition;\n return projectionMatrix * mvPosition;\n ");var f=new ie({color:P(r.multiplyScalar(e.intensity??1),m).multiply(s),transparent:!0,position:h,uniforms:{color:{value:new a.Color(e.color)}}});null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??a.NormalBlending,f}(e,t);const s=new a.Mesh(new a.PlaneGeometry(1,1),n);return s.name="sprite",s}(e.output,t,z));break;case"stretchedSprite":q=new i(await async function(e,t){const i=null!=e.texture?await t.getTexture(e.texture):se,n=B(i).sample(k.uv),s=V(new l("color")),o=s.rgb;let r=s.w;if("number"==typeof e.softness&&e.softness>0){const t=L.subtract(W).divide(b(L)),i=E(t,v(e.softness));r=I(r.multiply(i))}const c=x(d,{position:w.position,offset:y("offset"),modelViewMatrix:C.modelViewMatrix,velocity:g("velocity"),size:y("size"),rotation:f("rotation")},"\n float lengthFactor = velocity.w;\n float avgSize = (size.x + size.y) * 0.5;\n\n vec4 mvPosition = modelViewMatrix * vec4( offset , 1.0 );\n vec3 viewVelocity = normalMatrix * velocity.xyz;\n float vlength = length(viewVelocity); \n mvPosition.xyz += position.y * normalize(cross(mvPosition.xyz, viewVelocity)) * avgSize; \n mvPosition.xyz -= (position.x + 0.5) * viewVelocity * (1.0 + lengthFactor / vlength) * avgSize;\n return projectionMatrix * mvPosition;\n ");var m=new ie({color:P(o.multiplyScalar(e.intensity??1),r).multiply(n),transparent:!0,position:c,uniforms:{color:{value:new a.Color(e.color)}}});null!=m&&!0===e.bloom&&(m.userData.hasBloom=!0);m.blending=Z[e.blendingMode]??a.NormalBlending;const u=new Y(new a.PlaneGeometry(1,1),m);return u.scaleFactor=e.scale,u}(e.output,t));break;case"shape":q=new i(await async function(e,t,i){if(null==e.shape)return console.log("Shape is null"),new o;const n=U[e.shape];if(null==n)return console.error(`No shape with type ${e.shape}`),new o;const s=F(e.params??{}),l=n.geometry(s);let m=null;m=null!=e.shader?await ae(e,t,i):null!=e.material?function(e){const t=S(new h("instanceColor")).rgb;let i,n=S(new r("particleData")).x;if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshBasicMaterial){let s=t.multiply(M(e.color));null!=e.map&&(s=s.multiply(B(e.map).sample(k.uv).rgb)),null!=e.alphaMap&&(n=n.multiply(B(e.alphaMap).sample(k.uv).r)),e instanceof a.MeshStandardMaterial?i=new c({color:T({color:s,emissive:M(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof a.MeshLambertMaterial?i=new c({color:A({color:s}).rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof a.MeshBasicMaterial&&(i=new c({color:s.rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}))}null!=i&&(!0===e.userData?.hasBloom&&null!=i&&(i.userData.hasBloom=!0),i.side=e.side,i.transparent=e.transparent);return i??e}(await t.getMaterial(e.material)):function(){const e=S(new h("instanceColor")).rgb,t=S(new r("particleData")).x;return new c({color:A({color:e}).rgb.rgba(t),transparent:!0})}();null!=m&&!0===e.bloom&&(m.userData.hasBloom=!0);return new a.Mesh(l,m)}(e.output,t,z));break;case"mesh":q=new i(await async function(e,t,i){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new o;const n=await t.getMesh(e.assetId),s=await t.getAsset(e.assetId);if(null!=e.shader){const s=await ae(e,t,i);null!=s&&!0===e.bloom&&(s.userData.hasBloom=!0),n.traverse((e=>{e instanceof a.Mesh&&(e.material=s)}))}else{const e=[];if(null!=s.materialAssignments)for(const i of s.materialAssignments)n.traverse((n=>{n instanceof a.Mesh&&n.material instanceof a.Material&&n.material.color instanceof a.Color&&(n.material.name!=i.name&&null!=i.name||"#"+n.material.color.getHexString()!==i.color||e.push(t.getMaterial(i.materialId).then((e=>n.material=e))))}));await Promise.all(e)}const r=[];if(n.traverse((e=>{e instanceof a.Mesh&&r.push(e)})),1===r.length){const e=r[0];return e.updateWorldMatrix(!0,!0),e.updateMatrixWorld(),e.matrix.copy(e.matrixWorld),e.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.removeFromParent(),e}return n}(e.output,t,z));break;case"trail":q=new i({type:"trail",taper:e.output.taper,headGeometry:null,dragTexture:!1,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom});break;default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const H=new re;H.parent=n,H.setRate(D),H._space=e.output.space;const J=await Promise.all(e.initializers.filter((e=>null!=$[e.type])).map((async e=>{const t=$[e.type],i=await F(e.params??{});return t.build(i)})));J.push(q,new N),H.addInitializers(J);const ee=await Promise.all(e.behaviours.filter((e=>null!=_[e.type])).map((async e=>{const t=_[e.type];for(const[i,n]of Object.entries(e.params))t.parameters&&null!=t.parameters[i]&&"curve"===t.parameters[i].type&&n.type!==Q.Curve&&(n.type=Q.Curve);const i=await F(e.params??{});return t.build(i)})).sort(((e,t)=>e instanceof te?1:0)));ee.push(new oe);for(const e of ee)e instanceof te&&(e.physics=m);H.addBehaviours(ee);for(const i of e.children){const e=await ne(i,t,n,m,z),s=new EmitterPool((()=>{const t=e.clone();return t.onExpired=()=>{const e=H.childEmitters.findIndex((e=>e.id===t.id));-1!=e&&H.childEmitters.splice(e,1),s.release(t)},t})),a=H.eventDispatcher,o=new Map;H.bindEmitterEvent=!0,a.addEventListener("PARTICLE_DEAD",(e=>{const t=o.get(e.id);if(null!=t){const e=H.childEmitters.findIndex((e=>e.id===t.id));null!=e&&t.stopEmit()}}));let r="PARTICLE_CREATED";if("spawnEvent"in i)switch(i.spawnEvent){case"collision":r="PARTICLE_COLLISION";break;case"start":r="PARTICLE_CREATED"}a.addEventListener(r,(e=>{const t=s.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),H.childEmitters.push(t),o.set(e.id,t),t.parentParticle=e,t.system=H.system,t.emit()}))}return H}const se=(new a.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");async function ae(e,t,i){const n=i.get(e.shader);if(null==n)return console.error("No shader exists with name "+e.shader),new a.Material;const s=new n.type,o=await D(e.shaderParams,n.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0);return Object.assign(s,o),s.build()}class oe extends t{initialize(e){e.body instanceof a.Object3D&&e.body.traverse((e=>{if(e instanceof a.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[q]||null!=t.uniforms[H]||t.uniforms[J])}}))}mutate(e,t,i){this.energize(e,t),e.target instanceof o&&e.target.traverse((t=>{if(t instanceof a.Mesh){const i=t.material;i instanceof c&&(null!=i.uniforms[q]&&(i.uniforms[q].value=this.energy),null!=i.uniforms[H]&&(i.uniforms[H].value=e.age),null!=i.uniforms[J]&&(i.uniforms[J].value=e.velocity))}}))}}class re extends n{constructor(){super(...arguments),this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}update(e){if(!this.isEmitting&&0===this.particles.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle?t.position.copy(t.parentParticle.position):t.setPosition(this.position),t.update(e)}clone(){const e=new re;return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach((t=>t.setParentRecursive(e)))}}export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
|
1
|
+
import e,{Behaviour as t,Body as i,Emitter as s,Rate as n}from"@hology/nebula";import*as a from"three";import{Object3D as o}from"three";import{AttributeVec3Node as r,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as m,UniformFloatNode as u,UniformVec3Node as p,Vec3ExpressionNode as h,Vec4Node as d,attributeFloat as f,attributeVec3 as y,attributeVec4 as g,attributes as w,float as v,glslFunction as x,lambertMaterial as A,log as b,pow as E,rgb as M,rgba as P,saturate as I,standardMaterial as T,textureSampler2d as B,transformed as R,uniformFloat as j,uniforms as C,varying as S,varyingAttributes as k,varyingVec3 as z,varyingVec4 as V}from"three-shader-graph";import{prepareClassParameters as D,prepareShapeParameters as F}from"../../scene/materializer.js";import{SerializedParamType as Q}from"../../scene/model.js";import{ShapeLibrary as U}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as W,linearEyeDepth as L}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as q,particleTimeUniformName as H,particleUniforms as G,particleVelcoityUniformName as J}from"../../shader-nodes/particle.js";import{sampleFlipbook as O}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as N}from"./initializsers.js";import{DelayRate as K,OnceRate as X}from"./rates.js";import{StretchedSprite as Y}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as _,VfxInitializserLibrary as $}from"./vfx-defs.js";import{MultiRenderer as ee}from"./vfx-renderers.js";import{WorldCollisionBehaviour as te}from"./vfx-collision-behaviour.js";import{SpriteNodeShaderMaterial as ie}from"../../shader/sprite-shader.js";export async function materializeVfx(t,i,s,n,r,l){let c=i;for(;null!=c.parent;)c=c.parent;const m=new o;m.name="particle system local",i.add(m);const u=new o;u.name="particle system world",c.add(u);const p=new ee(u,m,a,n),h=new e;return(await Promise.all(t.vfx.emitters.map((async e=>{const t=await se(e,s,h,r,l);return t.setParentRecursive(h),t.emit()})))).forEach((e=>h.addEmitter(e))),h.addRenderer(p).emit({onEnd:()=>{}}),{container:u,system:h,dispose:()=>{u.removeFromParent(),m.removeFromParent(),p.dispose()}}}async function se(e,t,s,m,z){const D=function(e){let t;switch(e.rate.type){case"continuous":t=new K(e.rate.delay??0,e.rate.count,e.rate.time);break;case"once":t=new X(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new n(0,1/0)}return t}(e);let q;switch(e.output.type){case"sprite":q=new i(await async function(e,t,i){let s=null;s=null!=e.shader?await ae(e,t,i):await async function(e,t){const i=null!=e.texture?await t.getTexture(e.texture):ne,s=B(i);let n=s.sample(k.uv);e.flipbook?.enabled&&(n=O(s,w.uv,e.flipbook.columns,e.flipbook.rows,G.time,e.flipbook.fps,e.flipbook.mode));const o=new u("rotation",0),r=new p("color").rgb,l=j("opacity",1),c=L.subtract(W).divide(L);let m=n.x.multiply(l);if("number"==typeof e.softness&&e.softness>0){const t=E(c,v(e.softness));m=m.multiply(t)}const h=x(d,{position:R.position,modelViewMatrix:C.modelViewMatrix,rotation:o},"\n vec2 center = vec2(0.5, 0.5);\n vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n // Using scale form instance matrix instead of modelMatrix\n vec2 scale;\n scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\n // This times 2 on scale seem to make it appear like when using regular sprites. \n // Not sure if this is correct though.\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * (scale);\n\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\n mvPosition.xy += rotatedPosition;\n return projectionMatrix * mvPosition;\n ");var f=new ie({color:P(r.multiplyScalar(e.intensity??1),m).multiply(n),transparent:!0,position:h,uniforms:{color:{value:new a.Color(e.color)}}});null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??a.NormalBlending,f}(e,t);const n=new a.Mesh(new a.PlaneGeometry(1,1),s);return n.name="sprite",n}(e.output,t,z));break;case"stretchedSprite":q=new i(await async function(e,t){const i=null!=e.texture?await t.getTexture(e.texture):ne,s=B(i).sample(k.uv),n=V(new l("color")),o=n.rgb;let r=n.w;if("number"==typeof e.softness&&e.softness>0){const t=L.subtract(W).divide(b(L)),i=E(t,v(e.softness));r=I(r.multiply(i))}const c=x(d,{position:w.position,offset:y("offset"),modelViewMatrix:C.modelViewMatrix,velocity:g("velocity"),size:y("size"),rotation:f("rotation")},"\n float lengthFactor = velocity.w;\n float avgSize = (size.x + size.y) * 0.5;\n\n vec4 mvPosition = modelViewMatrix * vec4( offset , 1.0 );\n vec3 viewVelocity = normalMatrix * velocity.xyz;\n float vlength = length(viewVelocity); \n mvPosition.xyz += position.y * normalize(cross(mvPosition.xyz, viewVelocity)) * avgSize; \n mvPosition.xyz -= (position.x + 0.5) * viewVelocity * (1.0 + lengthFactor / vlength) * avgSize;\n return projectionMatrix * mvPosition;\n ");var m=new ie({color:P(o.multiplyScalar(e.intensity??1),r).multiply(s),transparent:!0,position:c,uniforms:{color:{value:new a.Color(e.color)}}});null!=m&&!0===e.bloom&&(m.userData.hasBloom=!0);m.blending=Z[e.blendingMode]??a.NormalBlending;const u=new Y(new a.PlaneGeometry(1,1),m);return u.scaleFactor=e.scale,u}(e.output,t));break;case"shape":q=new i(await async function(e,t,i){if(null==e.shape)return console.log("Shape is null"),new o;const s=U[e.shape];if(null==s)return console.error(`No shape with type ${e.shape}`),new o;const n=F(e.params??{}),l=s.geometry(n);let m=null;m=null!=e.shader?await ae(e,t,i):null!=e.material?function(e){const t=S(new h("instanceColor")).rgb;let i,s=S(new r("particleData")).x;if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshBasicMaterial){let n=t.multiply(M(e.color));null!=e.map&&(n=n.multiply(B(e.map).sample(k.uv).rgb)),null!=e.alphaMap&&(s=s.multiply(B(e.alphaMap).sample(k.uv).r)),e instanceof a.MeshStandardMaterial?i=new c({color:T({color:n,emissive:M(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(s),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof a.MeshLambertMaterial?i=new c({color:A({color:n}).rgb.rgba(s),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof a.MeshBasicMaterial&&(i=new c({color:n.rgb.rgba(s),transparent:e.transparent,alphaTest:e.alphaTest}))}null!=i&&(!0===e.userData?.hasBloom&&null!=i&&(i.userData.hasBloom=!0),i.side=e.side,i.transparent=e.transparent);return i??e}(await t.getMaterial(e.material)):function(){const e=S(new h("instanceColor")).rgb,t=S(new r("particleData")).x;return new c({color:A({color:e}).rgb.rgba(t),transparent:!0})}();null!=m&&!0===e.bloom&&(m.userData.hasBloom=!0);return new a.Mesh(l,m)}(e.output,t,z));break;case"mesh":q=new i(await async function(e,t,i){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new o;const s=await t.getMesh(e.assetId),n=await t.getAsset(e.assetId);if(null!=e.shader){const n=await ae(e,t,i);null!=n&&!0===e.bloom&&(n.userData.hasBloom=!0),s.traverse((e=>{e instanceof a.Mesh&&(e.material=n)}))}else{const e=[];if(null!=n.materialAssignments)for(const i of n.materialAssignments)s.traverse((s=>{s instanceof a.Mesh&&s.material instanceof a.Material&&s.material.color instanceof a.Color&&(s.material.name!=i.name&&null!=i.name||"#"+s.material.color.getHexString()!==i.color||e.push(t.getMaterial(i.materialId).then((e=>s.material=e))))}));await Promise.all(e)}const r=[];if(s.traverse((e=>{e instanceof a.Mesh&&r.push(e)})),1===r.length){const e=r[0];return e.updateWorldMatrix(!0,!0),e.updateMatrixWorld(),e.matrix.copy(e.matrixWorld),e.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.removeFromParent(),e}return s}(e.output,t,z));break;case"trail":q=new i({type:"trail",taper:e.output.taper,headGeometry:null,dragTexture:!1,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom});break;default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const H=new re;H.parent=s,H.setRate(D),H._space=e.output.space;const J=await Promise.all(e.initializers.filter((e=>null!=$[e.type])).map((async e=>{const t=$[e.type],i=await F(e.params??{});return t.build(i)})));J.push(q,new N),H.addInitializers(J);const ee=await Promise.all(e.behaviours.filter((e=>null!=_[e.type])).map((async e=>{const t=_[e.type];for(const[i,s]of Object.entries(e.params))t.parameters&&null!=t.parameters[i]&&"curve"===t.parameters[i].type&&s.type!==Q.Curve&&(s.type=Q.Curve);const i=await F(e.params??{});return t.build(i)})).sort(((e,t)=>e instanceof te?1:0)));ee.push(new oe);for(const e of ee)e instanceof te&&(e.physics=m);H.addBehaviours(ee);for(const i of e.children){const e=await se(i,t,s,m,z),n=new EmitterPool((()=>{const t=e.clone();return t.onExpired=()=>{const e=H.childEmitters.findIndex((e=>e.id===t.id));-1!=e&&H.childEmitters.splice(e,1),n.release(t)},t})),a=H.eventDispatcher,o=new Map;H.bindEmitterEvent=!0,a.addEventListener("PARTICLE_DEAD",(e=>{const t=o.get(e.id);if(null!=t){const e=H.childEmitters.findIndex((e=>e.id===t.id));null!=e&&(t.stopEmit(),H.childEmitters.splice(e,1))}}));let r="PARTICLE_CREATED";if("spawnEvent"in i)switch(i.spawnEvent){case"collision":r="PARTICLE_COLLISION";break;case"start":r="PARTICLE_CREATED"}a.addEventListener(r,(e=>{const t=n.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),H.childEmitters.push(t),o.set(e.id,t),t.parentParticle=e,t.system=H.system,t.emit()}))}return H}const ne=(new a.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");async function ae(e,t,i){const s=i.get(e.shader);if(null==s)return console.error("No shader exists with name "+e.shader),new a.Material;const n=new s.type,o=await D(e.shaderParams,s.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0);return Object.assign(n,o),n.build()}class oe extends t{initialize(e){e.body instanceof a.Object3D&&e.body.traverse((e=>{if(e instanceof a.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[q]||null!=t.uniforms[H]||t.uniforms[J])}}))}mutate(e,t,i){this.energize(e,t),e.target instanceof o&&e.target.traverse((t=>{if(t instanceof a.Mesh){const i=t.material;i instanceof c&&(null!=i.uniforms[q]&&(i.uniforms[q].value=this.energy),null!=i.uniforms[H]&&(i.uniforms[H].value=e.age),null!=i.uniforms[J]&&(i.uniforms[J].value=e.velocity))}}))}}class re extends s{constructor(){super(...arguments),this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}update(e){if(!this.isEmitting&&0===this.particles.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle?t.position.copy(t.parentParticle.position):t.setPosition(this.position),t.update(e)}clone(){const e=new re;return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach((t=>t.setParentRecursive(e)))}}export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"vfx-renderers.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/vfx-renderers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAQ,QAAQ,EAA4B,MAAM,gBAAgB,CAAA;AACvG,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,
|
1
|
+
{"version":3,"file":"vfx-renderers.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/vfx-renderers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAQ,QAAQ,EAA4B,MAAM,gBAAgB,CAAA;AACvG,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAA2B,QAAQ,EAAc,MAAM,OAAO,CAAC;AAEtE,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAU/C,qBAAa,aAAc,SAAQ,cAAc;IAInC,OAAO,CAAC,cAAc;IAAY,OAAO,CAAC,cAAc;IAAY,OAAO,CAAC,KAAK;IAAgB,OAAO,CAAC,IAAI;IAHzH,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAAK;gBAEP,cAAc,EAAE,QAAQ,EAAU,cAAc,EAAE,QAAQ,EAAU,KAAK,EAAE,OAAO,KAAK,EAAU,IAAI,EAAE,cAAc;IAMzI,cAAc;IASd,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI;IAI3C,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI;IAI1C,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI;IAOxC,OAAO,CAAC,WAAW;IAwDnB,OAAO;CAYR;AAED,MAAM,MAAM,gBAAgB,GAAG,aAAa,CAAA;AAE5C,MAAM,MAAM,aAAa,GAAG;IAC1B,IAAI,EAAE,OAAO,CAA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EAAE,QAAQ,GAAG;QAAC,IAAI,CAAC,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAC;IAmFlF,gBAAgB,CAAC,QAAQ,KAAA;IAIzB,cAAc,CAAC,QAAQ,KAAA;CAcxB;AAOD,KAAK,iBAAiB,GAAG;IAAC,IAAI,EAAE,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAC;IAAC,SAAS,EAAE,QAAQ,EAAE,CAAA;CAAC,CAAA;AAEpI,qBAAa,iBAAkB,SAAQ,YAAY;IAEW,OAAO,CAAC,IAAI;gBAA5D,SAAS,EAAE,KAAK,CAAC,QAAQ,EAAE,KAAK,EAAE,OAAO,KAAK,EAAU,IAAI,EAAE,cAAc;IAGxF,OAAO;IAIP,cAAc;IAUd,OAAO,CAAC,MAAM,CAA0B;IAExC,OAAO,CAAC,YAAY;IAWpB,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,GAAG;QAAC,IAAI,CAAC,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAC;IAsElF,gBAAgB,CAAC,QAAQ,KAAA;IAuCzB,cAAc,CAAC,QAAQ,KAAA;CAiBxB;AAgDD;;;;;GAKG;AACH,iBAAS,2BAA2B,CAAC,IAAI,EAAE,iBAAiB,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAqExF;AAED,OAAO,EAAE,2BAA2B,EAAE,CAAA"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{CustomRenderer as e,MeshRenderer as t,PUID as r}from"@hology/nebula";import*as a from"three";import{InstancedBufferAttribute as s,Object3D as i}from"three";import{NodeShaderMaterial as n}from"three-shader-graph";import{StretchedSprite as o}from"./stretched-sprite.js";import{Trail as l}from"./trail-renderer.js";import{SpriteNodeShaderMaterial as c}from"../../shader/sprite-shader";var d;!function(e){e[e.mesh=0]="mesh",e[e.instanced=1]="instanced",e[e.sprite=2]="sprite",e[e.stretchedBillboard=3]="stretchedBillboard",e[e.trail=4]="trail"}(d||(d={}));export class MultiRenderer extends e{constructor(e,t,r,a){super(),this.worldContainer=e,this.localContainer=t,this.three=r,this.view=a,this.localRenderers=[],this.worldRenderers=[]}onSystemUpdate(){for(const e of this.worldRenderers)e?.onSystemUpdate();for(const e of this.localRenderers)e?.onSystemUpdate()}onParticleCreated(e){this.getRenderer(e)?.onParticleCreated(e)}onParticleUpdate(e){this.getRenderer(e)?.onParticleUpdate(e)}onParticleDead(e){this.getRenderer(e)?.onParticleDead(e),e._renderer=null}getRenderer(e){if(e._renderer)return e._renderer;const t=(null!=e?.parent?e?.parent._space:null)??"world",r="world"===t?this.worldContainer:this.localContainer,s="world"===t?this.worldRenderers:this.localRenderers;return"trail"===e.body.type?(null==s[d.trail]&&(s[d.trail]=new TrailRenderer(r,this.three)),e._renderer=s[d.trail]):e.body instanceof o?(null==s[d.stretchedBillboard]&&(s[d.stretchedBillboard]=new StretchedSpriteInstancedRenderer(r,this.three,this.view)),e._renderer=s[d.stretchedBillboard]):e.body instanceof a.Sprite||e.body instanceof a.Mesh&&"sprite"===e.body.name?(null==s[d.sprite]&&(s[d.sprite]=new CombinedRenderer(r,this.three)),e._renderer=s[d.sprite]):e.body instanceof a.Mesh&&0==e.body.children.length&&e.body.material instanceof n?(null==s[d.instanced]&&(s[d.instanced]=new InstancedRenderer(r,this.three,this.view)),e._renderer=s[d.instanced]):e.body instanceof a.Object3D?(null==s[d.mesh]&&(s[d.mesh]=new CombinedRenderer(r,this.three)),e._renderer=s[d.mesh]):void 0}dispose(){this.localRenderers.forEach((e=>{e instanceof InstancedRenderer&&e.dispose()})),this.worldRenderers.forEach((e=>{e instanceof InstancedRenderer&&e.dispose()}))}}export class TrailRenderer extends t{constructor(){super(...arguments),this.trails=[]}dispose(){}onSystemUpdate(){for(const e of this.trails)e.update()}onParticleCreated(e){const t=e.body,r=new l(this.container,!0),s=new i,n=l.createBaseMaterial();n.uniforms.taper.value=t.taper??!1;const o=new a.Color(t.color??0).multiplyScalar(t.intensity),c=new a.Color(t.colorEnd??0).multiplyScalar(t.intensity);n.uniforms.headColor.value.set(o.r,o.g,o.b,t.opacityStart??1),n.uniforms.tailColor.value.set(c.r,c.g,c.b,t.opacityEnd??1),t.bloom&&(n.userData.hasBloom=!0),r.initialize(n,Math.round(t.length??10),!1,0,null,s);const d=e.rotation;s.rotation.set(d.x,d.y,d.z);e.scale;r.activate(),this.trails.push(r),e.target=s}onParticleUpdate(e){const t=e.target;t.position.copy(e.position);e.velocity.clone().normalize();const r=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=r){const t=this.trails[r];if(e.useAlpha){t.material.uniforms.headColor.value.setW(e.alpha);t.material.uniforms.tailColor.value.setW(e.alpha)}}}onParticleDead(e){const t=e.target,r=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=r){const e=this.trails[r];e.removeFromParent(),e.mesh.removeFromParent(),t.removeFromParent(),this.trails.splice(r,1)}}}export class CombinedRenderer extends t{dispose(){}scale(e){const t=e.transform.initialScale;e.target instanceof a.Sprite?null!=t?e.target.scale.set(t.x*e.scale*e.radius,t.y*e.scale*e.radius,1):e.target.scale.set(e.scale*e.radius,e.scale*e.radius,1):null!=t?e.target.scale.set(t.x*e.scale,t.y*e.scale,t.z*e.scale):super.scale(e)}rotate(e){e.target.material.rotation=e.rotation.z}onParticleCreated(e){e.target||(e.target=this._targetPool.get(e.body),(e.useAlpha||e.useColor)&&(e.target instanceof a.Mesh||e.target instanceof a.Sprite&&e.target.material instanceof a.Material)&&(e.target.material.__puid=r.id(e.body.material),e.target.material=this._materialPool.get(e.target.material))),e.target&&e.target instanceof i&&(e.target.position.set(e.position.x,e.position.y,e.position.z),this.container.add(e.target))}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:s,rotation:n}=e;if(t){if(t.position.copy(e.position),this.isThreeSprite(e)||(t instanceof a.Mesh&&t.material instanceof c?e.target.material.rotation=e.rotation.z:t.rotation.set(n.x,n.y,n.z)),this.scale(e),e.transform&&e.transform.orientAlongVelocity&&t instanceof i){const r=m.set(e.velocity.x,e.velocity.y,e.velocity.z).normalize(),a=t.getWorldDirection(h);a.applyAxisAngle(p,Math.PI/-2),u.setFromUnitVectors(a,r),t.quaternion.copy(u)}t.material instanceof a.Material&&(r&&(t.material instanceof c&&null!=t.material.uniforms.opacity&&(t.material.uniforms.opacity.value=e.alpha,t.material.uniformsNeedUpdate=!0),t.material.opacity=e.alpha,t.material.transparent=!0),s&&(null!=t.material.color?t.material.color.copy(e.color):t.material instanceof a.ShaderMaterial&&null!=t.material.uniforms.color&&(t.material.uniforms.color.value=e.color,t.material.uniformsNeedUpdate=!0)))}}onParticleDead(e){e.target&&(e.target.material&&(e.useAlpha||e.useColor)&&this._materialPool.expire(e.target.material),this._targetPool.expire(e.target),this.container.remove(e.target),e.target=null)}}export class StretchedSpriteInstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach((e=>e.mesh.geometry.dispose()))}onSystemUpdate(){for(const e of this.meshes){const t=e.mesh.geometry.getAttribute("offset"),r=e.mesh.geometry.getAttribute("size"),s=e.mesh.geometry.getAttribute("velocity"),i=e.mesh.geometry.getAttribute("rotation"),n=e.mesh.geometry.getAttribute("color");let o=0;for(const l of e.particles){if(null==l||l.dead)continue;if(l.useColor||l.color instanceof a.Color){const e=U.copy(l.color).getRGB(C);n.setXYZW(o,e.r,e.g,e.b,1),n.needsUpdate=!0}l.useAlpha&&(n.setW(o,l.alpha),n.needsUpdate=!0),"number"==typeof l.rotation?i.setX(o,l.rotation):i.setX(o,l.rotation.x);const e=l.position;if(t.setXYZ(o,e.x,e.y,e.z),"number"!=typeof l.scale)throw new Error("Particle scale is not a number");r.setXYZ(o,l.scale,l.scale,l.scale);let c=l.body.scaleFactor;0===c&&(c=.001);const d=1,m=l.velocity;s.setXYZW(o,m.x*c,m.y*c,m.z*c,d),o++}o>0&&(t.clearUpdateRanges(),t.addUpdateRange(0,3*o),t.needsUpdate=!0,r.clearUpdateRanges(),r.addUpdateRange(0,3*o),r.needsUpdate=!0,n.clearUpdateRanges(),n.addUpdateRange(0,4*o),n.needsUpdate=!0,s.clearUpdateRanges(),s.addUpdateRange(0,4*o),s.needsUpdate=!0,i.clearUpdateRanges(),i.addUpdateRange(0,o),i.needsUpdate=!0)}}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate;return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(e.body instanceof o&&null==e.target){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(null==r){const i=this.calcMaxCount(e),n=new a.InstancedBufferGeometry;n.setIndex(t.geometry.getIndex()),n.setAttribute("position",t.geometry.getAttribute("position")),t.geometry.hasAttribute("normal")&&n.setAttribute("normal",t.geometry.getAttribute("normal")),n.setAttribute("uv",t.geometry.getAttribute("uv"));const o=new s(new Float32Array(3*i),3);o.setUsage(a.DynamicDrawUsage),n.setAttribute("offset",o);const l=new s(new Float32Array(4*i),4);if(l.setUsage(a.DynamicDrawUsage),n.setAttribute("color",l),t.material instanceof c){const e=new a.Color(t.material.color);for(let t=0;t<l.count;t++)l.setXYZW(t,e.r,e.g,e.b,1)}const d=new s(new Float32Array(3*i),3);d.setUsage(a.DynamicDrawUsage),n.setAttribute("size",d);const m=new s(new Float32Array(4*i),4);m.setUsage(a.DynamicDrawUsage),n.setAttribute("velocity",m);const h=new s(new Float32Array(4*i),1);h.setUsage(a.DynamicDrawUsage),n.setAttribute("rotation",h),r={mesh:new a.Mesh(n,t.material),indices:new Float32Array(i),particles:[]},this.meshes.push(r),this.container.add(r.mesh)}let i=r.indices.findIndex((e=>0===e));i<0&&(i=function(e){let t=e[0],r=0;for(let a=1;a<e.length;a++)e[a]<t&&(t=e[a],r=a);return r}(r.indices)),r.indices[i]=performance.now(),e.target=i,r.particles[i]=e}}onParticleUpdate(e){}onParticleDead(e){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(r){const t=r.mesh.geometry.getAttribute("size");t.setXYZ(e.target,0,0,0),t.needsUpdate=!0,r.particles[e.target]=null,r.indices[e.target]=0}e.target=null}}const m=new a.Vector3,h=new a.Vector3,u=new a.Quaternion,p=new a.Vector3(1,0,0);export class InstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach((e=>e.mesh.dispose()))}onSystemUpdate(){for(const e of this.meshes);}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate;return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(!(e.body instanceof a.Sprite)){if(null==e.target){const t=e.body;let r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));if(null==r){const s=this.calcMaxCount(e);r={mesh:new a.InstancedMesh(t.geometry,t.material,s),indices:new Array(s).fill(null),particles:[]},r.mesh.setColorAt(0,U.setScalar(1)),r.mesh.instanceColor.needsUpdate=!0,r.mesh.material.defines.USE_INSTANCING="";const i=new Float32Array(3*s);y.makeScale(0,0,0);for(let e=0;e<s;e++)i[3*e+0]=1,i[3*e+1]=1,r.mesh.setMatrixAt(e,y);r.mesh.instanceMatrix.needsUpdate=!0,r.mesh.geometry.setAttribute("particleData",new a.InstancedBufferAttribute(i,3)),this.meshes.push(r),this.container.add(r.mesh)}let s=r.indices.findIndex((e=>null==e));s<0&&(s=r.indices.indexOf(Math.min(...r.indices))),r.indices[s]=performance.now(),e.target=s,r.particles[s]=e}if("number"==typeof e.target){e.transform.initialScale;const t=e.body;let r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));f(e,r.mesh),e.useAlpha&&(r.mesh.material.transparent=!0)}}}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:a,rotation:s}=e;if(null==t)return;const i=e.body,n=this.meshes.find((e=>e.mesh.geometry.uuid===i.geometry.uuid&&e.mesh.material.uuid===i.material.uuid));if(null==n)return;f(e,n.mesh),a&&(n.mesh.setColorAt(e.target,U.copy(e.color)),n.mesh.instanceColor.needsUpdate=!0);const o=n.mesh.geometry.getAttribute("particleData");r&&o.setX(e.target,e.alpha),o.setY(e.target,e.energy),o.needsUpdate=!0}onParticleDead(e){if(null!=e.target){const t=e.body,r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));if(null==r)return;r.indices[e.target]=null,e.scale=0,f(e,r.mesh),r.mesh.instanceMatrix.needsUpdate=!0,e.target=null}}}const g=new i;function f(e,t){if(w.set(e.position.x,e.position.y,e.position.z),e.transform&&e.transform.orientAlongVelocity){const r=m.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize();t.getMatrixAt(e.target,g.matrix);const a=g.getWorldDirection(x);a.applyAxisAngle(p,Math.PI/-2),b.setFromUnitVectors(a,r)}else A.set(e.rotation.x,e.rotation.y,e.rotation.z),b.setFromEuler(A);const r=e.transform.initialScale;null!=r?x.set(r.x*e.scale,r.y*e.scale,r.z*e.scale):x.set(e.scale,e.scale,e.scale),y.compose(w,b,x),t.setMatrixAt(e.target,y),t.instanceMatrix.needsUpdate=!0}const y=new a.Matrix4,b=new a.Quaternion,w=new a.Vector3,x=new a.Vector3,A=new a.Euler,U=new a.Color(0),C={r:0,g:0,b:0};function M(e,t){const r=e.mesh,s=r.count,i=[],n=r.geometry.getAttribute("particleData"),o=new a.Vector3;for(let l=0;l<s;l++){const s=new a.Matrix4,c=new a.Color;r.getMatrixAt(l,s),r.getColorAt(l,c);const d=n.getX(l);o.setFromMatrixPosition(s);const m=o.distanceTo(t.position);i.push({index:l,distance:m,matrix:s,particle:e.particles[l],color:c,pdx:d})}i.sort(((e,t)=>t.distance-e.distance));for(let e=0;e<s;e++){const t=i[e].matrix;null==i[e].particle&&t.makeScale(0,0,0),r.setMatrixAt(e,t),r.setColorAt(e,i[e].color),n.setX(e,i[e].pdx)}r.instanceMatrix.needsUpdate=!0}export{M as sortInstancedMeshByDistance};/*
|
1
|
+
import{CustomRenderer as e,MeshRenderer as t,PUID as r}from"@hology/nebula";import*as a from"three";import{InstancedBufferAttribute as i,Object3D as s}from"three";import{NodeShaderMaterial as o}from"three-shader-graph";import{StretchedSprite as n}from"./stretched-sprite.js";import{Trail as l}from"./trail-renderer.js";import{SpriteNodeShaderMaterial as c}from"../../shader/sprite-shader";var d;!function(e){e[e.mesh=0]="mesh",e[e.instanced=1]="instanced",e[e.sprite=2]="sprite",e[e.stretchedBillboard=3]="stretchedBillboard",e[e.trail=4]="trail"}(d||(d={}));export class MultiRenderer extends e{constructor(e,t,r,a){super(),this.worldContainer=e,this.localContainer=t,this.three=r,this.view=a,this.localRenderers=[],this.worldRenderers=[]}onSystemUpdate(){for(const e of this.worldRenderers)e?.onSystemUpdate();for(const e of this.localRenderers)e?.onSystemUpdate()}onParticleCreated(e){this.getRenderer(e)?.onParticleCreated(e)}onParticleUpdate(e){this.getRenderer(e)?.onParticleUpdate(e)}onParticleDead(e){this.getRenderer(e)?.onParticleDead(e),e._renderer=null}getRenderer(e){if(e._renderer)return e._renderer;const t=(null!=e?.parent?e?.parent._space:null)??"world",r="world"===t?this.worldContainer:this.localContainer,i="world"===t?this.worldRenderers:this.localRenderers;return"trail"===e.body.type?(null==i[d.trail]&&(i[d.trail]=new TrailRenderer(r,this.three)),e._renderer=i[d.trail]):e.body instanceof n?(null==i[d.stretchedBillboard]&&(i[d.stretchedBillboard]=new StretchedSpriteInstancedRenderer(r,this.three,this.view)),e._renderer=i[d.stretchedBillboard]):e.body instanceof a.Sprite||e.body instanceof a.Mesh&&"sprite"===e.body.name?(null==i[d.sprite]&&(i[d.sprite]=new CombinedRenderer(r,this.three)),e._renderer=i[d.sprite]):e.body instanceof a.Mesh&&0==e.body.children.length&&e.body.material instanceof o?(null==i[d.instanced]&&(i[d.instanced]=new InstancedRenderer(r,this.three,this.view)),e._renderer=i[d.instanced]):e.body instanceof a.Object3D?(null==i[d.mesh]&&(i[d.mesh]=new CombinedRenderer(r,this.three)),e._renderer=i[d.mesh]):void 0}dispose(){this.localRenderers.forEach((e=>{e instanceof InstancedRenderer&&e.dispose()})),this.worldRenderers.forEach((e=>{e instanceof InstancedRenderer&&e.dispose()}))}}export class TrailRenderer extends t{constructor(){super(...arguments),this.trails=[]}dispose(){}onSystemUpdate(){for(const e of this.trails)e.update()}onParticleCreated(e){const t=e.body,r=new l(this.container,!0),i=new s,o=l.createBaseMaterial();o.uniforms.taper.value=t.taper??!1;const n=new a.Color(t.color??0).multiplyScalar(t.intensity),c=new a.Color(t.colorEnd??0).multiplyScalar(t.intensity);o.uniforms.headColor.value.set(n.r,n.g,n.b,t.opacityStart??1),o.uniforms.tailColor.value.set(c.r,c.g,c.b,t.opacityEnd??1),t.bloom&&(o.userData.hasBloom=!0),r.initialize(o,Math.round(t.length??10),!1,0,null,i);const d=e.rotation;i.rotation.set(d.x,d.y,d.z);e.scale;r.activate(),this.trails.push(r),e.target=i}onParticleUpdate(e){const t=e.target;t.position.copy(e.position);let r=x;e.old&&e.old.position?r.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize():r.copy(e.velocity).normalize();const a=w;a.setFromUnitVectors(r,y),t.rotation.set(0,0,0),t.applyQuaternion(a);const i=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=i){const t=this.trails[i];if(e.useAlpha){t.material.uniforms.headColor.value.setW(e.alpha);t.material.uniforms.tailColor.value.setW(e.alpha)}}}onParticleDead(e){const t=e.target,r=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=r){const e=this.trails[r];e.removeFromParent(),e.mesh.removeFromParent(),t.removeFromParent(),this.trails.splice(r,1)}}}export class CombinedRenderer extends t{dispose(){}scale(e){const t=e.transform.initialScale;e.target instanceof a.Sprite?null!=t?e.target.scale.set(t.x*e.scale*e.radius,t.y*e.scale*e.radius,1):e.target.scale.set(e.scale*e.radius,e.scale*e.radius,1):null!=t?e.target.scale.set(t.x*e.scale,t.y*e.scale,t.z*e.scale):super.scale(e)}rotate(e){e.target.material.rotation=e.rotation.z}onParticleCreated(e){e.target||(e.target=this._targetPool.get(e.body),(e.useAlpha||e.useColor)&&(e.target instanceof a.Mesh||e.target instanceof a.Sprite&&e.target.material instanceof a.Material)&&(e.target.material.__puid=r.id(e.body.material),e.target.material=this._materialPool.get(e.target.material))),e.target&&e.target instanceof s&&(e.target.position.set(e.position.x,e.position.y,e.position.z),this.container.add(e.target))}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:i,rotation:o}=e;if(t){if(t.position.copy(e.position),this.isThreeSprite(e)||(t instanceof a.Mesh&&t.material instanceof c?e.target.material.rotation=e.rotation.z:t.rotation.set(o.x,o.y,o.z)),this.scale(e),e.transform&&e.transform.orientAlongVelocity&&t instanceof s){const r=m.set(e.velocity.x,e.velocity.y,e.velocity.z).normalize(),a=t.getWorldDirection(h);a.applyAxisAngle(p,Math.PI/-2),u.setFromUnitVectors(a,r),t.quaternion.copy(u)}t.material instanceof a.Material&&(r&&(t.material instanceof c&&null!=t.material.uniforms.opacity&&(t.material.uniforms.opacity.value=e.alpha,t.material.uniformsNeedUpdate=!0),t.material.opacity=e.alpha,t.material.transparent=!0),i&&(null!=t.material.color?t.material.color.copy(e.color):t.material instanceof a.ShaderMaterial&&null!=t.material.uniforms.color&&(t.material.uniforms.color.value=e.color,t.material.uniformsNeedUpdate=!0)))}}onParticleDead(e){e.target&&(e.target.material&&(e.useAlpha||e.useColor)&&this._materialPool.expire(e.target.material),this._targetPool.expire(e.target),this.container.remove(e.target),e.target=null)}}export class StretchedSpriteInstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach((e=>e.mesh.geometry.dispose()))}onSystemUpdate(){for(const e of this.meshes){const t=e.mesh.geometry.getAttribute("offset"),r=e.mesh.geometry.getAttribute("size"),i=e.mesh.geometry.getAttribute("velocity"),s=e.mesh.geometry.getAttribute("rotation"),o=e.mesh.geometry.getAttribute("color");let n=0;for(const l of e.particles){if(null==l||l.dead)continue;if(l.useColor||l.color instanceof a.Color){const e=C.copy(l.color).getRGB(M);o.setXYZW(n,e.r,e.g,e.b,1),o.needsUpdate=!0}l.useAlpha&&(o.setW(n,l.alpha),o.needsUpdate=!0),"number"==typeof l.rotation?s.setX(n,l.rotation):s.setX(n,l.rotation.x);const e=l.position;if(t.setXYZ(n,e.x,e.y,e.z),"number"!=typeof l.scale)throw new Error("Particle scale is not a number");r.setXYZ(n,l.scale,l.scale,l.scale);let c=l.body.scaleFactor;0===c&&(c=.001);const d=1,m=l.velocity;i.setXYZW(n,m.x*c,m.y*c,m.z*c,d),n++}n>0&&(t.clearUpdateRanges(),t.addUpdateRange(0,3*n),t.needsUpdate=!0,r.clearUpdateRanges(),r.addUpdateRange(0,3*n),r.needsUpdate=!0,o.clearUpdateRanges(),o.addUpdateRange(0,4*n),o.needsUpdate=!0,i.clearUpdateRanges(),i.addUpdateRange(0,4*n),i.needsUpdate=!0,s.clearUpdateRanges(),s.addUpdateRange(0,n),s.needsUpdate=!0)}}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate;return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(e.body instanceof n&&null==e.target){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(null==r){const s=this.calcMaxCount(e),o=new a.InstancedBufferGeometry;o.setIndex(t.geometry.getIndex()),o.setAttribute("position",t.geometry.getAttribute("position")),t.geometry.hasAttribute("normal")&&o.setAttribute("normal",t.geometry.getAttribute("normal")),o.setAttribute("uv",t.geometry.getAttribute("uv"));const n=new i(new Float32Array(3*s),3);n.setUsage(a.DynamicDrawUsage),o.setAttribute("offset",n);const l=new i(new Float32Array(4*s),4);if(l.setUsage(a.DynamicDrawUsage),o.setAttribute("color",l),t.material instanceof c){const e=new a.Color(t.material.color);for(let t=0;t<l.count;t++)l.setXYZW(t,e.r,e.g,e.b,1)}const d=new i(new Float32Array(3*s),3);d.setUsage(a.DynamicDrawUsage),o.setAttribute("size",d);const m=new i(new Float32Array(4*s),4);m.setUsage(a.DynamicDrawUsage),o.setAttribute("velocity",m);const h=new i(new Float32Array(4*s),1);h.setUsage(a.DynamicDrawUsage),o.setAttribute("rotation",h),r={mesh:new a.Mesh(o,t.material),indices:new Float32Array(s),particles:[]},this.meshes.push(r),this.container.add(r.mesh)}let s=r.indices.findIndex((e=>0===e));s<0&&(s=function(e){let t=e[0],r=0;for(let a=1;a<e.length;a++)e[a]<t&&(t=e[a],r=a);return r}(r.indices)),r.indices[s]=performance.now(),e.target=s,r.particles[s]=e}}onParticleUpdate(e){}onParticleDead(e){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(r){const t=r.mesh.geometry.getAttribute("size");t.setXYZ(e.target,0,0,0),t.needsUpdate=!0,r.particles[e.target]=null,r.indices[e.target]=0}e.target=null}}const m=new a.Vector3,h=new a.Vector3,u=new a.Quaternion,p=new a.Vector3(1,0,0);export class InstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach((e=>e.mesh.dispose()))}onSystemUpdate(){for(const e of this.meshes);}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate;return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(!(e.body instanceof a.Sprite)){if(null==e.target){const t=e.body;let r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));if(null==r){const i=this.calcMaxCount(e);r={mesh:new a.InstancedMesh(t.geometry,t.material,i),indices:new Array(i).fill(null),particles:[]},r.mesh.setColorAt(0,C.setScalar(1)),r.mesh.instanceColor.needsUpdate=!0,r.mesh.material.defines.USE_INSTANCING="";const s=new Float32Array(3*i);b.makeScale(0,0,0);for(let e=0;e<i;e++)s[3*e+0]=1,s[3*e+1]=1,r.mesh.setMatrixAt(e,b);r.mesh.instanceMatrix.needsUpdate=!0,r.mesh.geometry.setAttribute("particleData",new a.InstancedBufferAttribute(s,3)),this.meshes.push(r),this.container.add(r.mesh)}let i=r.indices.findIndex((e=>null==e));i<0&&(i=r.indices.indexOf(Math.min(...r.indices))),r.indices[i]=performance.now(),e.target=i,r.particles[i]=e}if("number"==typeof e.target){e.transform.initialScale;const t=e.body;let r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));f(e,r.mesh),e.useAlpha&&(r.mesh.material.transparent=!0)}}}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:a,rotation:i}=e;if(null==t)return;const s=e.body,o=this.meshes.find((e=>e.mesh.geometry.uuid===s.geometry.uuid&&e.mesh.material.uuid===s.material.uuid));if(null==o)return;f(e,o.mesh),a&&(o.mesh.setColorAt(e.target,C.copy(e.color)),o.mesh.instanceColor.needsUpdate=!0);const n=o.mesh.geometry.getAttribute("particleData");r&&n.setX(e.target,e.alpha),n.setY(e.target,e.energy),n.needsUpdate=!0}onParticleDead(e){if(null!=e.target){const t=e.body,r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));if(null==r)return;r.indices[e.target]=null,e.scale=0,f(e,r.mesh),r.mesh.instanceMatrix.needsUpdate=!0,e.target=null}}}const g=new s;function f(e,t){if(x.set(e.position.x,e.position.y,e.position.z),e.transform&&e.transform.orientAlongVelocity){const r=m.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize();t.getMatrixAt(e.target,g.matrix);const a=g.getWorldDirection(A);a.applyAxisAngle(p,Math.PI/-2),w.setFromUnitVectors(a,r)}else U.set(e.rotation.x,e.rotation.y,e.rotation.z),w.setFromEuler(U);const r=e.transform.initialScale;null!=r?A.set(r.x*e.scale,r.y*e.scale,r.z*e.scale):A.set(e.scale,e.scale,e.scale),b.compose(x,w,A),t.setMatrixAt(e.target,b),t.instanceMatrix.needsUpdate=!0}const y=new a.Vector3(0,0,-1),b=new a.Matrix4,w=new a.Quaternion,x=new a.Vector3,A=new a.Vector3,U=new a.Euler,C=new a.Color(0),M={r:0,g:0,b:0};function P(e,t){const r=e.mesh,i=r.count,s=[],o=r.geometry.getAttribute("particleData"),n=new a.Vector3;for(let l=0;l<i;l++){const i=new a.Matrix4,c=new a.Color;r.getMatrixAt(l,i),r.getColorAt(l,c);const d=o.getX(l);n.setFromMatrixPosition(i);const m=n.distanceTo(t.position);s.push({index:l,distance:m,matrix:i,particle:e.particles[l],color:c,pdx:d})}s.sort(((e,t)=>t.distance-e.distance));for(let e=0;e<i;e++){const t=s[e].matrix;null==s[e].particle&&t.makeScale(0,0,0),r.setMatrixAt(e,t),r.setColorAt(e,s[e].color),o.setX(e,s[e].pdx)}r.instanceMatrix.needsUpdate=!0}export{P as sortInstancedMeshByDistance};/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,5 +1,6 @@
|
|
1
1
|
import * as RAPIER from "@dimforge/rapier3d-compat";
|
2
2
|
import { Observable, Subject } from "rxjs";
|
3
|
+
import * as THREE from "three";
|
3
4
|
import { ColorRepresentation, Object3D, Vector3 } from "three";
|
4
5
|
import { CollisionShape } from '../../../index.js';
|
5
6
|
import { AbstractType } from '../../../utils/type.js';
|
@@ -408,4 +409,10 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
|
|
408
409
|
*/
|
409
410
|
createCharacterCollision(): RAPIER.CharacterCollision;
|
410
411
|
}
|
412
|
+
/**
|
413
|
+
* This handles interleaved buffer attributes
|
414
|
+
* @param attr
|
415
|
+
* @returns
|
416
|
+
*/
|
417
|
+
export declare function extractFloat32Array(attr: THREE.BufferAttribute | THREE.InterleavedBufferAttribute): Float32Array;
|
411
418
|
//# sourceMappingURL=physics-system.d.ts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"physics-system.d.ts","sourceRoot":"","sources":["../../../../src/gameplay/services/physics/physics-system.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,2BAA2B,CAAA;AAEnD,OAAO,EAAgE,UAAU,EAAE,OAAO,EAA2B,MAAM,MAAM,CAAA;
|
1
|
+
{"version":3,"file":"physics-system.d.ts","sourceRoot":"","sources":["../../../../src/gameplay/services/physics/physics-system.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,2BAA2B,CAAA;AAEnD,OAAO,EAAgE,UAAU,EAAE,OAAO,EAA2B,MAAM,MAAM,CAAA;AACjI,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAGL,mBAAmB,EAE6C,QAAQ,EAIxE,OAAO,EACR,MAAM,OAAO,CAAA;AAGd,OAAO,EAGL,cAAc,EAQf,MAAM,mBAAmB,CAAA;AAM1B,OAAO,EAAE,YAAY,EAAQ,MAAM,wBAAwB,CAAA;AAC3D,OAAO,EAAW,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAKnC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAA;AAGzF,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,KAAK,gBAAgB,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AAG7G,qBAAa,aAAa;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AE,CAAC,SAAS,SAAS,EAClE,IAAI,EAAE,CAAC,EACP,KAAK,EAAE,CAAC,GACP,UAAU,CAAC,CAAC,CAAC;IAKhB;;;;;OAKG;IACI,wBAAwB,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,EACtE,IAAI,EAAE,CAAC,EACP,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC,GACzB,UAAU,CAAC,CAAC,CAAC;IAIhB;;;OAGG;IACI,oBAAoB,CAAC,KAAK,EAAE,SAAS;IAS5C;;;OAGG;IACH,OAAO,CAAC,UAAU;IAKlB;;;;;OAKG;IACI,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,GAAG;QAC7D,EAAE,EAAE,OAAO,CAAC;QACZ,EAAE,EAAE,OAAO,CAAC;QACZ,EAAE,EAAE,OAAO,CAAA;KACZ,EAAE;IA8BH;;OAEG;IACI,IAAI;IAMX;;;;;;;OAOG;IACH,OAAO,CAAC,gBAAgB;IA2BxB;;;;;;;OAOG;IACH,OAAO,CAAC,QAAQ;IAoChB;;;;;;OAMG;IACH,OAAO,CAAC,WAAW;IAqFnB;;;OAGG;IACI,wBAAwB,IAAI,MAAM,CAAC,kBAAkB;CAG7D;AA4LD;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,KAAK,CAAC,eAAe,GAAG,KAAK,CAAC,0BAA0B,GAC7D,YAAY,CAcd"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as t,__metadata as e}from"tslib";import*as i from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as c,takeUntil as l}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as y,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as v,Scene as x,Vector3 as b}from"three";import{Service as B}from"typedi";import{AssetMeshInstance as A}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as C,CapsuleCollisionShape as D,ConeCollisionShape as M,ConvexPolyhedronCollisionShape as z,CylinderCollisionShape as R,PhysicalShapeMesh as S,PlaneCollisionShape as T,SphereCollisionShape as E,TrimeshCollisionShape as W}from"../../../index.js";import{LandscapeGroup as j}from"../../../scene/landscape/landscape.js";import{ViewController as F}from"../render.js";import{World as V}from"../world.js";import*as _ from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as P}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as I}from"./abstract-physics-system.js";import{ActorComponent as L,Component as k}from"../../../gameplay/actors/component.js";import{inject as O}from"../../../gameplay/inject.js";export{Component,ActorComponent,attach,Attach}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.hitNormal=new b}}export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));let N=class extends I{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(t,e){super(),this.viewController=t,this.gameWorld=e,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new c,this.beforeStep=new c,this.afterStep=new c,this.shouldRenderDebug=!1,this._raycaster=new v,this._reusableResult=new RayTestResult,this._raytestDiff=new b,this._raytestDirection=new b,this.controlledActors=new Set,this.ready=this.setup()}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.ready}renderDebug(){null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.gameWorld.scene.add(this.debugMesh));const t=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new u(t.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await Z(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;var i,s;null!=e&&(e.parent instanceof x&&($(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&(i=e.quaternion,s=t.rotation(),i.x=s.x,i.y=s.y,i.z=s.z,i.w=s.w),e.updateMatrix(),e.updateWorldMatrix(!1,!1)))})),this.afterStep.next(t)}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((t,e,i)=>{this.collisionEvents.next({handle1:t,handle2:e,started:i}),this.collisionEvents.next({handle1:e,handle2:t,started:i})}))}rayTestFromCamera(t,e,i){this._raycaster.setFromCamera(Y,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(s);return this.rayTest(s,o,e,i)}rayTest(t,e,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),i;J(nt.origin,t),J(nt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(nt,r,!1,void 0,void 0,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?t=>!t.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const e=nt.pointAt(a.timeOfImpact);i._internal=a,$(i.hitNormal,a.normal),$(i.hitPoint,e),i.distance=et.subVectors(i.hitPoint,t).length();const s=this.world.bodies.getAll().find((t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,(t=>t===a.collider))));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){const e=new h(n,t,r,s?.debugColor??255);this.gameWorld.scene.add(e),setTimeout((()=>this.gameWorld.scene.remove(e)),s?.debugLifetime??200)}return i}setGravity(t,e,i){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=i}getGravity(){return U.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())tt(t,(t=>t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof S&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof A&&!1!==t.userData?.src?.collisionDetection)if(t.children[0]&&t.children[0].instanceMatrix)this.createForInstancedMesh(t.children[0],t.collisionShapes);else{const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else t instanceof j?this.addLandscapeGroup(t):(t instanceof p||t instanceof x)&&t.children.forEach((t=>this.addRecursively(t)))}createForInstancedMesh(t,e){const i=new m;for(let s=0;s<t.count;s++){const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*s),o.applyMatrix4(i);this.createStaticBody(o,e)}}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,i,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,o,st);const a=e.computedMovement();return $(it,a),it}setNextKinematicTranslation(t,e){const i=this.actorBodies.get(t.id),s=i.translation();s.x+=e.x,s.y+=e.y,s.z+=e.z,i?.setNextKinematicTranslation(s)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.setAngvel(H,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.setLinvel(H,!0)}getLinearVelocity(t,e=new b){const i=this.actorBodies.get(t.id).linvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}getAngularVelocity(t,e=new b){const i=this.actorBodies.get(t.id).angvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}setLinearDamping(t,e){const i=this.actorBodies.get(t.id);i?.setLinearDamping(e)}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}addLandscapeGroup(t){const e=t.userData.src,s=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new b);if(e.landscape.holes&&e.landscape.holes.some((t=>t.m===n.name&&0!==t.w[0]))){const t=n.geometry.clone(),s=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=s.x,a[t+1]*=s.y,a[t+2]*=s.z;const c=t.index;for(let t=0;t<c.count;t+=3){const e=r.getX(c.getX(t)),i=r.getX(c.getY(t)),s=r.getX(c.getZ(t));(e>.5||i>.5||s>.5)&&(c.setX(t,0),c.setY(t,0),c.setZ(t,0))}const l=i.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);J(e,o),t.setTranslation(e,!1),this.world.createCollider(l,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const c=s.find((t=>t.x===n.x&&t.y==n.y));if(null!=c)for(const e of c.points){if(null==a[e.i%t])continue;const i=t-1-Math.floor(e.i/t);i in a[e.i%t]?a[e.i%t][i]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:i,heightMap:c})}const l=e.landscape.options.density,d=a.flatMap((t=>t.reverse())),h=i.ColliderDesc.heightfield(l,l,new Float32Array(d),new i.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);J(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const i=this.actorBodies.get(t.id);i?.setEnabled(e)}addActor(t,e,s={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const o=t.object;let n;switch(s.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=i.RigidBodyDesc.dynamic(),n.mass=s.mass??1;break;case PhysicsBodyType.kinematic:n=i.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=i.RigidBodyDesc.kinematicVelocityBased();break;default:n=s.isTrigger?i.RigidBodyDesc.kinematicVelocityBased():i.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==s.continousCollisionDetection);for(const t of e)this.addShape(r,t,o);tt(r,(t=>{null!=s.isTrigger&&(t.setSensor(s.isTrigger),t.setActiveCollisionTypes(i.ActiveCollisionTypes.ALL),t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)),null!=s.friction&&t.setFriction(s.friction),null!=s.density&&t.setDensity(s.density),null!=s.mass&&t.setMass(s.mass),null!=s.restitution&&t.setRestitution(s.restitution)})),Q(r,o),!0===s.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,r),this.bodyActors.set(r,t)}applyTorque(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.addTorque(H,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.applyTorqueImpulse(H,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.addForce(H,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.applyImpulse(H,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);J(H,e),null==i?s?.addForce(H,!0):(J(X,i),s?.addForceAtPoint(H,X,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);J(H,e),null==i?s.applyImpulse(H,!0):(J(X,i),s.applyImpulseAtPoint(H,X,!0))}applyRadiusImpulse(t,e,s){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const n=K;$(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);H.x=a.x,H.y=a.y,H.z=a.z,o.applyImpulse(H,!0)}))}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){const e=new Set;t.traverse((t=>{e.add(t.uuid)}));for(const[t,i]of this.staticBodies.entries())!e.has(t.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(i))}removeSceneObject(t){if(t instanceof j){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,i){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((({started:t})=>t===i)),a((({handle1:t,handle2:e,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:i}))),r((({a1:i,a2:s})=>null!=i&&null!=s&&i.id===t.id&&e(i,s))),a((({a2:t})=>t)))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>t.started)),r((({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id})),a((t=>t.handle2)))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>!t.started)),r((({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id})),a((t=>t.handle2)))}onHasContactChanged(t){const e=new Set,i=new o(!1);return this.onBeginContact(t).subscribe((t=>{e.add(t),i.next(e.size>0)})),this.onEndContact(t).subscribe((t=>{e.delete(t),i.next(e.size>0)})),i.pipe(n())}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>i instanceof e),!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>i instanceof e),!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>e.id===i.id),!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>e.id===i.id),!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e?Q(e,t.object):console.warn("Actor has not been added to physics world",t)}setupWorld(){const t=new i.World({x:0,y:-9.81,z:0});this.world=t}getActorContacts(t,e){const s=this.actorBodies.get(t.id);if(s&&s.numColliders()>0){const o=s.collider(0);let n=o.shape,r=o.translation(),a=o.rotation(),c=e,l=.3;const d=this.world.castShape(r,a,c,n,.1,l,!0,null,null,null,this.actorBodies.get(t.id),(t=>t.shape.type!=i.ShapeType.HeightField));if(null!=d){const t=new b,e=new b,i=new b;return $(t,d.witness2),$(e,d.witness1),$(i,d.normal1),i.negate(),[{ri:t,rj:e,ni:i}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){this.world?.bodies.forEach((t=>this.world.removeRigidBody(t))),this.world?.free(),this.fixedupdateSub?.unsubscribe()}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const i of e){if(null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return Q(n,t),n.userData=t.uuid,n}addShape(t,e,s){const o=s.getWorldScale(ot),n=this.createShape(e,o);null!=e.collisionGroup&&n.setCollisionGroups(e.collisionGroup),n.friction=e.friction??.1,null!=e.restitution&&(n.restitution=e.restitution),null!=e.density&&(n.density=e.density,n.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(n.mass=e.mass,n.massPropsMode=i.MassPropsMode.Mass);const r=e.offset.clone().multiply(o);J(n.translation,r);const a=(new w).setFromEuler(e.rotation);var c,l;e instanceof z&&e.mesh instanceof d.Mesh&&a.multiply(e.mesh.getWorldQuaternion(q)),c=n.rotation,l=a,c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w;return this.world.createCollider(n,t)}createShape(t,e){if(t instanceof C)return i.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof D){return i.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof W){const s=null!=t.geometry.getIndex()?t.geometry:_.mergeVertices(t.geometry),o=new Float32Array(s.getAttribute("position").array);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(t instanceof z){let s;t.mesh instanceof d.Mesh?s=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?s=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=new Float32Array(s.getAttribute("position").array);if(t.mesh instanceof d.Mesh){const e=P(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;return i.ColliderDesc.convexHull(n)}if(t instanceof E){const s=2*e.x-e.y-e.z;return Math.abs(s)>.01?this.createShape(new z(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):i.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof R?i.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof M?i.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof T?i.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};N=t([B(),e("design:paramtypes",[F,V])],N);export{N as PhysicsSystem};const G=new b,q=new d.Quaternion;function Q(t,e){const s=e.getWorldPosition(G),o=e.getWorldQuaternion(q);t.setTranslation(new i.Vector3(s.x,s.y,s.z),!1),t.setRotation(new i.Quaternion(o.x,o.y,o.z,o.w),!1)}const U=new b,H=new i.Vector3(0,0,0),X=new i.Vector3(0,0,0),K=new b,Y=new d.Vector2,Z=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function J(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function $(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function tt(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const et=new b,it=new b,st=t=>!t.isSensor(),ot=new b;const nt=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));let rt=class extends L{constructor(){super(...arguments),this._active=!0,this.physics=O(N),this.world=O(V)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};rt=t([k()],rt);/*
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import*as i from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as c,takeUntil as l}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as y,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as v,Scene as x,Vector3 as b}from"three";import{Service as B}from"typedi";import{AssetMeshInstance as A}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as C,CapsuleCollisionShape as D,ConeCollisionShape as M,ConvexPolyhedronCollisionShape as z,CylinderCollisionShape as S,PhysicalShapeMesh as R,PlaneCollisionShape as T,SphereCollisionShape as E,TrimeshCollisionShape as W}from"../../../index.js";import{LandscapeGroup as F}from"../../../scene/landscape/landscape.js";import{ViewController as j}from"../render.js";import{World as V}from"../world.js";import*as _ from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as P}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as I}from"./abstract-physics-system.js";import{ActorComponent as L,Component as k}from"../../../gameplay/actors/component.js";import{inject as O}from"../../../gameplay/inject.js";export{Component,ActorComponent,attach,Attach}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.hitNormal=new b}}export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));let N=class extends I{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(t,e){super(),this.viewController=t,this.gameWorld=e,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new c,this.beforeStep=new c,this.afterStep=new c,this.shouldRenderDebug=!1,this._raycaster=new v,this._reusableResult=new RayTestResult,this._raytestDiff=new b,this._raytestDirection=new b,this.controlledActors=new Set,this.ready=this.setup()}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.ready}renderDebug(){null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.gameWorld.scene.add(this.debugMesh));const t=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new u(t.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await Z(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;var i,s;null!=e&&(e.parent instanceof x&&($(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&(i=e.quaternion,s=t.rotation(),i.x=s.x,i.y=s.y,i.z=s.z,i.w=s.w),e.updateMatrix(),e.updateWorldMatrix(!1,!1)))})),this.afterStep.next(t)}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((t,e,i)=>{this.collisionEvents.next({handle1:t,handle2:e,started:i}),this.collisionEvents.next({handle1:e,handle2:t,started:i})}))}rayTestFromCamera(t,e,i){this._raycaster.setFromCamera(Y,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(s);return this.rayTest(s,o,e,i)}rayTest(t,e,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),i;J(nt.origin,t),J(nt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(nt,r,!1,void 0,void 0,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?t=>!t.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const e=nt.pointAt(a.timeOfImpact);i._internal=a,$(i.hitNormal,a.normal),$(i.hitPoint,e),i.distance=et.subVectors(i.hitPoint,t).length();const s=this.world.bodies.getAll().find((t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,(t=>t===a.collider))));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){const e=new h(n,t,r,s?.debugColor??255);this.gameWorld.scene.add(e),setTimeout((()=>this.gameWorld.scene.remove(e)),s?.debugLifetime??200)}return i}setGravity(t,e,i){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=i}getGravity(){return U.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())tt(t,(t=>t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof R&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof A&&!1!==t.userData?.src?.collisionDetection)if(t.children[0]&&t.children[0].instanceMatrix)this.createForInstancedMesh(t.children[0],t.collisionShapes);else{const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else t instanceof F?this.addLandscapeGroup(t):(t instanceof p||t instanceof x)&&t.children.forEach((t=>this.addRecursively(t)))}createForInstancedMesh(t,e){const i=new m;for(let s=0;s<t.count;s++){const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*s),o.applyMatrix4(i);this.createStaticBody(o,e)}}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,i,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,o,st);const a=e.computedMovement();return $(it,a),it}setNextKinematicTranslation(t,e){const i=this.actorBodies.get(t.id),s=i.translation();s.x+=e.x,s.y+=e.y,s.z+=e.z,i?.setNextKinematicTranslation(s)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.setAngvel(H,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.setLinvel(H,!0)}getLinearVelocity(t,e=new b){const i=this.actorBodies.get(t.id).linvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}getAngularVelocity(t,e=new b){const i=this.actorBodies.get(t.id).angvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}setLinearDamping(t,e){const i=this.actorBodies.get(t.id);i?.setLinearDamping(e)}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}addLandscapeGroup(t){const e=t.userData.src,s=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new b);if(e.landscape.holes&&e.landscape.holes.some((t=>t.m===n.name&&0!==t.w[0]))){const t=n.geometry.clone(),s=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=s.x,a[t+1]*=s.y,a[t+2]*=s.z;const c=t.index;for(let t=0;t<c.count;t+=3){const e=r.getX(c.getX(t)),i=r.getX(c.getY(t)),s=r.getX(c.getZ(t));(e>.5||i>.5||s>.5)&&(c.setX(t,0),c.setY(t,0),c.setZ(t,0))}const l=i.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);J(e,o),t.setTranslation(e,!1),this.world.createCollider(l,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const c=s.find((t=>t.x===n.x&&t.y==n.y));if(null!=c)for(const e of c.points){if(null==a[e.i%t])continue;const i=t-1-Math.floor(e.i/t);i in a[e.i%t]?a[e.i%t][i]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:i,heightMap:c})}const l=e.landscape.options.density,d=a.flatMap((t=>t.reverse())),h=i.ColliderDesc.heightfield(l,l,new Float32Array(d),new i.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);J(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const i=this.actorBodies.get(t.id);i?.setEnabled(e)}addActor(t,e,s={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const o=t.object;let n;switch(s.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=i.RigidBodyDesc.dynamic(),n.mass=s.mass??1;break;case PhysicsBodyType.kinematic:n=i.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=i.RigidBodyDesc.kinematicVelocityBased();break;default:n=s.isTrigger?i.RigidBodyDesc.kinematicVelocityBased():i.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==s.continousCollisionDetection);for(const t of e)this.addShape(r,t,o);tt(r,(t=>{null!=s.isTrigger&&(t.setSensor(s.isTrigger),t.setActiveCollisionTypes(i.ActiveCollisionTypes.ALL),t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)),null!=s.friction&&t.setFriction(s.friction),null!=s.density&&t.setDensity(s.density),null!=s.mass&&t.setMass(s.mass),null!=s.restitution&&t.setRestitution(s.restitution)})),Q(r,o),!0===s.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,r),this.bodyActors.set(r,t)}applyTorque(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.addTorque(H,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.applyTorqueImpulse(H,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.addForce(H,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.applyImpulse(H,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);J(H,e),null==i?s?.addForce(H,!0):(J(X,i),s?.addForceAtPoint(H,X,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);J(H,e),null==i?s.applyImpulse(H,!0):(J(X,i),s.applyImpulseAtPoint(H,X,!0))}applyRadiusImpulse(t,e,s){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const n=K;$(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);H.x=a.x,H.y=a.y,H.z=a.z,o.applyImpulse(H,!0)}))}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){const e=new Set;t.traverse((t=>{e.add(t.uuid)}));for(const[t,i]of this.staticBodies.entries())!e.has(t.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(i))}removeSceneObject(t){if(t instanceof F){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,i){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((({started:t})=>t===i)),a((({handle1:t,handle2:e,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:i}))),r((({a1:i,a2:s})=>null!=i&&null!=s&&i.id===t.id&&e(i,s))),a((({a2:t})=>t)))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>t.started)),r((({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id})),a((t=>t.handle2)))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>!t.started)),r((({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id})),a((t=>t.handle2)))}onHasContactChanged(t){const e=new Set,i=new o(!1);return this.onBeginContact(t).subscribe((t=>{e.add(t),i.next(e.size>0)})),this.onEndContact(t).subscribe((t=>{e.delete(t),i.next(e.size>0)})),i.pipe(n())}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>i instanceof e),!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>i instanceof e),!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>e.id===i.id),!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>e.id===i.id),!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e?Q(e,t.object):console.warn("Actor has not been added to physics world",t)}setupWorld(){const t=new i.World({x:0,y:-9.81,z:0});this.world=t}getActorContacts(t,e){const s=this.actorBodies.get(t.id);if(s&&s.numColliders()>0){const o=s.collider(0);let n=o.shape,r=o.translation(),a=o.rotation(),c=e,l=.3;const d=this.world.castShape(r,a,c,n,.1,l,!0,null,null,null,this.actorBodies.get(t.id),(t=>t.shape.type!=i.ShapeType.HeightField));if(null!=d){const t=new b,e=new b,i=new b;return $(t,d.witness2),$(e,d.witness1),$(i,d.normal1),i.negate(),[{ri:t,rj:e,ni:i}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){this.world?.bodies.forEach((t=>this.world.removeRigidBody(t))),this.world?.free(),this.fixedupdateSub?.unsubscribe()}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const i of e){if(null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return Q(n,t),n.userData=t.uuid,n}addShape(t,e,s){const o=s.getWorldScale(ot),n=this.createShape(e,o);null!=e.collisionGroup&&n.setCollisionGroups(e.collisionGroup),n.friction=e.friction??.1,null!=e.restitution&&(n.restitution=e.restitution),null!=e.density&&(n.density=e.density,n.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(n.mass=e.mass,n.massPropsMode=i.MassPropsMode.Mass);const r=e.offset.clone().multiply(o);J(n.translation,r);const a=(new w).setFromEuler(e.rotation);var c,l;e instanceof z&&e.mesh instanceof d.Mesh&&a.multiply(e.mesh.getWorldQuaternion(q)),c=n.rotation,l=a,c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w;return this.world.createCollider(n,t)}createShape(t,e){if(t instanceof C)return i.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof D){return i.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof W){const s=null!=t.geometry.getIndex()?t.geometry:_.mergeVertices(t.geometry),o=extractFloat32Array(s.getAttribute("position"));for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(t instanceof z){let s;t.mesh instanceof d.Mesh?s=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?s=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=extractFloat32Array(s.getAttribute("position"));if(t.mesh instanceof d.Mesh){const e=P(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;n.length;return i.ColliderDesc.convexHull(n)}if(t instanceof E){const s=2*e.x-e.y-e.z;return Math.abs(s)>.01?this.createShape(new z(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):i.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof S?i.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof M?i.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof T?i.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};N=t([B(),e("design:paramtypes",[j,V])],N);export{N as PhysicsSystem};const G=new b,q=new d.Quaternion;function Q(t,e){const s=e.getWorldPosition(G),o=e.getWorldQuaternion(q);t.setTranslation(new i.Vector3(s.x,s.y,s.z),!1),t.setRotation(new i.Quaternion(o.x,o.y,o.z,o.w),!1)}const U=new b,H=new i.Vector3(0,0,0),X=new i.Vector3(0,0,0),K=new b,Y=new d.Vector2,Z=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function J(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function $(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function tt(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const et=new b,it=new b,st=t=>!t.isSensor(),ot=new b;const nt=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));let rt=class extends L{constructor(){super(...arguments),this._active=!0,this.physics=O(N),this.world=O(V)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};rt=t([k()],rt);export function extractFloat32Array(t){const e=t.itemSize,i=t.count,s=new Float32Array(i*e);for(let o=0;o<i;o++)for(let i=0;i<e;i++)s[o*e+i]=t.getComponent(o,i);return s}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
package/dist/rendering.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"rendering.d.ts","sourceRoot":"","sources":["../src/rendering.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EACL,MAAM,EAKN,QAAQ,EAIR,aAAa,EACb,iBAAiB,EAClB,MAAM,OAAO,CAAC;AAOf,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAC;AAGpD,OAAO,EAAE,QAAQ,EAAE,MAAM,+CAA+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AAS,EAAE,MAAM,KAAK,GAAG,EAAE,SAAS,UAAQ;IAqPlE,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,UAAU,CAA8B;IAChD,OAAO,CAAC,YAAY,CAAM;IAC1B,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,eAAe,CAAI;IAE3B,OAAO,CAAC,cAAc,CAAyB;IAE/C,OAAO,CAAC,aAAa;IAyBd,gBAAgB,CAAC,MAAM,EAAE,MAAM;IAI/B,mBAAmB;IAInB,mBAAmB,CAAC,MAAM,EAAE,MAAM;IAIzC,OAAO,CAAC,cAAc,CAAc;IACpC,OAAO,CAAC,QAAQ,CAAQ;IACjB,MAAM,CAAC,SAAS,CAAC,EAAE,MAAM;IAmChC,OAAO,CAAC,oBAAoB,CAAK;IACjC,OAAO,CAAC,WAAW,CAAiB;IAEpC,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,gBAAgB;IAkBxB,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,gBAAgB;CA4BzB;AAcD,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,QAIhD;AAuGD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,GAAG,OAAO,CAIzF"}
|
package/dist/rendering.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
var e;import{__decorate as t,__metadata as i}from"tslib";import*as s from"three";import{Color as r,Material as n,Matrix4 as a,Mesh as o,PerspectiveCamera as h,ShaderChunk as l,ShaderMaterial as d}from"three";import{EffectComposer as c,FXAAShader as m,GammaCorrectionShader as p,RenderPass as u,ShaderPass as f,UnrealBloomPass as g,VRButton as v}from"three-stdlib";import{CSMShader as x,CSMUtil as w}from"./csm.js";import{NodeShaderMaterial as b}from"three-shader-graph";import{Reflector as T}from"three-stdlib";import{OutputPass as y}from"three/examples/jsm/Addons.js";import{CSM as M}from"three/examples/jsm/csm/CSM.js";import C from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as R}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as P}from"typedi";import{depthUniformName as S,farUniformName as D,nearUniformName as F,resolutionUniformName as W,supportsDepthTextureExtension as H}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as A}from"./shader-nodes/time.js";import{DepthPass as L}from"./utils/three/depth-pass.js";import{GPUStatsPanel as k}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as O}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as j}from"./utils/three/traverse.js";(new s.Layers).set(9);const E=new s.MeshBasicMaterial({color:"black"}),B=new s.MeshDepthMaterial;B.depthPacking=s.RGBADepthPacking,B.blending=s.NoBlending,B.side=s.DoubleSide;const U=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let z=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof h&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.bloomComposer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.aoMaskDepthRenderTarget.dispose(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.aoPass.blendMaterial.uniforms.tDepth.value=this.aoMaskDepthRenderTarget.depthTexture,this.depthRenderTarget.dispose(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container))}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=U?.5:1,this.maxPixelRatio=U?1:window.devicePixelRatio,this.onResize=()=>{this.resizeRender(),this.paused||this.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=new C,this._showStats=!0,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],null!=i.maxPixelRatio&&(this.maxPixelRatio=i.maxPixelRatio),window.renderer=this.renderer=new s.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new s.Scene,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(v.createButton(this.renderer)),this.composer=new c(this.renderer);var n=t.clientWidth/t.clientHeight;const a=new s.PerspectiveCamera(45,n,.5,800);a.layers.enable(19),this.setCamera(a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=s.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=i.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=s.SRGBColorSpace,this.renderer.toneMapping=s.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,w.renderingView=this,w.patchThreeAdd(),this.isDepthTextureExtensionSupported=H(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container);const o=new u(this.scene,this.camera);this.composer.addPass(o);const h=new g(new s.Vector2(t.clientWidth,t.clientHeight),1.5,.4,.85);h.threshold=1,h.strength=.9,h.radius=.5,this.bloomPass=h;const l=new R(this.scene,this.camera,t.clientWidth,t.clientWidth);l.blendMaterial.uniforms.tDepth={value:this.aoMaskDepthRenderTarget.depthTexture},l.blendMaterial.uniforms.tAODepth={value:l.depthTexture},l.blendMaterial.fragmentShader="\n uniform float intensity;\n uniform sampler2D tDiffuse;\n uniform sampler2D tDepth;\n uniform sampler2D tAODepth;\n varying vec2 vUv;\n\n void main() {\n vec4 texel = texture2D( tDiffuse, vUv );\n float d = textureLod(tDepth, vUv.xy, 0.0).x;\n float d2 = textureLod(tAODepth, vUv.xy, 0.0).x;\n\n float depth = 2.0 * 1.0 * 500.0 / (500.0 + 1.0 - (2.0 * d - 1.0) * (500.0 - 1.0));\n gl_FragColor = vec4(mix(vec3(1.), texel.rgb, d2 > d ? 0.0 : intensity), texel.a);\n }\n ",l.output=R.OUTPUT.Default,l.enabled=!1,this.aoPass=l,!1!==this.options.ao?.enabled&&this.composer.addPass(l),this.renderer.info.autoReset=!1;const d=new c(this.renderer);d.renderToScreen=!1,d.addPass(o),d.addPass(h),this.bloomComposer=d,d.renderTarget2.texture.type=s.HalfFloatType,this.composer.renderTarget1.texture.type=s.HalfFloatType;const x=new f(new s.ShaderMaterial({uniforms:{baseTexture:{value:null},bloomTexture:{value:d.renderTarget2.texture}},vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }",fragmentShader:"\n uniform sampler2D baseTexture;\n uniform sampler2D bloomTexture;\n varying vec2 vUv;\n void main() {\n gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n }",defines:{}}),"baseTexture");if(x.needsSwap=!0,this.composer.addPass(x),this.outlinePass=new O(new s.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new f(m);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e)}new f(p).clear=!1,this.fixStatsStyle();const b=new y;this.composer.addPass(b)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setCamera(e){this.camera=e,this.composer.passes.forEach((t=>{t instanceof u?t.camera=e:t instanceof O?t.renderCamera=e:(t instanceof L||t instanceof R)&&(t.camera=e)})),null==this.csm?(this.csm=new M({maxFar:500,lightFar:250,lightMargin:20,cascades:4,shadowMapSize:2048,lightDirection:new s.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene}),l.lights_fragment_begin=x.lights_fragment_begin):(this.csm.camera=this.camera,this.camera instanceof h&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t){var i=!!e.extensions.get("WEBGL_depth_texture");const r=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio());return r.texture.minFilter=s.NearestFilter,r.texture.magFilter=s.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===i&&(r.depthTexture=new s.DepthTexture(128,128),r.depthTexture.type=s.UnsignedShortType,r.depthTexture.minFilter=s.NearestFilter,r.depthTexture.magFilter=s.NearestFilter),r}static createAOMaskDepthRenderTarget(e,t){const i=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:s.HalfFloatType});return i.texture.minFilter=s.NearestFilter,i.texture.magFilter=s.NearestFilter,i.texture.generateMipmaps=!1,i.stencilBuffer=!1,i.depthTexture=new s.DepthTexture(128,128),i.depthTexture.type=s.UnsignedInt248Type,i.depthTexture.minFilter=s.NearestFilter,i.depthTexture.magFilter=s.NearestFilter,i}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){null!=this.scene.environment&&e instanceof b&&(null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1}),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment)}loop(e,t=!1){const i=this.stats,r=i.addPanel(new C.Panel("Calls","#83f","#002")),h=i.addPanel(new C.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new k(this.renderer.getContext()),i.addPanel(l)),this.showStats=t;let d=10,c=1e3;const m=()=>{const e=this.renderer.info.render.calls;e>d&&(d=e,setTimeout((()=>d=10),5e3)),r.update(e,d);const t=this.renderer.info.render.triangles;t>c&&(c=t,setTimeout((()=>c=1e3),5e3)),h.update(t,c)};performance.now();s.Ray.prototype.intersectTriangle;const p=[],u=[];let f=0;const g=new a,v=new a,x=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return void setTimeout((()=>x(t)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,i.begin();let a=(t*=.001)-f;if(f=t,g.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(V),t-=V;e(t)}else e(a);this.onLoopCallbacks.forEach((e=>e(a))),this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),v.equals(g)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender(),p.length=0,u.length=0;const h=_;if(this.camera.updateMatrixWorld(),N.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(N),this.scene.traverseVisible((e=>{if(null!=this.scene.environment&&(e instanceof o||e instanceof s.Sprite)&&function(e,t){if(Array.isArray(e.material))for(const i of e.material)t(i);else null!=e.material&&t(e.material)}(e,(e=>this.applyEnvMap(e))),(e instanceof o||e instanceof s.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[S])&&isObjectInFrustum(e,h)?(e.visible=!1,p.push(e),this.initDepthUniform(e.material),e.renderOrder=100):e instanceof T?(e.visible=!1,u.push(e)):(e instanceof o||e instanceof s.Sprite)&&function(e){if(e.material instanceof n)return e.material.transparent||e.material.alphaTest>0;if(Array.isArray(e.material))for(const t of e.material)if(t.transparent||t.alphaTest>0)return!0}(e)&&(e.visible=!1,e.layers.enable(5),u.push(e)),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[A])e.material.uniforms[A].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const i of e.material)i.uniforms&&null!=i.uniforms[A]&&(i.uniforms[A].value=t)})),p.length>0){if(this.scene.overrideMaterial=B,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}if(p.forEach((e=>e.visible=!0)),u.forEach((e=>e.visible=!0)),this.aoPass.enabled){if(this.scene.overrideMaterial=B,this.camera.layers.set(5),this.renderer.setRenderTarget(this.aoMaskDepthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.camera.layers.enableAll(),this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}try{!this.paused&&this.running&&(this.showStats&&l?.startQuery(),this.render(a),this.showStats&&l?.endQuery(),this.showStats&&m(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}i.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(x)}),1e3/this.fpsCap):requestAnimationFrame(x))};!0===this.options.enableXR?this.renderer.setAnimationLoop(x):requestAnimationFrame(x)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let s=0;s<e.length;s++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*s+this.insetMargin*s,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[s])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){const t=this.hasBloom();if(t||this.hadBloom){const e=this.scene.fog;this.scene.fog=null;const t=this.renderer.getClearColor(this.prevClearColor);this.renderer.setClearColor(0),this.scene.traverseVisible((e=>this.darkenNonBloomed(e))),this.bloomComposer.render(),this.scene.traverse((e=>this.restoreMaterial(e))),this.bloomHidden.forEach((e=>e.visible=!0)),this.bloomHidden.length=0,this.renderer.setClearColor(t),this.scene.fog=e}this.hadBloom=t,this.composer.render(e)}hasBloom(){return null!=j(this.scene,(e=>e instanceof o&&!0===e.material?.userData?.hasBloom))}darkenNonBloomed(e){(e instanceof o||e instanceof s.Sprite||e instanceof s.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)?(this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=E:e.visible=!1):"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof d&&(e.uniforms[S].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[W]&&e.uniforms[W].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof h&&(null!=e.uniforms[F]&&(e.uniforms[F].value=this.camera.near),null!=e.uniforms[D]&&(e.uniforms[D].value=this.camera.far)))}};z=e=t([P(),i("design:paramtypes",[HTMLElement,Object])],z);export{z as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const V=.05;R.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse((function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls)&&(e.visible=!1),null!=e.material){let t=!1;if(Array.isArray(e.material)){for(const i of e.material)if(null!=i.alphaTest&&i.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0&&(t=!0);t&&(e.visible=!1)}}))};const _=new s.Frustum,I=new s.Box3,N=new s.Matrix4;export function isObjectInFrustum(e,t){const i=I.setFromObject(e);return t.intersectsBox(i)}/*
|
1
|
+
var e;import{__decorate as t,__metadata as i}from"tslib";import*as s from"three";import{Color as r,Material as n,Matrix4 as a,Mesh as o,PerspectiveCamera as h,ShaderChunk as l,ShaderMaterial as d}from"three";import{EffectComposer as c,FXAAShader as m,GammaCorrectionShader as p,RenderPass as u,ShaderPass as f,UnrealBloomPass as g,VRButton as v}from"three-stdlib";import{CSMShader as x,CSMUtil as w}from"./csm.js";import{NodeShaderMaterial as b}from"three-shader-graph";import{Reflector as T}from"three-stdlib";import{OutputPass as y}from"three/examples/jsm/Addons.js";import{CSM as M}from"three/examples/jsm/csm/CSM.js";import C from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as R}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as P}from"typedi";import{depthUniformName as S,farUniformName as D,nearUniformName as F,resolutionUniformName as W,supportsDepthTextureExtension as H}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as A}from"./shader-nodes/time.js";import{DepthPass as L}from"./utils/three/depth-pass.js";import{GPUStatsPanel as k}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as O}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as j}from"./utils/three/traverse.js";(new s.Layers).set(9);const E=new s.MeshBasicMaterial({color:"black"}),B=new s.MeshDepthMaterial;B.depthPacking=s.RGBADepthPacking,B.blending=s.NoBlending,B.side=s.DoubleSide;const U=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let z=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||0!==this.container.clientWidth&&0!==this.container.clientHeight&&(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof h&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.bloomComposer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.aoMaskDepthRenderTarget.dispose(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.aoPass.blendMaterial.uniforms.tDepth.value=this.aoMaskDepthRenderTarget.depthTexture,this.depthRenderTarget.dispose(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container))}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=U?.5:1,this.maxPixelRatio=U?1:window.devicePixelRatio,this.onResize=()=>{this.resizeRender(),this.paused||this.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=new C,this._showStats=!0,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],null!=i.maxPixelRatio&&(this.maxPixelRatio=i.maxPixelRatio),window.renderer=this.renderer=new s.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new s.Scene,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(v.createButton(this.renderer)),this.composer=new c(this.renderer);var n=(t.clientWidth||1)/(t.clientHeight||1);const a=new s.PerspectiveCamera(45,n,.5,800);a.layers.enable(19),this.setCamera(a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=s.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=i.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=s.SRGBColorSpace,this.renderer.toneMapping=s.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,w.renderingView=this,w.patchThreeAdd(),this.isDepthTextureExtensionSupported=H(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container);const o=new u(this.scene,this.camera);this.composer.addPass(o);const h=new g(new s.Vector2(t.clientWidth,t.clientHeight),1.5,.4,.85);h.threshold=1,h.strength=.9,h.radius=.5,this.bloomPass=h;const l=new R(this.scene,this.camera,t.clientWidth,t.clientWidth);l.blendMaterial.uniforms.tDepth={value:this.aoMaskDepthRenderTarget.depthTexture},l.blendMaterial.uniforms.tAODepth={value:l.depthTexture},l.blendMaterial.fragmentShader="\n uniform float intensity;\n uniform sampler2D tDiffuse;\n uniform sampler2D tDepth;\n uniform sampler2D tAODepth;\n varying vec2 vUv;\n\n void main() {\n vec4 texel = texture2D( tDiffuse, vUv );\n float d = textureLod(tDepth, vUv.xy, 0.0).x;\n float d2 = textureLod(tAODepth, vUv.xy, 0.0).x;\n\n float depth = 2.0 * 1.0 * 500.0 / (500.0 + 1.0 - (2.0 * d - 1.0) * (500.0 - 1.0));\n gl_FragColor = vec4(mix(vec3(1.), texel.rgb, d2 > d ? 0.0 : intensity), texel.a);\n }\n ",l.output=R.OUTPUT.Default,l.enabled=!1,this.aoPass=l,!1!==this.options.ao?.enabled&&this.composer.addPass(l),this.renderer.info.autoReset=!1;const d=new c(this.renderer);d.renderToScreen=!1,d.addPass(o),d.addPass(h),this.bloomComposer=d,U||(d.renderTarget2.texture.type=s.HalfFloatType,this.composer.renderTarget1.texture.type=s.HalfFloatType);const x=new f(new s.ShaderMaterial({uniforms:{baseTexture:{value:null},bloomTexture:{value:d.renderTarget2.texture}},vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }",fragmentShader:"\n uniform sampler2D baseTexture;\n uniform sampler2D bloomTexture;\n varying vec2 vUv;\n void main() {\n gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n }",defines:{}}),"baseTexture");if(x.needsSwap=!0,this.composer.addPass(x),this.outlinePass=new O(new s.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new f(m);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e)}new f(p).clear=!1,this.fixStatsStyle();const b=new y;this.composer.addPass(b)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setCamera(e){this.camera=e,this.composer.passes.forEach((t=>{t instanceof u?t.camera=e:t instanceof O?t.renderCamera=e:(t instanceof L||t instanceof R)&&(t.camera=e)})),null==this.csm?(this.csm=new M({maxFar:500,lightFar:250,lightMargin:20,cascades:4,shadowMapSize:2048,lightDirection:new s.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene}),l.lights_fragment_begin=x.lights_fragment_begin):(this.csm.camera=this.camera,this.camera instanceof h&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t){var i=!!e.extensions.get("WEBGL_depth_texture");const r=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio());return r.texture.minFilter=s.NearestFilter,r.texture.magFilter=s.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===i&&(r.depthTexture=new s.DepthTexture(128,128),r.depthTexture.type=s.UnsignedShortType,r.depthTexture.minFilter=s.NearestFilter,r.depthTexture.magFilter=s.NearestFilter),r}static createAOMaskDepthRenderTarget(e,t){const i=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:s.HalfFloatType});return i.texture.minFilter=s.NearestFilter,i.texture.magFilter=s.NearestFilter,i.texture.generateMipmaps=!1,i.stencilBuffer=!1,i.depthTexture=new s.DepthTexture(128,128),i.depthTexture.type=s.UnsignedInt248Type,i.depthTexture.minFilter=s.NearestFilter,i.depthTexture.magFilter=s.NearestFilter,i}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){null!=this.scene.environment&&e instanceof b&&(null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1}),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment)}loop(e,t=!1){const i=this.stats,r=i.addPanel(new C.Panel("Calls","#83f","#002")),h=i.addPanel(new C.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new k(this.renderer.getContext()),i.addPanel(l)),this.showStats=t;let d=10,c=1e3;const m=()=>{const e=this.renderer.info.render.calls;e>d&&(d=e,setTimeout((()=>d=10),5e3)),r.update(e,d);const t=this.renderer.info.render.triangles;t>c&&(c=t,setTimeout((()=>c=1e3),5e3)),h.update(t,c)};performance.now();s.Ray.prototype.intersectTriangle;const p=[],u=[];let f=0;const g=new a,v=new a,x=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return void setTimeout((()=>x(t)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,i.begin();let a=(t*=.001)-f;if(f=t,g.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(V),t-=V;e(t)}else e(a);this.onLoopCallbacks.forEach((e=>e(a))),this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),v.equals(g)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender(),p.length=0,u.length=0;const h=_;if(this.camera.updateMatrixWorld(),N.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(N),this.scene.traverseVisible((e=>{if(null!=this.scene.environment&&(e instanceof o||e instanceof s.Sprite)&&function(e,t){if(Array.isArray(e.material))for(const i of e.material)t(i);else null!=e.material&&t(e.material)}(e,(e=>this.applyEnvMap(e))),(e instanceof o||e instanceof s.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[S])&&isObjectInFrustum(e,h)?(e.visible=!1,p.push(e),this.initDepthUniform(e.material),e.renderOrder=100):e instanceof T?(e.visible=!1,u.push(e)):(e instanceof o||e instanceof s.Sprite)&&function(e){if(e.material instanceof n)return e.material.transparent||e.material.alphaTest>0;if(Array.isArray(e.material))for(const t of e.material)if(t.transparent||t.alphaTest>0)return!0}(e)&&(e.visible=!1,e.layers.enable(5),u.push(e)),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[A])e.material.uniforms[A].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const i of e.material)i.uniforms&&null!=i.uniforms[A]&&(i.uniforms[A].value=t)})),p.length>0){if(this.scene.overrideMaterial=B,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}if(p.forEach((e=>e.visible=!0)),u.forEach((e=>e.visible=!0)),this.aoPass.enabled){if(this.scene.overrideMaterial=B,this.camera.layers.set(5),this.renderer.setRenderTarget(this.aoMaskDepthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.camera.layers.enableAll(),this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}try{!this.paused&&this.running&&(this.showStats&&l?.startQuery(),this.render(a),this.showStats&&l?.endQuery(),this.showStats&&m(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}i.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(x)}),1e3/this.fpsCap):requestAnimationFrame(x))};!0===this.options.enableXR?this.renderer.setAnimationLoop(x):requestAnimationFrame(x)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let s=0;s<e.length;s++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*s+this.insetMargin*s,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[s])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;const t=this.hasBloom();if(t||this.hadBloom){const e=this.scene.fog;this.scene.fog=null;const t=this.renderer.getClearColor(this.prevClearColor);this.renderer.setClearColor(0),this.scene.traverseVisible((e=>this.darkenNonBloomed(e))),this.bloomComposer.render(),this.scene.traverse((e=>this.restoreMaterial(e))),this.bloomHidden.forEach((e=>e.visible=!0)),this.bloomHidden.length=0,this.renderer.setClearColor(t),this.scene.fog=e}this.hadBloom=t,this.composer.render(e)}hasBloom(){return null!=j(this.scene,(e=>e instanceof o&&!0===e.material?.userData?.hasBloom))}darkenNonBloomed(e){(e instanceof o||e instanceof s.Sprite||e instanceof s.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)?(this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=E:e.visible=!1):"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof d&&(e.uniforms[S].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[W]&&e.uniforms[W].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof h&&(null!=e.uniforms[F]&&(e.uniforms[F].value=this.camera.near),null!=e.uniforms[D]&&(e.uniforms[D].value=this.camera.far)))}};z=e=t([P(),i("design:paramtypes",[HTMLElement,Object])],z);export{z as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const V=.05;R.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse((function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls)&&(e.visible=!1),null!=e.material){let t=!1;if(Array.isArray(e.material)){for(const i of e.material)if(null!=i.alphaTest&&i.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0&&(t=!0);t&&(e.visible=!1)}}))};const _=new s.Frustum,I=new s.Box3,N=new s.Matrix4;export function isObjectInFrustum(e,t){const i=I.setFromObject(e);return t.intersectsBox(i)}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -28,6 +28,7 @@ export declare class AssetResourceLoader {
|
|
28
28
|
private getUri;
|
29
29
|
getTexture(asset: Asset): Promise<Texture>;
|
30
30
|
private _getTextureLoader;
|
31
|
+
clearCache(asset: Asset): void;
|
31
32
|
private asyncMeshResults;
|
32
33
|
getMesh(asset: Asset, options?: GetMeshOptions): Promise<LoadedMesh>;
|
33
34
|
getAudio(asset: Asset): Promise<AudioBuffer>;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"asset-resource-loader.d.ts","sourceRoot":"","sources":["../../src/scene/asset-resource-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6G,QAAQ,EAAE,OAAO,EAA+B,MAAM,OAAO,CAAC;AAIlL,OAAO,EAAE,KAAK,EAAY,MAAM,YAAY,CAAC;AAG7C,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAM/D,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAQ;IACxB,OAAO,CAAC,KAAK,CAAgC;IAC7C,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,cAAc,CAAuB;IAC7C,OAAO,CAAC,SAAS,CAAuC;IACxD,OAAO,CAAC,SAAS,CAAsC;IACvD,OAAO,CAAC,SAAS,CAAsC;IACvD,OAAO,CAAC,aAAa,CAAyC;IAC9D,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,SAAS,CAA0C;IAC3D,OAAO,CAAC,UAAU,CAAs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|
+
import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as a,Mesh as i,Object3D as r,TextureLoader as n}from"three";import{GLTFLoader as o,MTLLoader as h,OBJLoader as c}from"three-stdlib";import{FBXLoader as l}from"three-stdlib";import{cloneMesh as d}from"../utils/mesh.js";import{pathJoin as m}from"../utils/files.js";import{Subject as p,firstValueFrom as u}from"rxjs";import{importCollisionShapes as f,isCollisionMesh as g}from"./collision/collision-shape-import.js";import*as w from"three";import{iterateMaterials as y}from"../utils/materials.js";import{BufferGeometryUtils as x,EXRLoader as L,KTX2Loader as M,TGALoader as b,UltraHDRLoader as A}from"three/examples/jsm/Addons.js";const S=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new a,this.glbLoader=new o(this.loadingManager),this.fbxLoader=new l(this.loadingManager),this.objLoader=new c(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new b(this.loadingManager),this.exrLoader=new L(this.loadingManager),this.hdrLoader=new A(this.loadingManager),this.ktx2Loader=new M(this.loadingManager),this._textureLoader=new w.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this.makeReady=new p,this.ready=u(this.makeReady),this.asyncMeshResults=new Map,this.collisionShapeCache=new Map,this.optimizedMeshes=new Set}initKtx2(e){this.initialisedKtx2=!0,this.ktx2Loader.setTranscoderPath("/assets/basis/"),this.ktx2Loader.detectSupport(e)}setDataDir(e){this.basePath=m(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){return m(this.basePath,e)+`?windowId=${getElectronArg("windowId")}`}async getTexture(e){return null==e||null==e.fileKey?null:(await this.ready,this.textureCache.has(e.id)||await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then((t=>(t.wrapS=v(e.texture?.wrapS),t.wrapT=v(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0,this.textureCache.set(e.id,t),t))),this.textureCache.get(e.id))}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:this.textureLoader}clearCache(e){"mesh"===e.type&&Array.from(this.cache.keys()).forEach((t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)}))}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!S.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new s,animations:[]};const a=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(a))try{this.asyncMeshResults.has(a)||this.asyncMeshResults.set(a,this.loadMesh(e).finally((()=>this.asyncMeshResults.delete(a)))),this.cache.set(a,await this.asyncMeshResults.get(a))}catch(e){return this.onError(e),{scene:new s,animations:[]}}const r=this.cache.get(a).scene,n=this.computeCollisionShapes(e,r);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(r);const o=d(r),h=this.cache.get(a).animations;o.traverse((e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())}));const c=new AssetMeshInstance;c.add(o),c.collisionShapes=n,c.animations=h;const l=e.receiveShadow??!0,m=e.castShadow??!1;return o.traverse((e=>{e.castShadow=m,e.receiveShadow=l})),{scene:c,animations:h}}async getAudio(e){return await this.ready,this.audioLoader.loadAsync(this.getUri(e.fileKey))}computeCollisionShapes(e,t){const s=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(s)||this.collisionShapeCache.set(s,f(t,e)),this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then((e=>(e.scene.traverse((e=>{g(e)&&(e.visible=!1)})),e.scene=function(e,t){let s=!1;if(t.traverseVisible((e=>{j.test(e.name)&&(s=!0)})),!s)return t;const a=new w.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(j);if(null!=t){const s=parseInt(t[1]);0===s?a.addLevel(e,0):console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`)}else i.push(...e.children)}return a}(0,e.scene),e)))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid);let s=!0,a=0,r=0;if(e.traverse((e=>{if(e instanceof i&&e.geometry instanceof t&&!g(e)){a++;const t=Object.keys(e.geometry.attributes).length;t!==r&&0!==r&&(s=!1),r=t}else(e instanceof w.SkinnedMesh||e instanceof w.Bone)&&(s=!1)})),a>1&&s){const s=[],a=[],r=[];e.updateWorldMatrix(!0,!0),e.traverse((e=>{e instanceof i&&e.geometry instanceof t&&!g(e)&&!Array.isArray(e.material)&&(e.updateWorldMatrix(!0,!0),s.push(e.geometry.clone().applyMatrix4(e.matrixWorld)),a.push(e.material),r.push(e))}));for(const e of r)e.removeFromParent();const n=x.mergeGeometries(s,!0),o=[];let h=0;e:for(const e of a){for(const t of o)if(t.m.id===e.id){t.indices.push(h),h++;continue e}o.push({m:e,indices:[h]}),h++}let c=0;for(const e of o){for(const t of e.indices)n.groups[t].materialIndex=c;c++}e.add(new i(n,o.map((e=>e.m))))}e.traverse((e=>{if(e instanceof i&&e.geometry instanceof t){const t=e.geometry;Array.isArray(e.material)&&t.groups.length>1&&t.groups.length>e.material.length&&x.mergeGroups(t)}}))}async loadByAsset(e){const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then((e=>({scene:e.scene,animations:e.animations})));case"fbx":return this.fbxLoader.loadAsync(t).then((e=>({scene:e,animations:e.animations})));case"obj":if(null!=e.materialLib){const t=new h;t.materialOptions={normalizeRGB:!1};const s=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(s)}return this.objLoader.loadAsync(t).then((e=>(C(e),e))).then((e=>({scene:e,animations:e.animations})))}}}function C(e){if(e instanceof i)for(const t of y(e.material))t instanceof w.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(C)}export class AssetMeshInstance extends r{}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find((e=>e.startsWith(t)));return s?.substring(t.length)}function v(e){switch(e){case"clamp":return w.ClampToEdgeWrapping;case"repeat":return w.RepeatWrapping;case"mirror":return w.MirroredRepeatWrapping}return w.RepeatWrapping}const j=/_LOD(\d+)$/;/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|