@hology/core 0.0.27 → 0.0.30

Sign up to get free protection for your applications and to get access to all the features.
Files changed (62) hide show
  1. package/dist/effects/vfx/behaviours.d.ts +26 -0
  2. package/dist/effects/vfx/behaviours.js +5 -0
  3. package/dist/effects/vfx/index.d.ts +2 -0
  4. package/dist/effects/vfx/index.js +5 -0
  5. package/dist/effects/vfx/initializsers.d.ts +44 -0
  6. package/dist/effects/vfx/initializsers.js +5 -0
  7. package/dist/effects/vfx/rates.d.ts +6 -0
  8. package/dist/effects/vfx/rates.js +5 -0
  9. package/dist/effects/vfx/vfx-actor.d.ts +27 -0
  10. package/dist/effects/vfx/vfx-actor.js +5 -0
  11. package/dist/effects/vfx/vfx-asset.d.ts +99 -0
  12. package/dist/effects/vfx/vfx-asset.js +5 -0
  13. package/dist/effects/vfx/vfx-defs.d.ts +207 -0
  14. package/dist/effects/vfx/vfx-defs.js +5 -0
  15. package/dist/effects/vfx/vfx-materializer.d.ts +19 -0
  16. package/dist/effects/vfx/vfx-materializer.js +5 -0
  17. package/dist/effects/vfx/vfx-param.d.ts +13 -0
  18. package/dist/effects/vfx/vfx-param.js +5 -0
  19. package/dist/effects/vfx/zones.d.ts +74 -0
  20. package/dist/effects/vfx/zones.js +5 -0
  21. package/dist/gameplay/actors/builtin/components/character/character-movement.d.ts +5 -1
  22. package/dist/gameplay/actors/builtin/components/character/character-movement.js +1 -1
  23. package/dist/gameplay/actors/camera/third-party-camera-component.js +1 -1
  24. package/dist/gameplay/index.d.ts +1 -0
  25. package/dist/gameplay/index.js +1 -1
  26. package/dist/gameplay/initiate.d.ts +3 -0
  27. package/dist/gameplay/initiate.js +1 -1
  28. package/dist/gameplay/input/input-service.d.ts +4 -0
  29. package/dist/gameplay/input/input-service.js +1 -1
  30. package/dist/gameplay/polyfill.d.ts +1 -0
  31. package/dist/gameplay/polyfill.js +5 -0
  32. package/dist/gameplay/services/asset-loader.d.ts +9 -4
  33. package/dist/gameplay/services/asset-loader.js +1 -1
  34. package/dist/gameplay/services/render.d.ts +3 -2
  35. package/dist/rendering.d.ts +1 -0
  36. package/dist/rendering.js +1 -1
  37. package/dist/scene/materializer.d.ts +20 -3
  38. package/dist/scene/materializer.js +1 -1
  39. package/dist/scene/model.d.ts +8 -2
  40. package/dist/scene/model.js +1 -1
  41. package/dist/scene/objects/shapes.d.ts +4 -2
  42. package/dist/scene/scene-data-service.js +1 -1
  43. package/dist/scene/sky.d.ts +3 -0
  44. package/dist/scene/sky.js +1 -1
  45. package/dist/shader/parameter.d.ts +2 -1
  46. package/dist/shader-nodes/effects.d.ts +8 -0
  47. package/dist/shader-nodes/effects.js +5 -0
  48. package/dist/shader-nodes/glsl-node.d.ts +16 -0
  49. package/dist/shader-nodes/glsl-node.js +5 -0
  50. package/dist/shader-nodes/index.d.ts +4 -0
  51. package/dist/shader-nodes/index.js +1 -1
  52. package/dist/shader-nodes/math.d.ts +2 -0
  53. package/dist/shader-nodes/math.js +5 -0
  54. package/dist/shader-nodes/particle.d.ts +6 -0
  55. package/dist/shader-nodes/particle.js +5 -0
  56. package/dist/shader-nodes/shapes.d.ts +3 -0
  57. package/dist/shader-nodes/shapes.js +5 -0
  58. package/dist/shader-nodes/voronoi.d.ts +5 -0
  59. package/dist/shader-nodes/voronoi.js +5 -0
  60. package/dist/utils/math.js +1 -1
  61. package/package.json +3 -2
  62. package/tsconfig.tsbuildinfo +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as i}from"tslib";import{ActionInput as e,AxisInput as s,RotationInput as o}from"../../../../../gameplay/input";import{PhysicsSystem as n,RayTestResult as a}from"../../../../../gameplay/services/physics/physics-system";import{MathUtils as l,Vector3 as r}from"three";import{ActorComponent as c,Component as h}from"../../../component";import{CharacterMovementMode as p}from"./modes";import{Quaternion as m,Vec3 as y}from"cannon-es";import{CapsuleCollisionShape as d}from"../../../../../scene/collision/collision-shape";import{lerp as u}from"three/src/math/MathUtils";import{takeUntil as g}from"rxjs";import{PhysicsBodyType as S}from"../../../../services/physics/physics-system";const f=new r,v=new r,w=1/30;let x=class extends c{get autoStepMinWidth(){return this.cc.autostepMinWidth()}set autoStepMinWidth(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),t,this.cc.autostepIncludesDynamicBodies())}get autoStepDynamicObjects(){return this.cc.autostepIncludesDynamicBodies()}set autoStepDynamicObjects(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),this.cc.autostepMinWidth(),t)}get autoStepMaxHeight(){return this.cc.autostepMaxHeight()}set autoStepMaxHeight(t){this.cc.enableAutostep(t,this.cc.autostepMinWidth(),this.cc.autostepIncludesDynamicBodies())}get snapToGround(){return this.cc.snapToGroundDistance()}set snapToGround(t){this.cc.enableSnapToGround(t)}constructor(t){super(),this.physicsSystem=t,this.directionInput=new s,this.jumpInput=new e,this.sprintInput=new e,this.rotationInput=new o,this.horizontalSpeed=0,this.maxSpeed=8,this.maxSpeedBackwards=8,this.maxSpeedSprint=12,this.jumpVelocity=7,this.fallingMovementControl=.5,this.fallingReorientation=!1,this.gravityOverride=null,this.colliderHeight=2,this.colliderRadius=.5,this.jumpInAir=!1,this.mass=50,this.allowSliding=!0,this.minSlopeSlideAngle=l.degToRad(70),this.maxSlopeClimbAngle=l.degToRad(70),this.applyImpulsesToDynamicBodies=!0,this.velocity=new r,this.mode=p.walking,this.isSprinting=!1,this.pressedJump=!1,this.rayTestResult=new a;const i=this.cc=this.physicsSystem.getCharacterController(.1);i.enableSnapToGround(.1),i.enableAutostep(0,.1,!1)}onInit(){const t=this.cc;t.setApplyImpulsesToDynamicBodies(this.applyImpulsesToDynamicBodies),t.setMinSlopeSlideAngle(this.minSlopeSlideAngle),t.setMaxSlopeClimbAngle(this.maxSlopeClimbAngle),t.setCharacterMass(this.mass),t.setSlideEnabled(this.allowSliding),this.physicsSystem.addActor(this.actor,[this.createCollisionShape()],{mass:0,type:S.kinematic,continousCollisionDetection:!0,friction:1}),this.rotationInput.rotation.copy(this.actor.rotation);let i=this.rotationInput.rotation.y;const e=new r,s=new r,o=new r,n=new r,a=new r,l=new r;let c=0,h=null;this.physicsSystem.beforeStep.pipe(g(this.disposed)).subscribe((m=>{m>w&&(m=w),this.pressedJump=this.jumpInput.activated,this.isSprinting=this.sprintInput.activated&&this.directionInput.vertical>=0;let y=i-this.rotationInput.rotation.y;i=this.rotationInput.rotation.y,o.copy(this.actor.position),n.set(-this.directionInput.vector.x,0,this.directionInput.vector.y).normalize();const d=n.z<0?this.maxSpeedBackwards:this.isSprinting?this.maxSpeedSprint:this.maxSpeed;l.copy(n).applyAxisAngle(I,this.rotationInput.rotation.y),this.mode===p.walking&&(0!==l.length()?(c=Math.min(d,c),c=u(c,d,4*m)):c=0,a.copy(l).multiplyScalar(c),this.pressedJump&&(this.mode=p.falling,this.velocity.copy(a),this.velocity.y=this.jumpVelocity),a.y=m*this.getEffectiveGravity()),this.mode===p.falling&&(this.pressedJump&&this.jumpInAir&&(this.mode=p.falling,this.velocity.copy(a),this.velocity.y=this.jumpVelocity),this.velocity.y+=m*this.getEffectiveGravity(),a.copy(this.velocity),a.add(l.clone().multiplyScalar(d*this.fallingMovementControl*m)),this.fallingReorientation&&a.applyAxisAngle(new r(0,1,0),-y)),s.copy(a).normalize(),e.copy(a),this.actor.rotation.y-=y,a.length(),f.copy(a).multiplyScalar(m),v.copy(this.physicsSystem.getActorComputedMovement(this.actor,t,f)),this.physicsSystem.setNextKinematicTranslation(this.actor,v);let g=function(t){if(t.numComputedCollisions()>0){const i=t.computedCollision(0);A.x=i.normal2.x,A.y=i.normal2.y,A.z=i.normal2.z;const e=A.angleTo(I);A.x=i.normal1.x,A.y=i.normal1.y,A.z=i.normal1.z;const s=A.angleTo(I);return!(e<100)&&s>t.minSlopeSlideAngle()}return!1}(t);!t.computedGrounded()||g?this.mode!==p.falling&&(null==h?h=performance.now():performance.now()-h>100&&(this.mode=p.falling,this.velocity.copy(e))):this.velocity.y<=0&&(this.mode,p.falling,this.mode=p.walking,this.velocity.y=0,h=null),this.mode,p.walking,this.horizontalSpeed=c}))}getWallDirection(t,i){const e=t.clone().negate().cross(I);return e.dot(i)<0?e.negate():e}moveTo(t){this.actor.position.copy(t),this.physicsSystem.updateActorTransform(this.actor)}getEffectiveGravity(){var t;return null!==(t=this.gravityOverride)&&void 0!==t?t:this.physicsSystem.getGravity().y}get isGrounded(){return this.rayTestResult.hasHit}createCollisionShape(){const t=new d(this.colliderHeight,this.colliderRadius);return t.offset.y=this.colliderRadius+this.colliderHeight/2,t}step(t){}performMovement(t){}};x=t([h({inEditor:!1}),i("design:paramtypes",[n])],x);export{x as CharacterMovementComponent};const I=new r(0,1,0),A=new r;
1
+ import{__decorate as t,__metadata as i}from"tslib";import{ActionInput as o,AxisInput as e,RotationInput as s}from"../../../../../gameplay/input";import{PhysicsSystem as n,RayTestResult as r}from"../../../../../gameplay/services/physics/physics-system";import{MathUtils as a,Vector3 as l}from"three";import{ActorComponent as c,Component as h}from"../../../component";import{CharacterMovementMode as p}from"./modes";import{Quaternion as m,Vec3 as y}from"cannon-es";import{CapsuleCollisionShape as u}from"../../../../../scene/collision/collision-shape";import{lerp as d}from"three/src/math/MathUtils";import{takeUntil as g}from"rxjs";import{PhysicsBodyType as S}from"../../../../services/physics/physics-system";import{RootMotionClip as f}from"../../../../../gameplay/animation/root-motion";const v=new l,M=new l,A=1/30;let w=class extends c{get autoStepMinWidth(){return this.cc.autostepMinWidth()}set autoStepMinWidth(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),t,this.cc.autostepIncludesDynamicBodies())}get autoStepDynamicObjects(){return this.cc.autostepIncludesDynamicBodies()}set autoStepDynamicObjects(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),this.cc.autostepMinWidth(),t)}get autoStepMaxHeight(){return this.cc.autostepMaxHeight()}set autoStepMaxHeight(t){this.cc.enableAutostep(t,this.cc.autostepMinWidth(),this.cc.autostepIncludesDynamicBodies())}get snapToGround(){return this.cc.snapToGroundDistance()}set snapToGround(t){this.cc.enableSnapToGround(t)}constructor(t){super(),this.physicsSystem=t,this.directionInput=new e,this.jumpInput=new o,this.sprintInput=new o,this.rotationInput=new s,this.horizontalSpeed=0,this.maxSpeed=8,this.maxSpeedBackwards=8,this.maxSpeedSprint=12,this.jumpVelocity=7,this.fallingMovementControl=.5,this.fallingReorientation=!1,this.gravityOverride=null,this.colliderHeight=2,this.colliderRadius=.5,this.jumpInAir=!1,this.mass=50,this.allowSliding=!0,this.minSlopeSlideAngle=a.degToRad(70),this.maxSlopeClimbAngle=a.degToRad(70),this.applyImpulsesToDynamicBodies=!0,this.velocity=new l,this.mode=p.walking,this.isSprinting=!1,this.pressedJump=!1,this.rayTestResult=new r,this.resetRootMotion=!1;const i=this.cc=this.physicsSystem.getCharacterController(.1);i.enableSnapToGround(.1),i.enableAutostep(0,.1,!1)}onInit(){const t=this.cc;t.setApplyImpulsesToDynamicBodies(this.applyImpulsesToDynamicBodies),t.setMinSlopeSlideAngle(this.minSlopeSlideAngle),t.setMaxSlopeClimbAngle(this.maxSlopeClimbAngle),t.setCharacterMass(this.mass),t.setSlideEnabled(this.allowSliding),this.physicsSystem.addActor(this.actor,[this.createCollisionShape()],{mass:0,type:S.kinematic,continousCollisionDetection:!0,friction:1}),this.rotationInput.rotation.copy(this.actor.rotation);let i=this.rotationInput.rotation.y;const o=new l,e=new l,s=new l,n=new l,r=new l,a=new l;let c=0,h=null;const m=new l,y=new l,u=new l,w=new l;this.physicsSystem.beforeStep.pipe(g(this.disposed)).subscribe((g=>{if(null!=this.rootMotionAction){if(this.rootMotionAction.getClip()instanceof f){const t=this.rootMotionInterpolant;this.resetRootMotion&&(m.fromArray(t.evaluate(0)),this.resetRootMotion=!1),w.fromArray(t.evaluate(this.rootMotionAction.time)),y.subVectors(w,m),m.copy(w),this.rootMotionAction.getRoot().getWorldScale(u),y.multiply(u)}}g>A&&(g=A);const S=null!=this.rootMotionAction&&this.rootMotionAction.enabled&&0!=y.length();this.pressedJump=this.jumpInput.activated,this.isSprinting=this.sprintInput.activated&&this.directionInput.vertical>=0;let b=i-this.rotationInput.rotation.y;i=this.rotationInput.rotation.y,s.copy(this.actor.position),n.set(-this.directionInput.vector.x,0,this.directionInput.vector.y).normalize();const T=n.z<0?this.maxSpeedBackwards:this.isSprinting?this.maxSpeedSprint:this.maxSpeed;a.copy(n).applyAxisAngle(x,this.rotationInput.rotation.y),this.mode===p.walking?(0!==a.length()?(c=Math.min(T,c),c=d(c,T,4*g)):c=0,r.copy(a).multiplyScalar(c),this.pressedJump&&(this.mode=p.falling,this.velocity.copy(r),this.velocity.y=this.jumpVelocity),r.y=g*this.getEffectiveGravity()):this.mode===p.falling&&(this.pressedJump&&this.jumpInAir&&(this.mode=p.falling,this.velocity.copy(r),this.velocity.y=this.jumpVelocity),this.velocity.y+=g*this.getEffectiveGravity(),r.copy(this.velocity),r.add(a.clone().multiplyScalar(T*this.fallingMovementControl*g)),this.fallingReorientation&&r.applyAxisAngle(new l(0,1,0),-b)),e.copy(r).normalize(),o.copy(r),this.actor.rotation.y-=b,r.length(),S?(y.applyAxisAngle(x,this.actor.rotation.y),y.y+=g*this.getEffectiveGravity(),v.copy(y)):v.copy(r).multiplyScalar(g),M.copy(this.physicsSystem.getActorComputedMovement(this.actor,t,v)),this.physicsSystem.setNextKinematicTranslation(this.actor,M);let C=function(t){if(t.numComputedCollisions()>0){const i=t.computedCollision(0);I.x=i.normal2.x,I.y=i.normal2.y,I.z=i.normal2.z;const o=I.angleTo(x);I.x=i.normal1.x,I.y=i.normal1.y,I.z=i.normal1.z;const e=I.angleTo(x);return!(o<100)&&e>t.minSlopeSlideAngle()}return!1}(t);S||(!t.computedGrounded()||C?this.mode!==p.falling&&(null==h?h=performance.now():performance.now()-h>100&&(this.mode=p.falling,this.velocity.copy(o))):this.velocity.y<=0&&(this.mode,p.falling,this.mode=p.walking,this.velocity.y=0,h=null)),this.mode,p.walking,this.horizontalSpeed=c}))}setRootMotionAction(t){const i=null==t?void 0:t.getClip();if(i instanceof f){this.rootMotionAction=t,this.resetRootMotion=!0;const o=[];this.rootMotionInterpolant=i.motionTrack.InterpolantFactoryMethodSmooth(o)}}getWallDirection(t,i){const o=t.clone().negate().cross(x);return o.dot(i)<0?o.negate():o}moveTo(t){this.actor.position.copy(t),this.physicsSystem.updateActorTransform(this.actor)}getEffectiveGravity(){var t;return null!==(t=this.gravityOverride)&&void 0!==t?t:this.physicsSystem.getGravity().y}get isGrounded(){return this.rayTestResult.hasHit}createCollisionShape(){const t=new u(this.colliderHeight,this.colliderRadius);return t.offset.y=this.colliderRadius+this.colliderHeight/2,t}step(t){}performMovement(t){}};w=t([h({inEditor:!1}),i("design:paramtypes",[n])],w);export{w as CharacterMovementComponent};const x=new l(0,1,0),I=new l;
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{__awaiter as t,__decorate as e,__metadata as s}from"tslib";import{ActorComponent as i,Component as o,Attach as n}from"../component";import{CameraComponent as h}from"./camera-component";import{Vector3 as a}from"three";import{ViewController as r}from"../../services/render";import{DecimalInput as c,RestrictedRotationInput as m}from"../../input";import{PhysicsSystem as d,RayTestResult as l}from"../../services/physics/physics-system";import{clamp as u,lerp as p}from"three/src/math/MathUtils";let f=class extends i{constructor(t,e){super(),this.viewController=t,this.physicsSystem=e,this.distance=9,this.minDistance=1.5,this.maxDistance=this.distance,this.height=3,this.offsetX=-1,this.offsetZ=1.5,this.autoActivate=!0,this.bounceBackSpeed=5,this.collisionCheckRadius=.5,this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.rotationInput=new m(-Math.PI/4,Math.PI/2-.7),this.zoomInput=new c(1,0,1),this.offset=new a,this.lookAtOffset=new a(this.offsetX,0,this.offsetZ),this.isMouseLocked=!1,this.canvas=null,this.pointerLockInactivatedAt=null,this.onMouseDown=t=>{this.isMouseLocked||this.hideCursor()},this.onKeyDown=t=>{"Escape"===t.key&&this.showCursor()},this.onPointerLockChange=()=>{null!=document.pointerLockElement||null!=document.mozPointerLockElement||this.showCursor()}}onInit(){return t(this,void 0,void 0,(function*(){this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.autoActivate&&this.viewController.setCamera(this.camera.instance);const t=this.element;t.addEventListener("mousedown",this.onMouseDown),t.addEventListener("keydown",this.onKeyDown),document.addEventListener("pointerlockchange",this.onPointerLockChange,!1),this.disposed.subscribe((()=>{t.removeEventListener("mousedown",this.onMouseDown),t.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("pointerlockchange",this.onPointerLockChange,!1)}))}))}onLateUpdate(t){this.setFromRotation(t)}get element(){return this.viewController.htmlElement}hideCursor(){null!=this.pointerLockInactivatedAt&&performance.now()-this.pointerLockInactivatedAt<1600||(this.element.style.cursor="none",null==this.canvas&&(this.canvas=this.element.getElementsByTagName("canvas")[0]),this.canvas&&(this.canvas.requestPointerLock(),this.isMouseLocked=!0))}showCursor(){this.pointerLockInactivatedAt=performance.now(),this.element.style.cursor="default",window.document.exitPointerLock(),this.isMouseLocked=!1}setFromRotation(t){this.checkForCollision(t);const e=u(Math.min(this.restrictedDistance,this.distance),Math.min(this.minDistance,this.restrictedDistance),Math.max(this.distance*this.zoomInput.value,this.minDistance)),s=Math.cos(this.rotationInput.rotation.x)*e;this.offset.x=Math.sin(this.rotationInput.rotation.y)*s,this.offset.y=Math.sin(this.rotationInput.rotation.x)*e+2,this.offset.z=Math.cos(this.rotationInput.rotation.y)*-s,this.offset.add(this.lookAtOffset),this.updateCameraPosition()}checkForCollision(t){const e=this.getLookAtPosition(),s=v;let i=!1,o=this.distance;const n=new l,h=this.camera.instance.getWorldPosition(y);for(let t=-1;t<=1;t++){const a=w.subVectors(h,e);s.copy(h).add(a.multiplyScalar(1.2)),s.x+=t*this.collisionCheckRadius,this.physicsSystem.rayTest(e,s,n,{debugLifetime:0,excludeActor:this.actor}),n.hasHit&&n.distance<this.distance&&(o=Math.min(n.distance,o),i||(i=n.hasHit))}i||(this.restrictedDistance=p(this.restrictedDistance,this.distance,u(this.bounceBackSpeed*t,0,1)))}getLookAtPosition(){const t=k;return t.set(0,0,0),t.y=this.height,t.add(this.lookAtOffset),t.applyMatrix4(this.actor.object.matrixWorld),t}updateCameraPosition(){this.camera.instance.position.copy(this.offset);const t=this.getLookAtPosition();this.camera.instance.lookAt(t)}};e([n(),s("design:type",h)],f.prototype,"camera",void 0),f=e([o(),s("design:paramtypes",[r,d])],f);export{f as ThirdPartyCameraComponent};const k=new a,v=new a,w=(new a,new a),y=new a;
1
+ import{__awaiter as t,__decorate as e,__metadata as s}from"tslib";import{ActorComponent as i,Component as o,Attach as n}from"../component";import{CameraComponent as h}from"./camera-component";import{Vector3 as a}from"three";import{ViewController as r}from"../../services/render";import{DecimalInput as c,RestrictedRotationInput as m}from"../../input";import{PhysicsSystem as d,RayTestResult as l}from"../../services/physics/physics-system";import{clamp as u,lerp as p}from"three/src/math/MathUtils";let f=class extends i{constructor(t,e){super(),this.viewController=t,this.physicsSystem=e,this.distance=9,this.minDistance=1.5,this.maxDistance=this.distance,this.height=3,this.offsetX=-1,this.offsetZ=1.5,this.autoActivate=!0,this.bounceBackSpeed=5,this.collisionCheckRadius=.5,this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.rotationInput=new m(-Math.PI/4,Math.PI/2-.7),this.zoomInput=new c(1,0,1),this.offset=new a,this.lookAtOffset=new a(this.offsetX,0,this.offsetZ),this.isMouseLocked=!1,this.canvas=null,this.pointerLockInactivatedAt=null,this.onMouseDown=t=>{this.isMouseLocked||this.hideCursor()},this.onKeyDown=t=>{"Escape"===t.key&&this.showCursor()},this.onPointerLockChange=()=>{null!=document.pointerLockElement||null!=document.mozPointerLockElement||this.showCursor()}}onInit(){return t(this,void 0,void 0,(function*(){this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.autoActivate&&this.viewController.setCamera(this.camera.instance);const t=this.element;null!=document.body.requestPointerLock&&(t.addEventListener("mousedown",this.onMouseDown),t.addEventListener("keydown",this.onKeyDown),document.addEventListener("pointerlockchange",this.onPointerLockChange,!1),this.disposed.subscribe((()=>{t.removeEventListener("mousedown",this.onMouseDown),t.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("pointerlockchange",this.onPointerLockChange,!1)})))}))}onLateUpdate(t){this.setFromRotation(t)}get element(){return this.viewController.htmlElement}hideCursor(){null!=this.pointerLockInactivatedAt&&performance.now()-this.pointerLockInactivatedAt<1600||(this.element.style.cursor="none",null==this.canvas&&(this.canvas=this.element.getElementsByTagName("canvas")[0]),this.canvas&&(this.canvas.requestPointerLock(),this.isMouseLocked=!0))}showCursor(){this.pointerLockInactivatedAt=performance.now(),this.element.style.cursor="default",window.document.exitPointerLock(),this.isMouseLocked=!1}setFromRotation(t){this.checkForCollision(t);const e=u(Math.min(this.restrictedDistance,this.distance),Math.min(this.minDistance,this.restrictedDistance),Math.max(this.distance*this.zoomInput.value,this.minDistance)),s=Math.cos(this.rotationInput.rotation.x)*e;this.offset.x=Math.sin(this.rotationInput.rotation.y)*s,this.offset.y=Math.sin(this.rotationInput.rotation.x)*e+2,this.offset.z=Math.cos(this.rotationInput.rotation.y)*-s,this.offset.add(this.lookAtOffset),this.updateCameraPosition()}checkForCollision(t){const e=this.getLookAtPosition(),s=v;let i=!1,o=this.distance;const n=new l,h=this.camera.instance.getWorldPosition(y);for(let t=-1;t<=1;t++){const a=w.subVectors(h,e);s.copy(h).add(a.multiplyScalar(1.2)),s.x+=t*this.collisionCheckRadius,this.physicsSystem.rayTest(e,s,n,{debugLifetime:0,excludeActor:this.actor}),n.hasHit&&n.distance<this.distance&&(o=Math.min(n.distance,o),i||(i=n.hasHit))}i||(this.restrictedDistance=p(this.restrictedDistance,this.distance,u(this.bounceBackSpeed*t,0,1)))}getLookAtPosition(){const t=k;return t.set(0,0,0),t.y=this.height,t.add(this.lookAtOffset),t.applyMatrix4(this.actor.object.matrixWorld),t}updateCameraPosition(){this.camera.instance.position.copy(this.offset);const t=this.getLookAtPosition();this.camera.instance.lookAt(t)}};e([n(),s("design:type",h)],f.prototype,"camera",void 0),f=e([o(),s("design:paramtypes",[r,d])],f);export{f as ThirdPartyCameraComponent};const k=new a,v=new a,w=(new a,new a),y=new a;
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -12,3 +12,4 @@ export { Container as DIContainer } from 'typedi';
12
12
  export * from './animation/anim-sm';
13
13
  export * from './animation/root-motion';
14
14
  export * from './services/asset-loader';
15
+ export { VisualEffect } from '../effects/vfx/vfx-param';
@@ -1,4 +1,4 @@
1
- import"reflect-metadata";export*from"./initiate";export*from"./inject";export{Service,Inject}from"typedi";export{ActorFactory}from"./actors/factory";export{Actor,BaseActor}from"./actors/actor";export{Component,ActorComponent,attach,Attach}from"./actors/component";export*from"./services/world";export*from"./services/render";export*from"./services/physics/physics-system";export{Container as DIContainer}from"typedi";export*from"./animation/anim-sm";export*from"./animation/root-motion";export*from"./services/asset-loader";
1
+ import"reflect-metadata";export*from"./initiate";export*from"./inject";export{Service,Inject}from"typedi";export{ActorFactory}from"./actors/factory";export{Actor,BaseActor}from"./actors/actor";export{Component,ActorComponent,attach,Attach}from"./actors/component";export*from"./services/world";export*from"./services/render";export*from"./services/physics/physics-system";export{Container as DIContainer}from"typedi";export*from"./animation/anim-sm";export*from"./animation/root-motion";export*from"./services/asset-loader";export{VisualEffect}from"../effects/vfx/vfx-param";
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -12,6 +12,9 @@ export type InitiateGameConfig = {
12
12
  actors: {
13
13
  [name: string]: ActorType;
14
14
  };
15
+ xr?: {
16
+ enabled: boolean;
17
+ };
15
18
  };
16
19
  export declare function initiateGame<T_Game>(gameClass: GameClass<T_Game>, config: InitiateGameConfig): HologyRuntime<T_Game>;
17
20
  export declare abstract class GameInstance {
@@ -1,4 +1,4 @@
1
- import{__awaiter as t}from"tslib";import e from"typedi";import{loadScene as n}from"../scene/bootstrap";import{ActorFactory as o}from"./actors/factory";import{World as s}from"./services/world";import{ViewController as r}from"./services/render";import{RenderingView as i}from"../rendering";import{PhysicsSystem as a}from"./services/physics/physics-system";import{MeshComponent as c}from"./actors/builtin/components/mesh-component";import{activeContainerInstance as m}from"./actors/internal/container-map";import{InputService as d}from"./input";import{RuntimeBackendService as l}from"../scene/runtime-backend-service";import{RuntimeAssetsService as p}from"../scene/runtime-asset-service";import{AssetResourceLoader as h}from"../scene/asset-resource-loader";import{AssetLoader as u}from"./services/asset-loader";export function initiateGame(d,f){if(0!=f.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(r);const g=e.of("default"),w=new HologyRuntime(g),v=new o(g,{inEditor:!1});var y;e.set(o,v),y=f.element,Object.assign(y.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%"});const I=new i(f.element);I.renderer.shadowMap.autoUpdate=!0,e.set(i,I);const S=new r(I);e.set(r,S);const b=new s(e.get(o));e.set(s,b);const D=new l(f.dataDir),x=new p(D),G=new h;G.setDataDir(f.dataDir);const H=new u(G,x);return e.set(u,H),(()=>{t(this,void 0,void 0,(function*(){const t=e.get(a);if(yield t.start(),w.isShutdown)return;const{scene:o,actors:s}=yield n(I,f.sceneName,f.dataDir,f.shaders,f.actors,v,D,x,G);if(b.scene=o,w.isShutdown)return void I.stop();e.import([c]);for(const t of s)b.addActor(t);t.addFromScene(o),I.loop((t=>{})),w.status=5,m.value=g,g.remove(d),g.set({id:d,type:d});const r=g.get(d);m.value=null,w.gameInstance=r,r instanceof GameInstance&&r.onStart(),w._resolver(!0)}))})(),w}export class GameInstance{onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(t){this.containerInstance=t,this.status=0,this.isShutdown=!1,this.ready=new Promise((t=>{this._resolver=t}))}getWorld(){return this.containerInstance.get(s)}getService(t){return this.containerInstance.get(t)}shutdown(){this.isShutdown=!0,this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(d).stop();const t=this.containerInstance.get(i);null==t||t.stop();for(const t of this.getWorld().actors)this.getWorld().removeActor(t);this.containerInstance.get(a).stop(),this.containerInstance.reset()}}
1
+ import{__awaiter as e}from"tslib";import t from"typedi";import{loadScene as n}from"../scene/bootstrap";import{ActorFactory as o}from"./actors/factory";import{World as s}from"./services/world";import{ViewController as r}from"./services/render";import{RenderingView as i}from"../rendering";import{PhysicsSystem as a}from"./services/physics/physics-system";import{MeshComponent as c}from"./actors/builtin/components/mesh-component";import{activeContainerInstance as m}from"./actors/internal/container-map";import{InputService as l}from"./input";import{RuntimeBackendService as d}from"../scene/runtime-backend-service";import{RuntimeAssetsService as p}from"../scene/runtime-asset-service";import{AssetResourceLoader as h}from"../scene/asset-resource-loader";import{AssetLoader as u}from"./services/asset-loader";import{polyfillClient as f}from"./polyfill";export function initiateGame(l,g){var w;if(f(),0!=g.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;t.has(r);const v=t.of("default"),y=new HologyRuntime(v),I=new o(v,{inEditor:!1});var S;t.set(o,I),S=g.element,Object.assign(S.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%"});const b=new i(g.element,{enableXR:!0===(null===(w=g.xr)||void 0===w?void 0:w.enabled)});b.renderer.shadowMap.autoUpdate=!0,t.set(i,b);const x=new r(b);t.set(r,x);const D=new s(t.get(o));t.set(s,D);const G=new d(g.dataDir),H=new p(G),R=new h;R.setDataDir(g.dataDir);const W=Object.entries(g.shaders).map((([e,t])=>({name:e,type:t}))),j=new u(R,H,W);return t.set(u,j),(()=>{e(this,void 0,void 0,(function*(){const e=t.get(a);if(yield e.start(),y.isShutdown)return;const{scene:o,actors:s}=yield n(b,g.sceneName,g.dataDir,g.shaders,g.actors,I,G,H,R);if(D.scene=o,y.isShutdown)return void b.stop();t.import([c]);for(const e of s)D.addActor(e);e.addFromScene(o),b.loop((e=>{})),y.status=5,m.value=v,v.remove(l),v.set({id:l,type:l});const r=v.get(l);m.value=null,y.gameInstance=r,r instanceof GameInstance&&r.onStart(),y._resolver(!0)}))})(),y}export class GameInstance{onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(e){this.containerInstance=e,this.status=0,this.isShutdown=!1,this.ready=new Promise((e=>{this._resolver=e}))}getWorld(){return this.containerInstance.get(s)}getService(e){return this.containerInstance.get(e)}shutdown(){this.isShutdown=!0,this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(l).stop();const e=this.containerInstance.get(i);null==e||e.stop();for(const e of this.getWorld().actors)this.getWorld().removeActor(e);this.containerInstance.get(a).stop(),this.containerInstance.reset()}}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -9,10 +9,13 @@ export declare class InputService {
9
9
  private toggleCallbacks;
10
10
  private keybinds;
11
11
  private mousebinds;
12
+ private touchmoveBinds;
12
13
  private wheelbinds;
13
14
  private onKeyDown;
14
15
  private onKeyUp;
15
16
  private onMouseMove;
17
+ private prevTouchEvent;
18
+ private onTouchMove;
16
19
  private onWheel;
17
20
  start(): void;
18
21
  stop(): void;
@@ -25,6 +28,7 @@ export declare class InputService {
25
28
  unbind(name: ActionIdentifier): void;
26
29
  setKeybind(name: ActionIdentifier, key: Keybind): void;
27
30
  setMousebind(name: ActionIdentifier, mouse: Mousebind): void;
31
+ setTouchMoveBind(name: ActionIdentifier, mouse: Mousebind): void;
28
32
  setWheelbind(name: ActionIdentifier, mouse: Wheelbind): void;
29
33
  removeKeybind(name: ActionIdentifier): void;
30
34
  removeMousebind(name: ActionIdentifier): void;
@@ -1,4 +1,4 @@
1
- import{__decorate as e}from"tslib";import{Service as t}from"typedi";let s=class{constructor(){this.inputs=new Map,this.deltaCallbacks=new Map,this.toggleCallbacks=new Map,this.keybinds=new Map,this.mousebinds=new Map,this.wheelbinds=new Map,this.onKeyDown=e=>{this.keybinds.forEach(((t,s)=>{for(const n of t)n.test(e)&&(this.inputs.has(s)?this.inputs.get(s)(!0):this.toggleCallbacks.has(s)?this.toggleCallbacks.get(s)(!0):console.warn("No input callback for registered for key bind "+n.display()))}))},this.onKeyUp=e=>{this.keybinds.forEach(((t,s)=>{for(const n of t)n.test(e)&&(this.inputs.has(s)?this.inputs.get(s)(!1):this.toggleCallbacks.has(s)?this.toggleCallbacks.get(s)(!1):console.warn("No input callback for registered for key bind "+n.display()))}))},this.onMouseMove=e=>{(null!=document.pointerLockElement||null!=document.mozPointerLockElement)&&this.mousebinds.forEach(((t,s)=>{var n;const i=null!==(n=this.inputs.get(s))&&void 0!==n?n:this.deltaCallbacks.get(s);if(null!=i)switch(t.axis){case"x":i(e.movementX*t.multiplier);break;case"y":i(e.movementY*t.multiplier)}else console.warn("No input callback for registered for mouse bind "+t.axis)}))},this.onWheel=e=>{this.wheelbinds.forEach(((t,s)=>{var n;const i=null!==(n=this.inputs.get(s))&&void 0!==n?n:this.deltaCallbacks.get(s);null!=i?i(e.deltaY*t.multiplier):console.warn("No input callback for registered for wheel bind")}))}}start(){document.addEventListener("keydown",this.onKeyDown),document.addEventListener("mousedown",this.onKeyDown),document.addEventListener("mouseup",this.onKeyUp),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("wheel",this.onWheel)}stop(){document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("mousedown",this.onKeyDown),document.removeEventListener("mouseup",this.onKeyUp),document.removeEventListener("keyup",this.onKeyUp),document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("wheel",this.onWheel)}bind(e,t){this.inputs.set(e,t)}bindToggle(e,t){this.toggleCallbacks.set(e,t)}bindDelta(e,t){this.deltaCallbacks.set(e,t)}unbind(e){this.inputs.delete(e),this.toggleCallbacks.delete(e),this.deltaCallbacks.delete(e)}setKeybind(e,t){this.keybinds.has(e)||this.keybinds.set(e,[]),this.keybinds.get(e).push(t)}setMousebind(e,t){this.mousebinds.set(e,t)}setWheelbind(e,t){this.wheelbinds.set(e,t)}removeKeybind(e){this.keybinds.delete(e)}removeMousebind(e){this.mousebinds.delete(e)}removeWheelbind(e){this.wheelbinds.delete(e)}};s=e([t()],s);export{s as InputService};
1
+ import{__decorate as e}from"tslib";import{Service as t}from"typedi";let s=class{constructor(){this.inputs=new Map,this.deltaCallbacks=new Map,this.toggleCallbacks=new Map,this.keybinds=new Map,this.mousebinds=new Map,this.touchmoveBinds=new Map,this.wheelbinds=new Map,this.onKeyDown=e=>{this.keybinds.forEach(((t,s)=>{for(const n of t)n.test(e)&&(this.inputs.has(s)?this.inputs.get(s)(!0):this.toggleCallbacks.has(s)?this.toggleCallbacks.get(s)(!0):console.warn("No input callback for registered for key bind "+n.display()))}))},this.onKeyUp=e=>{this.keybinds.forEach(((t,s)=>{for(const n of t)n.test(e)&&(this.inputs.has(s)?this.inputs.get(s)(!1):this.toggleCallbacks.has(s)?this.toggleCallbacks.get(s)(!1):console.warn("No input callback for registered for key bind "+n.display()))}))},this.onMouseMove=e=>{(null!=document.pointerLockElement||null!=document.mozPointerLockElement)&&this.mousebinds.forEach(((t,s)=>{var n;const i=null!==(n=this.inputs.get(s))&&void 0!==n?n:this.deltaCallbacks.get(s);if(null!=i)switch(t.axis){case"x":i(e.movementX*t.multiplier);break;case"y":i(e.movementY*t.multiplier)}else console.warn("No input callback for registered for mouse bind "+t.axis)}))},this.onTouchMove=e=>{const t=e.touches[0];null!=t&&(null!=this.prevTouchEvent&&t.identifier===this.prevTouchEvent.identifier?(this.touchmoveBinds.forEach(((e,s)=>{var n;const i=null!==(n=this.inputs.get(s))&&void 0!==n?n:this.deltaCallbacks.get(s);if(null!=i)switch(e.axis){case"x":i((t.clientX-this.prevTouchEvent.clientX)*e.multiplier);break;case"y":i((t.clientY-this.prevTouchEvent.clientY)*e.multiplier)}else console.warn("No input callback for registered for mouse bind "+e.axis)})),this.prevTouchEvent=t):this.prevTouchEvent=e.touches[0])},this.onWheel=e=>{this.wheelbinds.forEach(((t,s)=>{var n;const i=null!==(n=this.inputs.get(s))&&void 0!==n?n:this.deltaCallbacks.get(s);null!=i?i(e.deltaY*t.multiplier):console.warn("No input callback for registered for wheel bind")}))}}start(){document.addEventListener("keydown",this.onKeyDown),document.addEventListener("mousedown",this.onKeyDown),document.addEventListener("mouseup",this.onKeyUp),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("touchmove",this.onTouchMove),document.addEventListener("wheel",this.onWheel)}stop(){document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("mousedown",this.onKeyDown),document.removeEventListener("mouseup",this.onKeyUp),document.removeEventListener("keyup",this.onKeyUp),document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("touchmove",this.onTouchMove),document.removeEventListener("wheel",this.onWheel)}bind(e,t){this.inputs.set(e,t)}bindToggle(e,t){this.toggleCallbacks.set(e,t)}bindDelta(e,t){this.deltaCallbacks.set(e,t)}unbind(e){this.inputs.delete(e),this.toggleCallbacks.delete(e),this.deltaCallbacks.delete(e)}setKeybind(e,t){this.keybinds.has(e)||this.keybinds.set(e,[]),this.keybinds.get(e).push(t)}setMousebind(e,t){this.mousebinds.set(e,t)}setTouchMoveBind(e,t){this.touchmoveBinds.set(e,t)}setWheelbind(e,t){this.wheelbinds.set(e,t)}removeKeybind(e){this.keybinds.delete(e)}removeMousebind(e){this.mousebinds.delete(e)}removeWheelbind(e){this.wheelbinds.delete(e)}};s=e([t()],s);export{s as InputService};
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -0,0 +1 @@
1
+ export declare function polyfillClient(): void;
@@ -0,0 +1,5 @@
1
+ export function polyfillClient(){window.requestIdleCallback=window.requestIdleCallback||function(n){const e=Date.now();return setTimeout((function(){n({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-e))}})}),1)},window.cancelIdleCallback=window.cancelIdleCallback||function(n){clearTimeout(n)}}
2
+ /*
3
+ * Copyright (©) 2023. All rights reserved.
4
+ * See the LICENSE.md file for details.
5
+ */
@@ -1,10 +1,13 @@
1
- import { AssetResourceLoader } from "../../scene/asset-resource-loader";
1
+ import { AssetResourceLoader, LoadedMesh } from "../../scene/asset-resource-loader";
2
2
  import { AssetsProvider } from "../../scene/assets-provider";
3
3
  import { AssetId } from "../../scene/model";
4
4
  import { GLTF } from "three-stdlib";
5
+ import { Material } from "three";
6
+ import { ShaderImpl } from "../../shader/shader";
5
7
  export declare class AssetLoader {
6
8
  protected assetResourceLoader: AssetResourceLoader;
7
9
  protected assetService: AssetsProvider;
10
+ shaders: ShaderImpl[];
8
11
  protected baseUrl: string;
9
12
  protected urlSuffix: string;
10
13
  private loadingManager;
@@ -15,7 +18,7 @@ export declare class AssetLoader {
15
18
  private tgaLoader;
16
19
  private textureLoader;
17
20
  private audioLoader;
18
- constructor(assetResourceLoader: AssetResourceLoader, assetService: AssetsProvider);
21
+ constructor(assetResourceLoader: AssetResourceLoader, assetService: AssetsProvider, shaders: ShaderImpl[]);
19
22
  /**
20
23
  * @param filePath
21
24
  * @returns A path to the file that works both in the editor and
@@ -29,6 +32,8 @@ export declare class AssetLoader {
29
32
  * @param filePath A path relative to your website's base url. Always use backslash for directory separetors, even in Windows.
30
33
  */
31
34
  geGltfAtPath(filePath: string): Promise<GLTF>;
32
- getModelByAssetName(name: string): Promise<import("../../scene/asset-resource-loader").LoadedMesh>;
33
- getModelByAssetId(id: AssetId): Promise<import("../../scene/asset-resource-loader").LoadedMesh>;
35
+ getModelByAssetName(name: string): Promise<LoadedMesh>;
36
+ getModelByAssetId(id: AssetId): Promise<LoadedMesh>;
37
+ getTextureByAssetId(id: AssetId): Promise<THREE.Texture>;
38
+ getMaterialByAssetId(id: AssetId): Promise<Material>;
34
39
  }
@@ -1,4 +1,4 @@
1
- import{__awaiter as e,__decorate as t,__metadata as s}from"tslib";import{AssetResourceLoader as r}from"../../scene/asset-resource-loader";import{FBXLoader as o,GLTFLoader as i,MTLLoader as a,OBJLoader as n,TGALoader as d}from"three-stdlib";import{AudioLoader as l,LoadingManager as h,TextureLoader as u}from"three";import{pathJoin as c}from"../../utils/files";import{Service as g}from"typedi";let f=class{constructor(e,t){this.assetResourceLoader=e,this.assetService=t,this.baseUrl="",this.urlSuffix="",this.loadingManager=new h,this.glbLoader=new i(this.loadingManager),this.fbxLoader=new o(this.loadingManager),this.objLoader=new n(this.loadingManager),this.mtlLoader=new a(this.loadingManager),this.tgaLoader=new d(this.loadingManager),this.textureLoader=new u(this.loadingManager),this.audioLoader=new l(this.loadingManager)}resolvePath(e){return c(this.baseUrl,e)+this.urlSuffix}getModelAtPath(t){return e(this,void 0,void 0,(function*(){const e=this.resolvePath(t);switch(t.split(".").pop().toLowerCase()){case"glb":case"gltf":return(yield this.glbLoader.loadAsync(e)).scene;case"fbx":return this.fbxLoader.loadAsync(e);case"obj":return this.objLoader.loadAsync(e);default:throw new Error(`File suffix is not supperted in file ${t}`)}}))}geGltfAtPath(t){return e(this,void 0,void 0,(function*(){const e=this.resolvePath(t);return this.glbLoader.loadAsync(e)}))}getModelByAssetName(t){return e(this,void 0,void 0,(function*(){const e=(yield this.assetService.getAssets()).find((e=>e.name===t));if(null==e)throw new Error(`No model could be found with asset name ${t}`);return this.assetResourceLoader.getMesh(e)}))}getModelByAssetId(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetService.getAsset(t);if(null==e)throw new Error(`No model could be found with asset id ${t}`);return this.assetResourceLoader.getMesh(e)}))}};f=t([g(),s("design:paramtypes",[r,Object])],f);export{f as AssetLoader};
1
+ import{__awaiter as e,__decorate as t,__metadata as s}from"tslib";import{AssetResourceLoader as r}from"../../scene/asset-resource-loader";import{FBXLoader as i,GLTFLoader as o,MTLLoader as a,OBJLoader as n,TGALoader as d}from"three-stdlib";import{AudioLoader as h,LoadingManager as l,TextureLoader as u}from"three";import{pathJoin as c}from"../../utils/files";import{Service as f}from"typedi";import{materialFromAsset as g}from"../../scene/materializer";let w=class{constructor(e,t,s){this.assetResourceLoader=e,this.assetService=t,this.shaders=s,this.baseUrl="",this.urlSuffix="",this.loadingManager=new l,this.glbLoader=new o(this.loadingManager),this.fbxLoader=new i(this.loadingManager),this.objLoader=new n(this.loadingManager),this.mtlLoader=new a(this.loadingManager),this.tgaLoader=new d(this.loadingManager),this.textureLoader=new u(this.loadingManager),this.audioLoader=new h(this.loadingManager)}resolvePath(e){return c(this.baseUrl,e)+this.urlSuffix}getModelAtPath(t){return e(this,void 0,void 0,(function*(){const e=this.resolvePath(t);switch(t.split(".").pop().toLowerCase()){case"glb":case"gltf":return(yield this.glbLoader.loadAsync(e)).scene;case"fbx":return this.fbxLoader.loadAsync(e);case"obj":return this.objLoader.loadAsync(e);default:throw new Error(`File suffix is not supperted in file ${t}`)}}))}geGltfAtPath(t){return e(this,void 0,void 0,(function*(){const e=this.resolvePath(t);return this.glbLoader.loadAsync(e)}))}getModelByAssetName(t){return e(this,void 0,void 0,(function*(){const e=(yield this.assetService.getAssets()).find((e=>e.name===t));if(null==e)throw new Error(`No model could be found with asset name ${t}`);return this.assetResourceLoader.getMesh(e)}))}getModelByAssetId(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetService.getAsset(t);if(null==e)throw new Error(`No model could be found with asset id ${t}`);return this.assetResourceLoader.getMesh(e)}))}getTextureByAssetId(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetService.getAsset(t);if(null==e)throw new Error(`No texture could be found with asset id ${t}`);return this.assetResourceLoader.getTexture(e)}))}getMaterialByAssetId(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetService.getAsset(t);if(null==e)throw new Error(`No material could be found with asset id ${t}`);return g(e,null,this.assetService,this.assetResourceLoader,this.shaders,!1)}))}};w=t([f(),s("design:paramtypes",[r,Object,Array])],w);export{w as AssetLoader};
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -3,6 +3,7 @@ import { RenderingView } from "../../rendering";
3
3
  import { Observable } from "rxjs";
4
4
  import * as THREE from "three";
5
5
  import { CameraActor } from "../../gameplay/actors/builtin/camera-actor";
6
+ import { BaseActor } from "../../gameplay/actors/actor";
6
7
  export declare class ViewController {
7
8
  private view;
8
9
  private readonly tick;
@@ -13,8 +14,8 @@ export declare class ViewController {
13
14
  get fpsCap(): number;
14
15
  set showStats(value: boolean);
15
16
  get showStats(): boolean;
16
- onUpdate(actor?: any): Observable<number>;
17
- onLateUpdate(actor?: any): Observable<number>;
17
+ onUpdate(actor?: BaseActor): Observable<number>;
18
+ onLateUpdate(actor?: BaseActor): Observable<number>;
18
19
  setCamera(camera: Camera | CameraActor): void;
19
20
  getCamera(): Camera;
20
21
  get htmlElement(): HTMLElement;
@@ -3,6 +3,7 @@ import { WebGLRenderer, Object3D, WebGLRenderTarget, Camera } from "three";
3
3
  import { CSM } from "three-stdlib";
4
4
  export type RenderingViewOptions = {
5
5
  enableOutlines?: boolean;
6
+ enableXR?: boolean;
6
7
  };
7
8
  export declare class RenderingView {
8
9
  container: HTMLElement;
package/dist/rendering.js CHANGED
@@ -1,4 +1,4 @@
1
- import*as e from"three";import{Mesh as t,Matrix4 as i,ShaderMaterial as s,PerspectiveCamera as r,ShaderChunk as n}from"three";import{EffectComposer as a}from"three-stdlib";import{RenderPass as h}from"three-stdlib";import{ShaderPass as o}from"three-stdlib";import{FXAAShader as d}from"three-stdlib";import{CSM as l}from"three-stdlib";import{CSMUtil as c}from"./csm";import{GammaCorrectionShader as m}from"three-stdlib";import{Reflector as p}from"three-stdlib";import{depthUniformName as u,resolutionUniformName as g,supportsDepthTextureExtension as v,nearUniformName as f,farUniformName as w}from"./shader-nodes/depth";import{elapsedTimeUniformName as x}from"./shader-nodes/time";import{OutlinePass as C}from"./utils/three/outline-pass";import b from"./utils/three/stats";import{lambertVertexShaderOverride as R}from"./rendering/shader-override";import{DepthPass as y}from"./utils/three/depth-pass";const P=new e.MeshDepthMaterial;P.depthPacking=e.RGBADepthPacking,P.blending=e.NoBlending;n.lights_pars_begin;n.lights_lambert_vertex=R;export class RenderingView{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||(this.camera instanceof r&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(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.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight)}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=1,this.onResize=()=>{this.resizeRender(),this.paused||this.composer.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=b(),this._showStats=!1,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,window.renderer=this.renderer=new e.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new e.Scene,this.renderer.setPixelRatio(window.devicePixelRatio*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.composer=new a(this.renderer);var s=t.clientWidth/t.clientHeight;const r=new e.PerspectiveCamera(45,s,.5,500);r.layers.enable(19),this.setCamera(r),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=e.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=!1,this.renderer.outputEncoding=e.sRGBEncoding,this.renderer.physicallyCorrectLights=!1,this.renderer.gammaFactor=1.4,c.renderingView=this,c.patchThreeAdd(),this.isDepthTextureExtensionSupported=v(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=RenderingView.createDepthRenderTarget(this.renderer,this.container);const n=new h(this.scene,this.camera);if(this.composer.addPass(n),this.outlinePass=new C(new e.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 o(d);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e);var l=new o(m);l.clear=!1,this.composer.addPass(l)}}setCamera(t){this.camera=t,this.composer.passes.forEach((e=>{e instanceof h?e.camera=t:e instanceof C?e.renderCamera=t:e instanceof y&&(e.camera=t)})),null==this.csm?this.csm=new l({maxFar:200,lightFar:300,cascades:5,shadowMapSize:2048,lightDirection:new e.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5,camera:this.camera,parent:this.scene}):(this.csm.camera=this.camera,this.camera instanceof r&&(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(t,i){var s=!!t.extensions.get("WEBGL_depth_texture");const r=new e.WebGLRenderTarget(i.clientWidth*t.getPixelRatio(),i.clientHeight*t.getPixelRatio());return r.texture.minFilter=e.NearestFilter,r.texture.magFilter=e.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===s&&(r.depthTexture=new e.DepthTexture(128,128),r.depthTexture.type=e.UnsignedShortType,r.depthTexture.minFilter=e.NearestFilter,r.depthTexture.magFilter=e.NearestFilter),r}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.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);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}loop(s,r=!1){const n=this.stats;n.showPanel(0),this.showStats=r;performance.now();e.Ray.prototype.intersectTriangle;let a=0;const h=new i,o=new i,d=e=>{var i,r;const l=this.renderer.getContext();if(this.paused&&this.running&&l.drawingBufferHeight>1)return void setTimeout((()=>d(e)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,n.begin();let c=(e*=.001)-a;if(a=e,h.copy(this.camera.matrixWorld),c>1){let e=c;for(;e>.05;)s(S),e-=S;s(e)}else s(c);this.onLoopCallbacks.forEach((e=>e(c))),null===(i=this.camera)||void 0===i||i.updateMatrixWorld(),o.copy(this.camera.matrixWorld),o.equals(h)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender();const m=[],g=[];if(this.scene.traverse((i=>{var s,r,n,a,h,o;i instanceof t&&i.visible&&((null===(r=null===(s=i.material)||void 0===s?void 0:s.userData)||void 0===r?void 0:r.water)||(null===(n=i.material)||void 0===n?void 0:n.uniforms)&&null!=(null===(a=i.material)||void 0===a?void 0:a.uniforms[u]))?(i.visible=!1,m.push(i),this.initDepthUniform(i.material),i.renderOrder=100):i instanceof p&&(i.visible=!1,g.push(i)),i instanceof t&&(null===(h=i.material)||void 0===h?void 0:h.uniforms)&&null!=(null===(o=i.material)||void 0===o?void 0:o.uniforms[x])&&(i.material.uniforms[x].value=e)})),m.length>0){if(this.scene.overrideMaterial=P,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}m.forEach((e=>e.visible=!0)),g.forEach((e=>e.visible=!0));try{!this.paused&&this.running&&(this.composer.render(c),this.renderOverlay())}catch(e){console.warn(e)}n.end(),null===(r=this.csm)||void 0===r||r.update(),this.running&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(d)}),1e3/this.fpsCap):requestAnimationFrame(d))};requestAnimationFrame(d)}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(){this.composer.render()}initDepthUniform(e){e instanceof s&&(e.uniforms[u].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[g]&&e.uniforms[g].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof r&&(e.uniforms[f].value=this.camera.near,e.uniforms[w].value=this.camera.far))}}export function setRenderingPaused(e){var t,i;null!=(null===(i=null===(t=window.editor)||void 0===t?void 0:t.viewer)||void 0===i?void 0:i.renderingView)&&(window.editor.viewer.renderingView.paused=e)}const S=.05;
1
+ import*as e from"three";import{Mesh as t,Matrix4 as i,ShaderMaterial as s,PerspectiveCamera as r,ShaderChunk as n}from"three";import{EffectComposer as a,VRButton as o}from"three-stdlib";import{RenderPass as h}from"three-stdlib";import{ShaderPass as d}from"three-stdlib";import{FXAAShader as l}from"three-stdlib";import{CSM as c}from"three-stdlib";import{CSMUtil as m}from"./csm";import{GammaCorrectionShader as p}from"three-stdlib";import{Reflector as u}from"three-stdlib";import{depthUniformName as g,resolutionUniformName as v,supportsDepthTextureExtension as f,nearUniformName as w,farUniformName as b}from"./shader-nodes/depth";import{elapsedTimeUniformName as x}from"./shader-nodes/time";import{OutlinePass as C}from"./utils/three/outline-pass";import R from"./utils/three/stats";import{lambertVertexShaderOverride as y}from"./rendering/shader-override";import{DepthPass as P}from"./utils/three/depth-pass";const S=new e.MeshDepthMaterial;S.depthPacking=e.RGBADepthPacking,S.blending=e.NoBlending;n.lights_pars_begin;n.lights_lambert_vertex=y;export class RenderingView{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||(this.camera instanceof r&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(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.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight)}constructor(t,i={}){var s;this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=1,this.onResize=()=>{this.resizeRender(),this.paused||this.composer.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=R(),this._showStats=!1,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,window.renderer=this.renderer=new e.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new e.Scene,this.renderer.setPixelRatio(window.devicePixelRatio*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=null!==(s=this.options.enableXR)&&void 0!==s&&s,!0===this.options.enableXR&&document.body.appendChild(o.createButton(this.renderer)),this.composer=new a(this.renderer);var r=t.clientWidth/t.clientHeight;const n=new e.PerspectiveCamera(45,r,.5,500);n.layers.enable(19),this.setCamera(n),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=e.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=!1,this.renderer.outputEncoding=e.sRGBEncoding,this.renderer.physicallyCorrectLights=!1,this.renderer.gammaFactor=1.4,m.renderingView=this,m.patchThreeAdd(),this.isDepthTextureExtensionSupported=f(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=RenderingView.createDepthRenderTarget(this.renderer,this.container);const c=new h(this.scene,this.camera);if(this.composer.addPass(c),this.outlinePass=new C(new e.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 d(l);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e);var u=new d(p);u.clear=!1,this.composer.addPass(u)}}setCamera(t){this.camera=t,this.composer.passes.forEach((e=>{e instanceof h?e.camera=t:e instanceof C?e.renderCamera=t:e instanceof P&&(e.camera=t)})),null==this.csm?this.csm=new c({maxFar:200,lightFar:300,cascades:5,shadowMapSize:2048,lightDirection:new e.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5,camera:this.camera,parent:this.scene}):(this.csm.camera=this.camera,this.camera instanceof r&&(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(t,i){var s=!!t.extensions.get("WEBGL_depth_texture");const r=new e.WebGLRenderTarget(i.clientWidth*t.getPixelRatio(),i.clientHeight*t.getPixelRatio());return r.texture.minFilter=e.NearestFilter,r.texture.magFilter=e.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===s&&(r.depthTexture=new e.DepthTexture(128,128),r.depthTexture.type=e.UnsignedShortType,r.depthTexture.minFilter=e.NearestFilter,r.depthTexture.magFilter=e.NearestFilter),r}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.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);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}loop(s,r=!1){const n=this.stats;n.showPanel(0),this.showStats=r;performance.now();e.Ray.prototype.intersectTriangle;let a=0;const o=new i,h=new i,d=e=>{var i,r;const l=this.renderer.getContext();if(this.paused&&this.running&&l.drawingBufferHeight>1)return void setTimeout((()=>d(e)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,n.begin();let c=(e*=.001)-a;if(a=e,o.copy(this.camera.matrixWorld),c>1){let e=c;for(;e>.05;)s(T),e-=T;s(e)}else s(c);this.onLoopCallbacks.forEach((e=>e(c))),null===(i=this.camera)||void 0===i||i.updateMatrixWorld(),h.copy(this.camera.matrixWorld),h.equals(o)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender();const m=[],p=[];if(this.scene.traverse((i=>{var s,r,n,a,o,h;i instanceof t&&i.visible&&((null===(r=null===(s=i.material)||void 0===s?void 0:s.userData)||void 0===r?void 0:r.water)||(null===(n=i.material)||void 0===n?void 0:n.uniforms)&&null!=(null===(a=i.material)||void 0===a?void 0:a.uniforms[g]))?(i.visible=!1,m.push(i),this.initDepthUniform(i.material),i.renderOrder=100):i instanceof u&&(i.visible=!1,p.push(i)),i instanceof t&&(null===(o=i.material)||void 0===o?void 0:o.uniforms)&&null!=(null===(h=i.material)||void 0===h?void 0:h.uniforms[x])&&(i.material.uniforms[x].value=e)})),m.length>0){if(this.scene.overrideMaterial=S,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}m.forEach((e=>e.visible=!0)),p.forEach((e=>e.visible=!0));try{!this.paused&&this.running&&(this.composer.render(c),this.renderOverlay())}catch(e){console.warn(e)}n.end(),null===(r=this.csm)||void 0===r||r.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(d)}),1e3/this.fpsCap):requestAnimationFrame(d))};!0===this.options.enableXR?this.renderer.setAnimationLoop(d):requestAnimationFrame(d)}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(){this.composer.render()}initDepthUniform(e){e instanceof s&&(e.uniforms[g].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[v]&&e.uniforms[v].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof r&&(e.uniforms[w].value=this.camera.near,e.uniforms[b].value=this.camera.far))}}export function setRenderingPaused(e){var t,i;null!=(null===(i=null===(t=window.editor)||void 0===t?void 0:t.viewer)||void 0===i?void 0:i.renderingView)&&(window.editor.viewer.renderingView.paused=e)}const T=.05;
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -9,11 +9,11 @@ import { Type } from "../utils/type";
9
9
  import { AssetResourceLoader } from './asset-resource-loader';
10
10
  import { AssetsProvider } from "./assets-provider";
11
11
  import { LandscapeInitOptions } from "./landscape/landscape";
12
- import { Asset, CustomParamValue, MaterialAssignment, ShapeType } from "./model";
12
+ import { Asset, CustomParamValue, MaterialAssignment, SerializedParamType, ShapeType } from "./model";
13
13
  import { BaseActor } from '../gameplay/actors/actor';
14
14
  import { ContainerInstance } from "typedi";
15
15
  export type SceneObjectId = string;
16
- export type SceneObjectType = "asset_mesh" | "light" | "shape_mesh" | "spline" | "landscape" | "particles" | "global_fog" | "global_light" | "actor" | "group" | "prefab";
16
+ export type SceneObjectType = "asset_mesh" | "light" | "shape_mesh" | "spline" | "landscape" | "particles" | "global_fog" | "global_light" | "actor" | "group" | "prefab" | "vfx" | "sky";
17
17
  export type LightType = "point" | "directional" | "ambient";
18
18
  type DirectionalLightSettings = {
19
19
  color: string | number;
@@ -34,7 +34,7 @@ type AmbientLightSettings = {
34
34
  };
35
35
  export interface SceneObject {
36
36
  id: SceneObjectId;
37
- name?: string;
37
+ name: string;
38
38
  children?: SceneObject[];
39
39
  assetId?: string;
40
40
  shape?: ShapeType;
@@ -64,7 +64,11 @@ export interface SceneObject {
64
64
  type: SceneObjectType;
65
65
  castShadow?: boolean;
66
66
  receiveShadow?: boolean;
67
+ sky?: SkySettings;
67
68
  }
69
+ export type SkySettings = {
70
+ materialId: string;
71
+ };
68
72
  export interface ActorSettings {
69
73
  type: string;
70
74
  params?: Record<string, CustomParamValue>;
@@ -193,9 +197,13 @@ export declare class SceneMaterializer {
193
197
  * be impossible to guarantee.
194
198
  */
195
199
  private initActorsPostInit;
200
+ private addVfxChildActors;
201
+ private removeVfxChildActors;
196
202
  private applyActorComponentParams;
197
203
  private _canBeInstancedCache;
198
204
  private canAssetBeInstanced;
205
+ private sky;
206
+ private preInit;
199
207
  initWithInstancing(): Promise<void>;
200
208
  private createInstancedMesh;
201
209
  private remove;
@@ -220,8 +228,10 @@ export declare class SceneMaterializer {
220
228
  * @returns
221
229
  */
222
230
  materialize(source: SceneObject, parent?: Object3D, anonymous?: boolean): Promise<Object3D>;
231
+ private updateSky;
223
232
  private createComponent;
224
233
  private createFromActor;
234
+ private createFromVfx;
225
235
  cleanup(): void;
226
236
  private createFromShape;
227
237
  private createLandscape;
@@ -236,6 +246,12 @@ export declare class SceneMaterializer {
236
246
  dispose(): void;
237
247
  }
238
248
  export declare function materialFromAsset(asset: Asset, renderingView: RenderingView, assetsService: AssetsProvider, assetManagerService: AssetResourceLoader, shaders: ShaderImpl[], useCache?: boolean): Promise<Material>;
249
+ export declare function prepareShapeParameters(paramsSource: {
250
+ [key: string]: CustomParamValue;
251
+ }): Promise<{
252
+ [key: string]: unknown;
253
+ }>;
254
+ export declare function toSerializedParamType(type: Type<any>): SerializedParamType;
239
255
  export declare function prepareCustomParams<T>(propertyParams: PropertyParameter[], previous: Record<string, CustomParamValue>, defaults?: Record<string, unknown>): Record<string, CustomParamValue>;
240
256
  export declare function prepareCustomParamsFromType<T>(type: Type<T>, previous: Record<string, CustomParamValue>, diContainer?: ContainerInstance): Record<string, CustomParamValue>;
241
257
  /**
@@ -243,4 +259,5 @@ export declare function prepareCustomParamsFromType<T>(type: Type<T>, previous:
243
259
  * Returns undefined if
244
260
  */
245
261
  export declare function serializeCustomParameter(type: ParameterType, value: unknown): unknown;
262
+ export declare const customParameterDefaultValueByType: Map<SerializedParamType, any>;
246
263
  export {};
@@ -1,4 +1,4 @@
1
- import{__awaiter as e}from"tslib";import{Subject as t}from"rxjs";import*as i from"three";import{BoxGeometry as a,Color as r,Euler as s,Fog as n,FogExp2 as o,Group as l,Material as c,Mesh as d,MeshLambertMaterial as h,MeshPhongMaterial as u,MeshStandardMaterial as m,Object3D as p,PointLight as f,Quaternion as v,SphereGeometry as g,Texture as y,Vector2 as w,Vector3 as A,Vector4 as S}from"three";import b,{SpriteRenderer as M}from"three-nebula";import{bool as D,BooleanNode as I,float as x,FloatNode as P,NodeShaderMaterial as N,rgb as j,RgbNode as E,Texture2dLookupNode as O,textureSampler2d as F,vec2 as V,Vec2Node as B,vec3 as z,Vec3Node as C,vec4 as _}from"three-shader-graph";import T from"../gameplay/actors/builtin";import{extractShaderParameters as $}from"../shader/parameter";import{groupBy as k,ArrayMap as L}from"../utils/collections";import{filterChildrenShallow as R,filterSceneShallow as U}from"../utils/three/traverse";import{AssetMeshInstance as H}from"./asset-resource-loader";import{BoxCollisionShape as W,PhysicalShapeMesh as G}from"./collision/collision-shape";import{isCollisionMesh as J}from"./collision/collision-shape-import";import{initLandscape as X}from"./landscape/landscape";import{LandscapeManager as Y}from"./landscape/landscape-manager";import{SectionGrid as q,smoothNormalsCrossMeshes as Z}from"./landscape/utils";import{createGrassMaterial as K}from"./materials/grass";import{createGrassFoliageMaterial as Q}from"./materials/grass-foliage";import{getMaterialAttribute as ee}from"./materials/utils/material-painting";import{createWaterMaterial as te}from"./materials/water";import{SerializedParamType as ie}from"./model";import{Matrix4 as ae}from"three";import{BaseActor as re}from"../gameplay/actors/actor";import{Sampler2DNode as se}from"../shader-nodes";import{StandardShader as ne}from"../shader/builtin/standard-shader";import{LambertShader as oe}from"../shader/builtin/lambert-shader";import{ShapeLibrary as le,ShapeLibraryKeys as ce}from"./objects/shapes";import{ambientLightName as de}from"./sky";import{withInjectionContext as he}from"../gameplay";import{iterateMaterials as ue}from"../utils/materials";const me={};export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,i){this.dataProvider=e,this.assetsService=t,this.assetManagerService=i}get(t,i){return new SceneMaterializer(t,this.dataProvider,this.assetsService,this.assetManagerService,i,[],[],{create:()=>null,initActor:()=>e(this,void 0,void 0,(function*(){}))})}}export class SceneMaterializer{constructor(i,a,r,s,n,o,l,c){this.scene=i,this.dataProvider=a,this.assetsService=r,this.assetManagerService=s,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new t,this.removed$=new t,this.error$=new t,this.editorActorParamSnapshot=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.originalFog=null,a.onUpdate((e=>this.update(e))),a.onRemove((e=>this.remove(e))),this.updateSubscription=r.onUpdate.subscribe((t=>e(this,void 0,void 0,(function*(){"material"==t.type?((yield this.assetsService.getAssets()).filter((e=>{var i;return(null!==(i=e.materialAssignments)&&void 0!==i?i:[]).some((e=>e.materialId===t.id))})).forEach((e=>{const t=this.findByAssetId(e.id);e.materialAssignments.forEach((e=>{t.forEach((t=>{const i=t.userData.src.materialAssignments;null!=i&&i.some((t=>t.color===e.color))||this.applyMaterial(t,e)}))}))})),U(this.scene,(e=>{var i;return null!=e.userData.src&&(null!==(i=e.userData.src.materialAssignments)&&void 0!==i?i:[]).some((e=>e.materialId===t.id))}),(e=>null!=e.userData.src)).forEach((t=>e(this,void 0,void 0,(function*(){this.deleteSceneObject(t.userData.src),this.materialize(t.userData.src)}))))):"mesh"==t.type?this.findByAssetId(t.id).forEach((e=>{De(e.userData.src.materialAssignments,t.materialAssignments).forEach((t=>{this.applyMaterial(e,t)}))})):"prefab"===t.type&&this.findByAssetId(t.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}))}))))}get actorInstances(){return Array.from(this.materializedActors.values())}prefetchAssets(){return e(this,void 0,void 0,(function*(){const e=Array.from(new Set(this.dataProvider.getObjects().filter((e=>null!=e.assetId&&"asset_mesh"==e.type)).filter((e=>e.assetId))));yield Promise.all(e.map((e=>this.assetsService.getAsset(e.assetId).then((e=>e&&this.assetManagerService.getMesh(e))))))}))}init(){return e(this,void 0,void 0,(function*(){fe.clear(),yield this.prefetchAssets(),yield Promise.all(this.dataProvider.getObjects().map((e=>this.materialize(e)))),yield this.initActorsPostInit()}))}initActorsPostInit(t=this.actorInstances){const i=t.map((t=>e(this,void 0,void 0,(function*(){var e,i,a,r;const s=t.object.userData.src,n=yield this.assetsService.getAsset(s.assetId),o=Object.assign(Object.assign({},null!==(i=null===(e=null==n?void 0:n.actor)||void 0===e?void 0:e.params)&&void 0!==i?i:{}),null!==(a=s.actor.params)&&void 0!==a?a:{});for(const e of null!==(r=s.actor.innerParams)&&void 0!==r?r:[])yield this.applyActorComponentParams(t,e.path.slice(),e.params);const l=yield ye(o,t.constructor,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);Object.assign(t,l);try{return yield this.actorProvider.initActor(t)}catch(e){console.error(`Failed to initiate actor (name="${s.name}", id=${s.id})`,e)}}))));return Promise.all(i)}applyActorComponentParams(t,i,a){return e(this,void 0,void 0,(function*(){const e=i.length,r=i.shift();if(0==e){const e=yield ye(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);for(const[i,a]of Object.entries(e))null!=a&&(t[i]=a)}else null!=t[r]&&(yield this.applyActorComponentParams(t[r],i,a))}))}canAssetBeInstanced(t){return e(this,void 0,void 0,(function*(){if(!this._canBeInstancedCache.has(t.assetId)){const e=yield this.createFromAsset(t);if(null==e)return!1;const i=[];e.traverse((e=>{!J(e)&&e.isMesh&&i.push(e)}));const a=1==i.length&&0==i[0].children.length,r=!0;this._canBeInstancedCache.set(t.assetId,a&&r)}return this._canBeInstancedCache.get(t.assetId)}))}initWithInstancing(){return e(this,void 0,void 0,(function*(){const t=new L;for(const i of this.dataProvider.getObjects())yield be(i,((i,a,r)=>e(this,void 0,void 0,(function*(){var e,s;const n="asset_mesh"==i.type&&(yield this.canAssetBeInstanced(i))?i.assetId+JSON.stringify(null!==(e=i.materialAssignments)&&void 0!==e?e:[]):"other";"other"!==n&&a&&(null===(s=a.children)||void 0===s?void 0:s.length)>0&&a.children.splice(a.children.findIndex((e=>e.id===i.id)),1),"other"===n&&a||t.push(n,Object.assign(Object.assign({},i),{parentTransform:r}))}))));for(const[e,i]of t.entries())if("other"!==e&&i.length>0){const e=yield this.createFromAsset(i[0]);if(null==e)continue;const t=yield this.createInstancedMesh(i,e),a=new H;a.add(t),a.userData.src=i[0],e instanceof H&&(a.collisionShapes=e.collisionShapes),a.castShadow=!1,a.receiveShadow=!1,this.scene.add(a)}else yield Promise.all(i.map((e=>this.materialize(e))));yield this.initActorsPostInit()}))}createInstancedMesh(t,a){var r,n;return e(this,void 0,void 0,(function*(){const e=a.children.filter((e=>!J(e)))[0],o=yield this.assetsService.getAsset(t[0].assetId);yield this.applyMaterials(a,De(t[0].materialAssignments,o.materialAssignments)),e.updateMatrix();const l=e.geometry.clone().applyMatrix4(e.matrix),c=new i.InstancedMesh(l,e.material.clone(),t.length);c.material.side=i.FrontSide;for(let e=0;e<t.length;e++){const a=(new i.Matrix4).compose((new A).fromArray(t[e].position),(new v).setFromEuler((new s).fromArray(t[e].rotation)),(new A).fromArray(t[e].scale)),r=(new ae).copy(t[e].parentTransform).multiply(a);c.setMatrixAt(e,r)}return c.castShadow=null===(r=o.castShadow)||void 0===r||r,c.receiveShadow=null===(n=o.receiveShadow)||void 0===n||n,c}))}remove(e){if("global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("actor"==e.type){const t=this.materializedActors.get(e.id);null!=t&&t.disposed.next(!0)}const t=this.sceneObjectMap.get(e.id);null==t||t.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter((t=>{var i;return(null===(i=t.object.userData.src)||void 0===i?void 0:i.id)===e.id})).forEach((e=>this.components.splice(this.components.indexOf(e,1)))),this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))})),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex((t=>t.source.id===e.id));if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return U(this.scene,(t=>{var i;return(null===(i=t.userData.src)||void 0===i?void 0:i.assetId)==e}),(e=>null!=e.userData.src))}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter((e=>"null"!==e.materialId)).map((t=>this.applyMaterial(e,t))))}applyMaterial(t,i){const a=[];return t.traverse((t=>e(this,void 0,void 0,(function*(){if(t instanceof d||t.isMesh)for(const e of ue(t.material))e.hasOwnProperty("color")&&a.push(t)})))),Promise.all(a.map((t=>e(this,void 0,void 0,(function*(){var e,a,r,s;if(t.material instanceof Array)for(let r=0;r<t.material.length;r++){const s=t.material[r];if(null==s.color)continue;const n="#"+s.color.getHexString(),o=s.name;if(n===i.color&&(s.name===i.name||null==i.name)||t.userData["originalColor_"+r]===i.color&&t.userData["originalMaterialName_"+r]===i.name){const s=yield this.assetsService.getAsset(i.materialId),l=t.material[r];s&&(t.material[r]=yield materialFromAsset(s,this.renderingView,this.assetsService,this.assetManagerService,this.shaders),t.userData["originalColor_"+r]=null!==(e=t.userData["originalColor_"+r])&&void 0!==e?e:n,t.userData["originalMaterialName_"+r]=null!==(a=t.userData["originalMaterialName_"+r])&&void 0!==a?a:o,this.inEditor&&this._originalMaterials.set(t.id+"#"+r,l))}}else{const e="#"+t.material.color.getHexString(),a=t.material.name;if(e===i.color&&(t.material.name===i.name||null==i.name)||t.userData.originalColor===i.color&&t.userData.originalName===i.name){const n=yield this.assetsService.getAsset(i.materialId),o=t.material;n&&(t.material=yield materialFromAsset(n,this.renderingView,this.assetsService,this.assetManagerService,this.shaders),t.userData.originalColor=null!==(r=t.userData.originalColor)&&void 0!==r?r:e,t.userData.originalMaterialName=null!==(s=t.userData.originalMaterialName)&&void 0!==s?s:a,this.inEditor&&this._originalMaterials.set(t.id,o))}}})))))}unapplyMaterials(t){t.traverse((t=>e(this,void 0,void 0,(function*(){var e,i;if(t instanceof d)if(t.material instanceof Array)for(let i=0;i<t.material.length;i++)t.material[i]=null!==(e=this._originalMaterials.get(t.id+"#"+i))&&void 0!==e?e:t.material[i];else t.material=null!==(i=this._originalMaterials.get(t.id))&&void 0!==i?i:t.material}))))}updateActors(t){this.actorTypes=t;const i=new Set(Object.values(T));U(this.scene,(e=>{var t,a;return(null===(t=e.userData.src)||void 0===t?void 0:t.id)&&"actor"===e.userData.src.type&&this.materializedActors.has(null===(a=e.userData.src)||void 0===a?void 0:a.id)&&!i.has(e.userData.src.actor.type)})).forEach((t=>e(this,void 0,void 0,(function*(){this.remove(t.userData.src),yield this.materializeAndInitActor(t.userData.src)}))))}updateShaders(e){this.shaders=e;for(const[e,t]of fe.entries())t.userData.customShaderName&&fe.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),U(this.scene,(e=>!0)).forEach((e=>{e.traverse((e=>{var t,i;if(e instanceof d){if(null!=(null===(t=e.material.userData)||void 0===t?void 0:t.customShaderName)){const t=null===(i=function(e,t){if(t(e))return e;let i;return e.traverseAncestors((e=>{null==i&&t(e)&&(i=e)})),i}(e,(e=>{var t;return null!=(null===(t=e.userData.src)||void 0===t?void 0:t.id)})))||void 0===i?void 0:i.userData.src;null!=t&&this.update(t)}}}))}))}update(t){return e(this,void 0,void 0,(function*(){const e=this.sceneObjectMap.get(t.id);if(e){const a=this.findParent(t);if(null!=a&&a.uuid!=e.uuid?a.attach(e):console.error("Parent is wrong"),"prefab"!==t.type){this.unapplyMaterials(e);this.inEditor&&t.hidden&&!1?e.traverse((e=>{e instanceof d&&(e.material.wireframe=!0)})):e.traverse((e=>{e instanceof d&&(e.material.wireframe=!1)}))}if("asset_mesh"===t.type){const i=yield this.assetsService.getAsset(t.assetId);De(t.materialAssignments,i.materialAssignments).forEach((t=>this.applyMaterial(e,t)))}else"shape_mesh"===t.type&&this.applyMaterials(e,t.materialAssignments);if(e.position.fromArray(t.position),e.scale.fromArray(t.scale),e.rotation.fromArray(t.rotation),this.applyVertexMaterials(t,e),"light"==t.type)if("point"==t.light.type){const i=e;i.color=new r(t.light.point.color),i.intensity=t.light.point.intensity,i.decay=t.light.point.decay,i.castShadow=t.light.point.castShadow,i.distance=Math.max(t.light.point.distance,0)}else"directional"===t.light.type?this.applyDirectionalLight(t.light.directional):"ambient"===t.light.type&&this.applyDirectionalAmbientLight(e,t.light.ambient);else if("landscape"===t.shape)this.applyHeightMaps(e,t.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter((e=>e.source.id===t.id)).forEach((e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>!0))));else if("global_fog"===t.type){const e=(this.scene.fog instanceof o?"density":"linear")!==t.fog.type;this.scene.fog=Ae(t.fog),e&&(i=this.scene).traverse((e=>{if(e instanceof d){const t=e.material;t instanceof N&&(i.fog instanceof n?(t.uniforms.fogFar.value=i.fog.far,t.uniforms.fogNear.value=i.fog.near):i.fog instanceof o&&(t.uniforms.density={value:i.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}})),this.fixFogColor()}else if("actor"===t.type){if(this.materializedActors.has(t.id)){const e=this.editorActorParamSnapshot.get(t.id);null!=e&&e===JSON.stringify(t.actor)||(console.log("Rematerializing actor because parameters changed"),this.remove(t),yield this.materializeAndInitActor(t))}}else if("shape_mesh"===t.type){const i=yield this.createMeshByShape(t.shape,e.material,t.shapeParams);e instanceof G&&(e.geometry=i.geometry,e.collisionShape=i.collisionShape)}("asset_mesh"===t.type||"shape_mesh"===t.type&&"landscape"!==t.shape)&&pe(e,t.castShadow,t.receiveShadow),t.name&&t.name.length>0&&(e.name=t.name),this.updated$.next({object:e,source:t})}else{const e=yield this.materializeAndInitActor(t);this.updated$.next({object:e,source:t})}var i}))}materializeAndInitActor(t,i=this.findParent(t)){return e(this,void 0,void 0,(function*(){const e=yield this.materialize(t,i);if("actor"===t.type){const e=this.materializedActors.get(t.id);null!=e?yield this.initActorsPostInit([e]):console.error(`Something went wrong when creating actor ${t.id}`)}return e}))}findParent(e){const t=this.dataProvider.getObjects().flatMap((t=>t.id===e.id?null:R(t,(t=>{var i;return null===(i=t.children)||void 0===i?void 0:i.some((t=>t.id===e.id))}),(()=>!0))))[0];return null==t?this.scene:null!=t?U(this.scene,(e=>{var i,a;return(null===(a=null===(i=e.userData)||void 0===i?void 0:i.src)||void 0===a?void 0:a.id)===t.id}),(e=>{var t;return null!=(null===(t=e.userData)||void 0===t?void 0:t.src)}))[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new r(this.scene.fog.color).convertSRGBToLinear())}findMeshWithGeometry(e){let t;return e.traverse((e=>{e instanceof d&&e.geometry&&(t=e)})),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;const i=k(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof d){const t=ee(e,!1);if(null!=t){for(let e=0;e<t.array.length;e++)t.setX(e,0);t.needsUpdate=!0}}}));const a=new Set;for(const[e,r]of i.entries()){const i=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let s=!1;if(null==i)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const n=ee(i,!0);for(let e=0;e<n.array.length;e++)n.setX(e,0);for(const e of r)n.setX(e.i,e.w[0]),n.setY(e.i,e.w[1]),n.setZ(e.i,e.w[2]),s=!0;s&&a.add(e)}this.inEditor&&this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>a.has(e.name)))))}materialize(t,i,r=!1){var s,n,o,c;return e(this,void 0,void 0,(function*(){let e;switch(t.type){case"asset_mesh":e=yield this.createFromAsset(t);break;case"shape_mesh":e=yield this.createFromShape(t);break;case"light":e=yield this.createLight(t);break;case"particles":e=yield this.createParticleSystem(t),t.collisionDetection=!1;break;case"global_fog":this.scene.fog=Ae(t.fog),this.fixFogColor(),e=new l;break;case"actor":e=yield this.createFromActor(t);break;case"group":e=new l;break;case"prefab":e=yield this.createFromPrefabAsset(t);break;default:throw console.log(t),new Error("unknown type "+t.type)}if(null!=e){if(t.name&&t.name.length>0&&(e.name=t.name),e.position.fromArray(t.position),e.scale.fromArray(t.scale),e.rotation.fromArray(t.rotation),r||(e.userData.src=t),!this.inEditor){const i=null!==(s=t.components)&&void 0!==s?s:[],a=null!=t.assetId&&null!==(o=null===(n=yield this.assetsService.getAsset(t.assetId))||void 0===n?void 0:n.components)&&void 0!==o?o:[];i.push(...a),i.length>0?e.userData.componentRefs=yield Promise.all(i.map(((i,a)=>this.createComponent(e,t,i,a)))):"asset_mesh"==t.type&&function(e){e.traverse((e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}));const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}(e)}if(this.inEditor){let t=null;e instanceof G&&(t=function(e){if(e instanceof W)return new d(new a(...e.offset.toArray()),Se);return null}(e.collisionShape)),null!=t&&(t.layers.disable(0),t.layers.enable(18),t.scale.multiplyScalar(1.1),e.add(t))}return this.objectMap.set(e.uuid,t),this.sceneObjectMap.set(t.id,e),null==i?this.scene.add(e):null==i||i.add(e),null===(c=t.children)||void 0===c||c.forEach((t=>{this.materialize(t,e,r)})),e}}))}createComponent(t,i,a,r){return e(this,void 0,void 0,(function*(){const e=new me[a.path+"/"+a.className],s=i.id+r;e.id=s,e.object=t;for(const t of a.params)null!=t.value&&(e[t.name]=t.value);return this.components.push(e),s}))}createFromActor(t){var i,a,r;return e(this,void 0,void 0,(function*(){const e=null!==(a=null===(i=this.actorTypes.find((e=>{var i;return e.name===(null===(i=t.actor)||void 0===i?void 0:i.type)})))||void 0===i?void 0:i.type)&&void 0!==a?a:T[null===(r=t.actor)||void 0===r?void 0:r.type];if(null==e)return null;this.inEditor&&this.editorActorParamSnapshot.set(t.id,JSON.stringify(t.actor));const n=yield this.actorProvider.create(e,(new A).fromArray(t.position),(new s).fromArray(t.rotation),!0);return this.materializedActors.set(t.id,n),null==n?void 0:n.object}))}cleanup(){this.materializedActors.clear()}createFromShape(t){var i,a,s;return e(this,void 0,void 0,(function*(){const e=this.inEditor&&t.hidden;let n;if("landscape"==t.shape)n=this.createLandscape(t);else{let s=new m({name:"Default",color:new r("#aaaaaa"),visible:this.inEditor||!t.hidden,wireframe:e});const o=yield this.createMeshByShape(t.shape,s,t.shapeParams);o.castShadow=null===(i=t.castShadow)||void 0===i||i,o.receiveShadow=null!==(a=t.castShadow)&&void 0!==a&&a,t.collisionDetection||(o.collisionShape=null),n=o,this._originalMaterials.set(n.id,o.material),n.traverse((e=>{}))}return e||((null!==(s=t.materialAssignments)&&void 0!==s?s:[]).filter((e=>null!=e.materialId)).forEach((e=>this.applyMaterial(n,e))),this.applyVertexMaterials(t,n)),n}))}createLandscape(e){var t;if(null==(null===(t=e.landscape)||void 0===t?void 0:t.options))return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new l;const i=X(e.landscape.options);this.applyHeightMaps(i,e.landscape.heightMaps,!0);const a=new Y(e,this.renderingView,i,this.assetManagerService,this.assetsService,this.shaders,(t=>{var i;(null!==(i=e.materialAssignments)&&void 0!==i?i:[]).filter((e=>null!=e.materialId)).forEach((e=>this.applyMaterial(t,e)))}));return this.landscapeManagers.push(a),a.refreshGeometry(),i}applyHeightMaps(e,t,i=!1){const a=new q(e.sections);for(const e of null!=t?t:[]){const t=a.find(e.x,e.y);if(!t)return;const i=t.geometry.getAttribute("position");for(const t of e.points)i.setY(t.i,t.y);i.needsUpdate=!0}const r=e.sections;r.forEach((e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()})),this.inEditor&&!i||setTimeout((()=>Z(r)),50)}createMeshByShape(t,i,a={}){return e(this,void 0,void 0,(function*(){if("landscape"!==t&&ce.includes(t)){const r=yield function(t){return e(this,void 0,void 0,(function*(){const e={};for(const[i,a]of Object.entries(t)){const t=yield we(a,null,null,null);null!=t&&(e[i]=t)}return e}))}(null!=a?a:{});return"cylinder"==t&&r.openEnded,new G(le[t].geometry(r),i,le[t].collision(r))}throw new Error(`Unsupported shape '${t}'`)}))}createFromAsset(t){var i,a,r,s;return e(this,void 0,void 0,(function*(){const e=yield this.assetsService.getAsset(t.assetId);if(null==e)return void console.warn(`Can not find asset with id ${t.assetId} and name ${t.name}`);let{scene:n}=yield this.assetManagerService.getMesh(e);De(t.materialAssignments,e.materialAssignments).forEach((e=>this.applyMaterial(n,e)));const o=null===(a=null!==(i=t.receiveShadow)&&void 0!==i?i:!!e.receiveShadow)||void 0===a||a,l=null!==(s=null!==(r=t.castShadow)&&void 0!==r?r:!!e.castShadow)&&void 0!==s&&s;return n.receiveShadow=o,pe(n,l,o),t.collisionDetection||(n.collisionShapes=[]),this.applyVertexMaterials(t,n),n.traverse((e=>{e instanceof d&&"computeBoundsTree"in e.geometry&&e.geometry.computeBoundsTree()})),n}))}createFromPrefabAsset(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetsService.getAsset(t.assetId);if(null==e)return void console.warn(`Can not find asset with id ${t.assetId} and name ${t.name}`);const i=new l;return e.prefab.objects.filter((e=>"global_fog"!==e.type)).forEach((e=>this.materialize(e,i,!0))),i}))}createParticleSystem(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetsService.getAsset(t.assetId),a=new p;return yield b.fromJSONAsync(e.particleSystem,i).then((e=>{const t=new M(a,i);e.addRenderer(t),this.renderingView.onLoop((t=>e.update()))})),a}))}createLight(t){var i;return e(this,void 0,void 0,(function*(){if("point"===t.light.type){const e=new f(t.light.point.color,t.light.point.intensity,t.light.point.distance,t.light.point.decay);if(e.castShadow=null===(i=t.light.point.castShadow)||void 0===i||i,this.inEditor){const t=new g(.3,10,10),i=new m({color:new r(16771709)}),a=new d(t,i);e.add(a)}return e}return"directional"===t.light.type?(this.applyDirectionalLight(t.light.directional),new l):"ambient"===t.light.type?(this.applyDirectionalAmbientLight(null,t.light.ambient),new l):void 0}))}applyDirectionalAmbientLight(e,t){const i=this.scene.children.find((e=>e.name===de));null!=i?(i.intensity=t.intensity,i.color.set(t.color),i.groundColor.set(t.color)):console.warn("Couldn't find ambient light")}applyDirectionalLight(e){for(const t of this.renderingView.csm.lights)t.intensity=e.intensity,t.color.set(e.color),t.castShadow=e.castShadow;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe()}}function pe(e,t,i){e.castShadow=t,e.receiveShadow=i,e.traverse((e=>{e.castShadow=t,e.receiveShadow=i}))}const fe=new Map,ve=new h({color:16711935}),ge=new Map;export function materialFromAsset(t,a,s,n,o,l=!0){var c,d,h,m,p,f,v,g,y,w,A;return e(this,void 0,void 0,(function*(){const e=JSON.stringify(t.material);if(l&&fe.has(e))return fe.get(e);const S={opacity:t.material.params.opacity,map:null,emissive:null!==(c=t.material.params.emissive)&&void 0!==c?c:null,metalness:null!==(d=t.material.params.metalness)&&void 0!==d?d:0,flatShading:null!==(h=t.material.params.flatShading)&&void 0!==h&&h,color:new r(t.material.params.color).convertSRGBToLinear(),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},b={};if(null!=t.material.params.map){const e=t.material.params.map,i=yield s.getAsset(e);null!=i&&(S.map=yield n.getTexture(i))}let M;switch(t.material.type){case"phong":M=new u(Object.assign(Object.assign({},S),b));break;case"water":M=te(S,a);break;case"grassFoliage":M=Q({color:S.color,map:S.map},a);break;case"grass":M=K(Object.assign(Object.assign({},S),{colorTwo:new r(t.material.params.colorTwo),colorThree:new r(t.material.params.colorThree)}),a);break;case"standard":case"lambert":case"shader":const e=null!==(m={standard:ne,lambert:oe}[t.material.type])&&void 0!==m?m:null===(p=o.find((e=>e.name==t.material.shader)))||void 0===p?void 0:p.type;if(e){const i=new e,r=yield ye(null!==(v=null===(f=t.material)||void 0===f?void 0:f.shaderParams)&&void 0!==v?v:{},e,s,n,null,a,o);Object.assign(i,r);try{M=i.build()}catch(e){console.log("Shader runtime error: "+e),ge.has(t.material.shader)||ge.set(t.material.shader,ve.clone()),M=ge.get(t.material.shader)}M.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),M=ve;break;default:throw new Error("Unsupported material type"+t.material.type)}return null==a||a.csm.setupMaterial(M),l&&fe.set(e,M),M.side=null!==(y=null!==(g=t.material.side)&&void 0!==g?g:M.side)&&void 0!==y?y:i.FrontSide,M.transparent=null!==(A=null!==(w=t.material.transparent)&&void 0!==w?w:S.transparent)&&void 0!==A&&A||M.transparent,M}))}function ye(t,i,a,r,s,n,o){return e(this,void 0,void 0,(function*(){const e={};for(const[i,l]of Object.entries(t)){const t=yield we(l,a,r,s,n,o);null!=t&&(e[i]=t)}return e}))}function we(t,i,a,n,o,l){return e(this,void 0,void 0,(function*(){if(null==t||null==t.value||""==t.value)return null;const e=t.value;switch(t.type){case ie.Number:case ie.FloatNode:let c="string"==typeof e?parseFloat(e):e;return t.type===ie.FloatNode?x(c):c;case ie.Texture:return yield a.getTexture(yield i.getAsset(e));case ie.Sampler2DNode:return F(yield a.getTexture(yield i.getAsset(e)));case ie.Boolean:return e;case ie.BooleanNode:return D(e);case ie.Vector2:case ie.Vec2Node:if("object"==typeof e){const i=e instanceof Array?(new w).fromArray(e):new w(i.x,i.y);return t.type===ie.Vec2Node?V(i):i}return null;case ie.Vector3:case ie.Vec3Node:if("object"==typeof e){const i=e instanceof Array?(new A).fromArray(e):new A(i.x,i.y,i.z);return t.type===ie.Vec3Node?z(i):i}return null;case ie.Color:case ie.RgbNode:const d=new r(e).convertSRGBToLinear();return t.type===ie.RgbNode?j(d):d;case ie.String:return e;case ie.BaseActor:const h=e;return null==n&&console.warn("Class parameters can not be prepared as actors are not passed in"),null==n?void 0:n.get(h);case ie.Euler:const u=e;return(new s).fromArray(u);case ie.Object3D:return(yield a.getMesh(yield i.getAsset(e))).scene;case ie.Material:return yield materialFromAsset(yield i.getAsset(e),o,i,a,l);case ie.AudioBuffer:return yield a.getAudio(yield i.getAsset(e))}return null}))}function Ae(e){var t,i;return"linear"===e.type?new n(new r(e.color),null!==(t=e.near)&&void 0!==t?t:100,null!==(i=e.far)&&void 0!==i?i:1e3):"density"===e.type?new o(e.color,e.density):void console.warn("Invalid fog type",e)}const Se=new m({color:4229780});function be(t,a,r,n){var o;return e(this,void 0,void 0,(function*(){null==n&&(n=(new ae).identity()),yield a(t,r,n);const e=n.clone().multiply(function(e,t){return t.compose((new A).fromArray(e.position),(new v).setFromEuler((new s).fromArray(e.rotation)),(new A).fromArray(e.scale))}(t,new i.Matrix4));return Promise.all((null!==(o=t.children)&&void 0!==o?o:[]).map((i=>be(i,a,t,e))))}))}function Me(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?ie.Number:t instanceof P||"function"==typeof e.prototype.isFloat?ie.FloatNode:t instanceof y||e===y||e.isTexture?ie.Texture:t instanceof se||e===O?ie.Sampler2DNode:t instanceof Boolean||e===Boolean?ie.Boolean:t instanceof I?ie.BooleanNode:t instanceof r||e==r?ie.Color:t instanceof E||"function"==typeof e.prototype.isRgb?ie.RgbNode:t instanceof w||e==w?ie.Vector2:t instanceof B||"function"==typeof e.prototype.isVec2?ie.Vec2Node:t instanceof A||e==A?ie.Vector3:t instanceof C||"function"==typeof e.prototype.isVec3?ie.Vec3Node:t instanceof String||e===String?ie.String:t instanceof re||e==re||e.prototype instanceof re||e.prototype==re?ie.BaseActor:t instanceof s||e==s?ie.Euler:t instanceof p||e==p?ie.Object3D:t instanceof c||e==c?ie.Material:t instanceof AudioBuffer||e==AudioBuffer?ie.AudioBuffer:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,i={}){return Object.fromEntries(e.map((e=>{var a,r,s;return[e.name,{type:Me(e.type),value:null!==(s=null!==(r=null===(a=t[e.name])||void 0===a?void 0:a.value)&&void 0!==r?r:i[e.name])&&void 0!==s?s:xe.get(Me(e.type))}]})))}export function prepareCustomParamsFromType(e,t,i=null){const a=$(e);if(0===a.length)return{};let r;null!=i?he(i,(()=>{r=i.get(e)})):r=new e;const s={};for(const e of a){const t=r[e.name];if(null!=t){const i=serializeCustomParameter(e.type,t);null!=i&&(s[e.name]=i)}}return prepareCustomParams(a,t,s)}export function serializeCustomParameter(e,t){function i(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case w:return t instanceof w?t.toArray():void i();case A:return t instanceof A?t.toArray():void i();case S:return t instanceof S?t.toArray():void i();case r:return t instanceof r?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new r(t).getHexString():void i();case String:return t;case s:return t instanceof s?t.toArray():void i()}}function De(e,t){return function(e,t,i){const a=[],r=new Set;for(const s of[...null!=e?e:[],...null!=t?t:[]]){const e=i(s);r.has(e)||(r.add(e),a.push(s))}return a}((null!=e?e:[]).filter((e=>Ie(e.materialId))),(null!=t?t:[]).filter((e=>Ie(e.materialId))),(e=>e.color+e.name))}function Ie(e){return"null"!=e&&null!=e}const xe=new Map([[ie.RgbNode,"#000000"],[ie.Color,"#000000"],[ie.Vector4,[0,0,0,0]],[ie.Vec4Node,[0,0,0,0]],[ie.Vector3,[0,0,0]],[ie.Vec3Node,[0,0,0]],[ie.Vector2,[0,0]],[ie.Vec2Node,[0,0]],[ie.Euler,[0,0,0,"XYZ"]]]);
1
+ import{__awaiter as e}from"tslib";import{Subject as t}from"rxjs";import*as i from"three";import{BoxGeometry as r,Color as a,Euler as s,Fog as o,FogExp2 as n,Group as l,Material as c,Mesh as d,MeshLambertMaterial as h,MeshPhongMaterial as u,MeshStandardMaterial as m,Object3D as p,PointLight as f,Quaternion as v,SphereGeometry as y,Texture as g,Vector2 as w,Vector3 as A,Vector4 as S}from"three";import b,{SpriteRenderer as M}from"three-nebula";import{bool as x,BooleanNode as I,float as P,FloatNode as D,NodeShaderMaterial as j,rgb as V,RgbNode as E,Texture2dLookupNode as N,textureSampler2d as C,vec2 as O,Vec2Node as F,vec3 as k,Vec3Node as z,vec4 as B}from"three-shader-graph";import _ from"../gameplay/actors/builtin";import{extractShaderParameters as T}from"../shader/parameter";import{groupBy as $,ArrayMap as L}from"../utils/collections";import{filterChildrenShallow as R,filterSceneShallow as U}from"../utils/three/traverse";import{AssetMeshInstance as H}from"./asset-resource-loader";import{BoxCollisionShape as W,PhysicalShapeMesh as G}from"./collision/collision-shape";import{isCollisionMesh as J}from"./collision/collision-shape-import";import{initLandscape as X}from"./landscape/landscape";import{LandscapeManager as Y}from"./landscape/landscape-manager";import{SectionGrid as q,smoothNormalsCrossMeshes as Z}from"./landscape/utils";import{createGrassMaterial as K}from"./materials/grass";import{createGrassFoliageMaterial as Q}from"./materials/grass-foliage";import{getMaterialAttribute as ee}from"./materials/utils/material-painting";import{createWaterMaterial as te}from"./materials/water";import{SerializedParamType as ie}from"./model";import{Matrix4 as re}from"three";import{BaseActor as ae}from"../gameplay/actors/actor";import{Sampler2DNode as se}from"../shader-nodes";import{StandardShader as oe}from"../shader/builtin/standard-shader";import{LambertShader as ne}from"../shader/builtin/lambert-shader";import{ShapeLibrary as le,ShapeLibraryKeys as ce}from"./objects/shapes";import{ambientLightName as de,createSky as he,defaultSkyMaterial as ue}from"./sky";import{ActorComponent as me,withInjectionContext as pe}from"../gameplay";import{iterateMaterials as fe}from"../utils/materials";import{VfxActor as ve}from"../effects/vfx/vfx-actor";import{VisualEffect as ye}from"../effects/vfx/vfx-param";const ge={};export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,i){this.dataProvider=e,this.assetsService=t,this.assetManagerService=i}get(t,i){return new SceneMaterializer(t,this.dataProvider,this.assetsService,this.assetManagerService,i,[],[],{create:()=>null,initActor:()=>e(this,void 0,void 0,(function*(){}))})}}export class SceneMaterializer{constructor(i,r,a,s,o,n,l,c){this.scene=i,this.dataProvider=r,this.assetsService=a,this.assetManagerService=s,this.renderingView=o,this.shaders=n,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new t,this.removed$=new t,this.error$=new t,this.editorActorParamSnapshot=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.originalFog=null,r.onUpdate((e=>this.update(e))),r.onRemove((e=>this.remove(e))),this.updateSubscription=a.onUpdate.subscribe((t=>e(this,void 0,void 0,(function*(){"material"==t.type?((yield this.assetsService.getAssets()).filter((e=>{var i;return(null!==(i=e.materialAssignments)&&void 0!==i?i:[]).some((e=>e.materialId===t.id))})).forEach((e=>{const t=this.findByAssetId(e.id);e.materialAssignments.forEach((e=>{t.forEach((t=>{const i=t.userData.src.materialAssignments;null!=i&&i.some((t=>t.color===e.color))||this.applyMaterial(t,e)}))}))})),U(this.scene,(e=>{var i;return null!=e.userData.src&&(null!==(i=e.userData.src.materialAssignments)&&void 0!==i?i:[]).some((e=>e.materialId===t.id))}),(e=>null!=e.userData.src)).forEach((t=>e(this,void 0,void 0,(function*(){this.deleteSceneObject(t.userData.src),this.materialize(t.userData.src)}))))):"mesh"==t.type?this.findByAssetId(t.id).forEach((e=>{je(e.userData.src.materialAssignments,t.materialAssignments).forEach((t=>{this.applyMaterial(e,t)}))})):"prefab"===t.type&&this.findByAssetId(t.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}))}))))}get actorInstances(){return Array.from(this.materializedActors.values())}prefetchAssets(){return e(this,void 0,void 0,(function*(){const e=Array.from(new Set(this.dataProvider.getObjects().filter((e=>null!=e.assetId&&"asset_mesh"==e.type)).filter((e=>e.assetId))));yield Promise.all(e.map((e=>this.assetsService.getAsset(e.assetId).then((e=>e&&this.assetManagerService.getMesh(e))))))}))}init(){return e(this,void 0,void 0,(function*(){this.preInit(),Ae.clear(),yield this.prefetchAssets(),yield Promise.all(this.dataProvider.getObjects().map((e=>this.materialize(e)))),yield this.initActorsPostInit()}))}initActorsPostInit(t=this.actorInstances){const i=t.map((t=>e(this,void 0,void 0,(function*(){var e,i,r,a,s;const o=t.object.userData.src;if("vfx"===o.type)return Promise.resolve();const n=yield this.assetsService.getAsset(o.assetId),l=Object.assign(Object.assign({},null!==(i=null===(e=null==n?void 0:n.actor)||void 0===e?void 0:e.params)&&void 0!==i?i:{}),null!==(a=null===(r=o.actor)||void 0===r?void 0:r.params)&&void 0!==a?a:{});this.removeVfxChildActors(t);for(const e of null!==(s=o.actor.innerParams)&&void 0!==s?s:[])yield this.applyActorComponentParams(t,e.path.slice(),e.params);const c=yield Me(l,t.constructor,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider);Object.assign(t,c),this.addVfxChildActors(t);try{return yield this.actorProvider.initActor(t)}catch(e){console.error(`Failed to initiate actor (name="${o.name}", id=${o.id})`,e)}}))));return Promise.all(i)}addVfxChildActors(e,t=e){for(const i of Object.keys(t))t[i]instanceof ye?null!=t[i].actor&&(console.log("add actor to world",t[i].actor),e.object.add(t[i].actor.object)):t[i]instanceof me&&this.addVfxChildActors(e,t[i])}removeVfxChildActors(e,t=e){for(const i of Object.keys(t))if(t[i]instanceof ye){if(null!=t[i].actor){t[i].actor.onEndPlay(),console.log("remve actor from world",t[i].actor),e.object.remove(t[i].actor.object)}}else t[i]instanceof me&&this.removeVfxChildActors(e,t[i])}applyActorComponentParams(t,i,r){return e(this,void 0,void 0,(function*(){const e=i.length,a=i.shift();if(0==e){const e=yield Me(r,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);for(const[i,r]of Object.entries(e))null!=r&&(t[i]=r)}else null!=t[a]&&(yield this.applyActorComponentParams(t[a],i,r))}))}canAssetBeInstanced(t){return e(this,void 0,void 0,(function*(){if(!this._canBeInstancedCache.has(t.assetId)){const e=yield this.createFromAsset(t);if(null==e)return!1;const i=[];e.traverse((e=>{!J(e)&&e.isMesh&&i.push(e)}));const r=1==i.length&&0==i[0].children.length,a=!0;this._canBeInstancedCache.set(t.assetId,r&&a)}return this._canBeInstancedCache.get(t.assetId)}))}preInit(){var e;null===(e=this.renderingView)||void 0===e||e.onLoop((()=>{var e;return null===(e=this.sky)||void 0===e?void 0:e.position.copy(this.renderingView.camera.position)}))}initWithInstancing(){return e(this,void 0,void 0,(function*(){this.preInit();const t=new L;for(const i of this.dataProvider.getObjects())yield De(i,((i,r,a)=>e(this,void 0,void 0,(function*(){var e,s;const o="asset_mesh"==i.type&&(yield this.canAssetBeInstanced(i))?i.assetId+JSON.stringify(null!==(e=i.materialAssignments)&&void 0!==e?e:[]):"other";"other"!==o&&r&&(null===(s=r.children)||void 0===s?void 0:s.length)>0&&r.children.splice(r.children.findIndex((e=>e.id===i.id)),1),"other"===o&&r||t.push(o,Object.assign(Object.assign({},i),{parentTransform:a}))}))));for(const[e,i]of t.entries())if("other"!==e&&i.length>0){const e=yield this.createFromAsset(i[0]);if(null==e)continue;const t=yield this.createInstancedMesh(i,e),r=new H;r.add(t),r.userData.src=i[0],e instanceof H&&(r.collisionShapes=e.collisionShapes),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}else yield Promise.all(i.map((e=>this.materialize(e))));yield this.initActorsPostInit()}))}createInstancedMesh(t,r){var a,o;return e(this,void 0,void 0,(function*(){const e=r.children.filter((e=>!J(e)))[0],n=yield this.assetsService.getAsset(t[0].assetId);yield this.applyMaterials(r,je(t[0].materialAssignments,n.materialAssignments)),e.updateMatrix();const l=e.geometry.clone().applyMatrix4(e.matrix),c=new i.InstancedMesh(l,e.material.clone(),t.length);c.material.side=i.FrontSide;for(let e=0;e<t.length;e++){const r=(new i.Matrix4).compose((new A).fromArray(t[e].position),(new v).setFromEuler((new s).fromArray(t[e].rotation)),(new A).fromArray(t[e].scale)),a=(new re).copy(t[e].parentTransform).multiply(r);c.setMatrixAt(e,a)}return c.castShadow=null===(a=n.castShadow)||void 0===a||a,c.receiveShadow=null===(o=n.receiveShadow)||void 0===o||o,c}))}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("actor"==e.type){const t=this.materializedActors.get(e.id);null!=t&&(t.disposed.next(!0),t.onEndPlay(),this.removeVfxChildActors(t))}const t=this.sceneObjectMap.get(e.id);null==t||t.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter((t=>{var i;return(null===(i=t.object.userData.src)||void 0===i?void 0:i.id)===e.id})).forEach((e=>this.components.splice(this.components.indexOf(e,1)))),this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))})),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex((t=>t.source.id===e.id));if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return U(this.scene,(t=>{var i;return(null===(i=t.userData.src)||void 0===i?void 0:i.assetId)==e}),(e=>null!=e.userData.src))}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter((e=>"null"!==e.materialId)).map((t=>this.applyMaterial(e,t))))}applyMaterial(t,i){const r=[];return t.traverse((t=>e(this,void 0,void 0,(function*(){if(t instanceof d||t.isMesh)for(const e of fe(t.material))e.hasOwnProperty("color")&&r.push(t)})))),Promise.all(r.map((t=>e(this,void 0,void 0,(function*(){var e,r,a,s;if(t.material instanceof Array)for(let a=0;a<t.material.length;a++){const s=t.material[a];if(null==s.color)continue;const o="#"+s.color.getHexString(),n=s.name;if(o===i.color&&(s.name===i.name||null==i.name)||t.userData["originalColor_"+a]===i.color&&t.userData["originalMaterialName_"+a]===i.name){const s=yield this.assetsService.getAsset(i.materialId),l=t.material[a];s&&(t.material[a]=yield materialFromAsset(s,this.renderingView,this.assetsService,this.assetManagerService,this.shaders),t.userData["originalColor_"+a]=null!==(e=t.userData["originalColor_"+a])&&void 0!==e?e:o,t.userData["originalMaterialName_"+a]=null!==(r=t.userData["originalMaterialName_"+a])&&void 0!==r?r:n,this.inEditor&&this._originalMaterials.set(t.id+"#"+a,l))}}else{const e="#"+t.material.color.getHexString(),r=t.material.name;if(e===i.color&&(t.material.name===i.name||null==i.name)||t.userData.originalColor===i.color&&t.userData.originalName===i.name){const o=yield this.assetsService.getAsset(i.materialId),n=t.material;o&&(t.material=yield materialFromAsset(o,this.renderingView,this.assetsService,this.assetManagerService,this.shaders),t.userData.originalColor=null!==(a=t.userData.originalColor)&&void 0!==a?a:e,t.userData.originalMaterialName=null!==(s=t.userData.originalMaterialName)&&void 0!==s?s:r,this.inEditor&&this._originalMaterials.set(t.id,n))}}})))))}unapplyMaterials(t){t.traverse((t=>e(this,void 0,void 0,(function*(){var e,i;if(t instanceof d)if(t.material instanceof Array)for(let i=0;i<t.material.length;i++)t.material[i]=null!==(e=this._originalMaterials.get(t.id+"#"+i))&&void 0!==e?e:t.material[i];else t.material=null!==(i=this._originalMaterials.get(t.id))&&void 0!==i?i:t.material}))))}updateActors(t){this.actorTypes=t;const i=new Set(Object.values(_));U(this.scene,(e=>{var t,r;return(null===(t=e.userData.src)||void 0===t?void 0:t.id)&&"actor"===e.userData.src.type&&this.materializedActors.has(null===(r=e.userData.src)||void 0===r?void 0:r.id)&&!i.has(e.userData.src.actor.type)})).forEach((t=>e(this,void 0,void 0,(function*(){this.remove(t.userData.src),yield this.materializeAndInitActor(t.userData.src)}))))}updateShaders(e){this.shaders=e;for(const[e,t]of Ae.entries())t.userData.customShaderName&&Ae.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),U(this.scene,(e=>!0)).forEach((e=>{e.traverse((e=>{var t,i;if(e instanceof d){if(null!=(null===(t=e.material.userData)||void 0===t?void 0:t.customShaderName)){const t=null===(i=function(e,t){if(t(e))return e;let i;return e.traverseAncestors((e=>{null==i&&t(e)&&(i=e)})),i}(e,(e=>{var t;return null!=(null===(t=e.userData.src)||void 0===t?void 0:t.id)})))||void 0===i?void 0:i.userData.src;null!=t&&this.update(t)}}}))}))}update(t){return e(this,void 0,void 0,(function*(){if("sky"===t.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(t);const e=this.sceneObjectMap.get(t.id);if(e){const r=this.findParent(t);if(null!=r&&r.uuid!=e.uuid?r.attach(e):console.error("Parent is wrong"),"prefab"!==t.type){this.unapplyMaterials(e);this.inEditor&&t.hidden&&!1?e.traverse((e=>{e instanceof d&&(e.material.wireframe=!0)})):e.traverse((e=>{e instanceof d&&(e.material.wireframe=!1)}))}if("asset_mesh"===t.type){const i=yield this.assetsService.getAsset(t.assetId);je(t.materialAssignments,i.materialAssignments).forEach((t=>this.applyMaterial(e,t)))}else"shape_mesh"===t.type&&this.applyMaterials(e,t.materialAssignments);let s=!1;if(e.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(s=!0)})),s||(e.position.fromArray(t.position),e.scale.fromArray(t.scale),e.rotation.fromArray(t.rotation)),this.applyVertexMaterials(t,e),"light"==t.type)if("point"==t.light.type){const i=e;i.color=new a(t.light.point.color),i.intensity=t.light.point.intensity,i.decay=t.light.point.decay,i.castShadow=t.light.point.castShadow,i.distance=Math.max(t.light.point.distance,0)}else"directional"===t.light.type?this.applyDirectionalLight(t.light.directional):"ambient"===t.light.type&&this.applyDirectionalAmbientLight(e,t.light.ambient);else if("landscape"===t.shape)this.applyHeightMaps(e,t.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter((e=>e.source.id===t.id)).forEach((e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>!0))));else if("global_fog"===t.type){const e=(this.scene.fog instanceof n?"density":"linear")!==t.fog.type;this.scene.fog=Ie(t.fog),e&&(i=this.scene).traverse((e=>{if(e instanceof d){const t=e.material;t instanceof j&&(i.fog instanceof o?(t.uniforms.fogFar.value=i.fog.far,t.uniforms.fogNear.value=i.fog.near):i.fog instanceof n&&(t.uniforms.density={value:i.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}})),this.fixFogColor()}else if("actor"===t.type){if(this.materializedActors.has(t.id)){const e=this.editorActorParamSnapshot.get(t.id);null!=e&&e===JSON.stringify(t.actor)||(console.log("Rematerializing actor because parameters changed"),this.remove(t),yield this.materializeAndInitActor(t))}}else if("shape_mesh"===t.type){const i=yield this.createMeshByShape(t.shape,e.material,t.shapeParams);e instanceof G&&(e.geometry=i.geometry,e.collisionShape=i.collisionShape)}("asset_mesh"===t.type||"shape_mesh"===t.type&&"landscape"!==t.shape)&&we(e,t.castShadow,t.receiveShadow),t.name&&t.name.length>0&&(e.name=t.name),this.updated$.next({object:e,source:t})}else{const e=yield this.materializeAndInitActor(t);this.updated$.next({object:e,source:t})}var i}))}materializeAndInitActor(t,i=this.findParent(t)){return e(this,void 0,void 0,(function*(){const r=yield this.materialize(t,i);return De(t,(t=>e(this,void 0,void 0,(function*(){if("actor"===t.type){const e=this.materializedActors.get(t.id);null!=e?yield this.initActorsPostInit([e]):console.error(`Something went wrong when creating actor ${t.id}`)}})))),r}))}findParent(e){const t=this.dataProvider.getObjects().flatMap((t=>t.id===e.id?null:R(t,(t=>{var i;return null===(i=t.children)||void 0===i?void 0:i.some((t=>t.id===e.id))}),(()=>!0))))[0];return null==t?this.scene:null!=t?U(this.scene,(e=>{var i,r;return(null===(r=null===(i=e.userData)||void 0===i?void 0:i.src)||void 0===r?void 0:r.id)===t.id}),(e=>{var t;return null!=(null===(t=e.userData)||void 0===t?void 0:t.src)}))[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new a(this.scene.fog.color).convertSRGBToLinear())}findMeshWithGeometry(e){let t;return e.traverse((e=>{e instanceof d&&e.geometry&&(t=e)})),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;const i=$(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof d){const t=ee(e,!1);if(null!=t){for(let e=0;e<t.array.length;e++)t.setX(e,0);t.needsUpdate=!0}}}));const r=new Set;for(const[e,a]of i.entries()){const i=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let s=!1;if(null==i)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=ee(i,!0);for(let e=0;e<o.array.length;e++)o.setX(e,0);for(const e of a)o.setX(e.i,e.w[0]),o.setY(e.i,e.w[1]),o.setZ(e.i,e.w[2]),s=!0;s&&r.add(e)}this.inEditor&&this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>r.has(e.name)))))}materialize(t,i,a=!1){var s,o,n,c;return e(this,void 0,void 0,(function*(){let e;switch(t.type){case"asset_mesh":e=yield this.createFromAsset(t);break;case"shape_mesh":e=yield this.createFromShape(t);break;case"light":e=yield this.createLight(t);break;case"particles":e=yield this.createParticleSystem(t),t.collisionDetection=!1;break;case"global_fog":this.scene.fog=Ie(t.fog),this.fixFogColor(),e=new l;break;case"sky":this.sky=he(),this.updateSky(t),e=this.sky;break;case"actor":e=yield this.createFromActor(t);break;case"group":e=new l;break;case"prefab":e=yield this.createFromPrefabAsset(t);break;case"vfx":e=yield this.createFromVfx(t);break;default:if(this.inEditor)throw new Error("unknown type "+t.type);console.warn(`Failed to materialize object. Unknown type '${t.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=e){if(t.name&&t.name.length>0&&(e.name=t.name),e.position.fromArray(t.position),e.scale.fromArray(t.scale),e.rotation.fromArray(t.rotation),a||(e.userData.src=t),!this.inEditor){const i=null!==(s=t.components)&&void 0!==s?s:[],r=null!=t.assetId&&null!==(n=null===(o=yield this.assetsService.getAsset(t.assetId))||void 0===o?void 0:o.components)&&void 0!==n?n:[];i.push(...r),i.length>0?e.userData.componentRefs=yield Promise.all(i.map(((i,r)=>this.createComponent(e,t,i,r)))):"asset_mesh"==t.type&&function(e){e.traverse((e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}));const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}(e)}if(this.inEditor){let t=null;e instanceof G&&(t=function(e){if(e instanceof W)return new d(new r(...e.offset.toArray()),Pe);return null}(e.collisionShape)),null!=t&&(t.layers.disable(0),t.layers.enable(18),t.scale.multiplyScalar(1.1),e.add(t))}return this.objectMap.set(e.uuid,t),this.sceneObjectMap.set(t.id,e),null==i?this.scene.add(e):null==i||i.add(e),null!=t.children&&(yield Promise.all(null===(c=t.children)||void 0===c?void 0:c.map((t=>this.materialize(t,e,a))))),e}}))}updateSky(t){var r;return e(this,void 0,void 0,(function*(){if(null==(null===(r=null==t?void 0:t.sky)||void 0===r?void 0:r.materialId))return void(this.sky.material=ue);const e=yield this.assetsService.getAsset(t.sky.materialId),a=yield materialFromAsset(e,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);a.side=i.BackSide,null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}))}createComponent(t,i,r,a){return e(this,void 0,void 0,(function*(){const e=new ge[r.path+"/"+r.className],s=i.id+a;e.id=s,e.object=t;for(const t of r.params)null!=t.value&&(e[t.name]=t.value);return this.components.push(e),s}))}createFromActor(t){var i,r,a;return e(this,void 0,void 0,(function*(){const e=null!==(r=null===(i=this.actorTypes.find((e=>{var i;return e.name===(null===(i=t.actor)||void 0===i?void 0:i.type)})))||void 0===i?void 0:i.type)&&void 0!==r?r:_[null===(a=t.actor)||void 0===a?void 0:a.type];if(null==e)return null;this.inEditor&&this.editorActorParamSnapshot.set(t.id,JSON.stringify(t.actor));const o=yield this.actorProvider.create(e,(new A).fromArray(t.position),(new s).fromArray(t.rotation),!0);return this.materializedActors.set(t.id,o),null==o?void 0:o.object}))}createFromVfx(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetsService.getAsset(t.assetId);null==e&&console.error("Could not find asset",t);const i=ve,r=yield this.actorProvider.create(i,(new A).fromArray(t.position),(new s).fromArray(t.rotation),!1);return yield r.fromAsset(e),r.play(),this.materializedActors.set(t.id,r),null==r?void 0:r.object}))}cleanup(){this.materializedActors.clear()}createFromShape(t){var i,r,s;return e(this,void 0,void 0,(function*(){const e=this.inEditor&&t.hidden;let o;if("landscape"==t.shape)o=this.createLandscape(t);else{let s=new m({name:"Default",color:new a("#aaaaaa"),visible:this.inEditor||!t.hidden,wireframe:!!e});const n=yield this.createMeshByShape(t.shape,s,t.shapeParams);n.castShadow=null===(i=t.castShadow)||void 0===i||i,n.receiveShadow=null!==(r=t.castShadow)&&void 0!==r&&r,t.collisionDetection||(n.collisionShape=null),o=n,this._originalMaterials.set(o.id,n.material),o.traverse((e=>{}))}return e||((null!==(s=t.materialAssignments)&&void 0!==s?s:[]).filter((e=>null!=e.materialId)).forEach((e=>this.applyMaterial(o,e))),this.applyVertexMaterials(t,o)),o}))}createLandscape(e){var t;if(null==(null===(t=e.landscape)||void 0===t?void 0:t.options))return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new l;const i=X(e.landscape.options);this.applyHeightMaps(i,e.landscape.heightMaps,!0);const r=new Y(e,this.renderingView,i,this.assetManagerService,this.assetsService,this.shaders,(t=>{var i;(null!==(i=e.materialAssignments)&&void 0!==i?i:[]).filter((e=>null!=e.materialId)).forEach((e=>this.applyMaterial(t,e)))}));return this.landscapeManagers.push(r),r.refreshGeometry(),i}applyHeightMaps(e,t,i=!1){const r=new q(e.sections);for(const e of null!=t?t:[]){const t=r.find(e.x,e.y);if(!t)return;const i=t.geometry.getAttribute("position");for(const t of e.points)i.setY(t.i,t.y);i.needsUpdate=!0}const a=e.sections;a.forEach((e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()})),this.inEditor&&!i||setTimeout((()=>Z(a)),50)}createMeshByShape(t,i,r={}){return e(this,void 0,void 0,(function*(){if("landscape"!==t&&ce.includes(t)){const e=yield prepareShapeParameters(null!=r?r:{});return"cylinder"==t&&e.openEnded,new G(le[t].geometry(e),i,le[t].collision(e))}if(this.inEditor)throw new Error(`Unsupported shape '${t}'`);console.warn(`Failed to create shape. Unsupported shape '${t}'. This might be because the hology/core library is not compatible with the editor version.`)}))}createFromAsset(t){var i,r,a,s;return e(this,void 0,void 0,(function*(){const e=yield this.assetsService.getAsset(t.assetId);if(null==e)return void console.warn(`Can not find asset with id ${t.assetId} and name ${t.name}`);let{scene:o}=yield this.assetManagerService.getMesh(e);je(t.materialAssignments,e.materialAssignments).forEach((e=>this.applyMaterial(o,e)));const n=null===(r=null!==(i=t.receiveShadow)&&void 0!==i?i:!!e.receiveShadow)||void 0===r||r,l=null!==(s=null!==(a=t.castShadow)&&void 0!==a?a:!!e.castShadow)&&void 0!==s&&s;return o.receiveShadow=n,we(o,l,n),t.collisionDetection||(o.collisionShapes=[]),this.applyVertexMaterials(t,o),o.traverse((e=>{e instanceof d&&"computeBoundsTree"in e.geometry&&e.geometry.computeBoundsTree()})),o}))}createFromPrefabAsset(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetsService.getAsset(t.assetId);if(null==e)return void console.warn(`Can not find asset with id ${t.assetId} and name ${t.name}`);const i=new l;return e.prefab.objects.filter((e=>"global_fog"!==e.type)).forEach((e=>this.materialize(e,i,!0))),i}))}createParticleSystem(t){return e(this,void 0,void 0,(function*(){const e=yield this.assetsService.getAsset(t.assetId),r=new p;return yield b.fromJSONAsync(e.particleSystem,i).then((e=>{const t=new M(r,i);e.addRenderer(t),this.renderingView.onLoop((t=>e.update()))})),r}))}createLight(t){var i;return e(this,void 0,void 0,(function*(){if("point"===t.light.type){const e=new f(t.light.point.color,t.light.point.intensity,t.light.point.distance,t.light.point.decay);if(e.castShadow=null===(i=t.light.point.castShadow)||void 0===i||i,this.inEditor){const t=new y(.3,10,10),i=new m({color:new a(16771709)}),r=new d(t,i);e.add(r)}return e}return"directional"===t.light.type?(this.applyDirectionalLight(t.light.directional),new l):"ambient"===t.light.type?(this.applyDirectionalAmbientLight(null,t.light.ambient),new l):void 0}))}applyDirectionalAmbientLight(e,t){const i=this.scene.children.find((e=>e.name===de));null!=i?(i.intensity=t.intensity,i.color.set(t.color),i.groundColor.set(t.color)):console.warn("Couldn't find ambient light")}applyDirectionalLight(e){for(const t of this.renderingView.csm.lights)t.intensity=e.intensity,t.color.set(e.color),t.castShadow=e.castShadow;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe()}}function we(e,t,i){e.castShadow=t,e.receiveShadow=i,e.traverse((e=>{e.castShadow=t,e.receiveShadow=i}))}const Ae=new Map,Se=new h({color:16711935}),be=new Map;export function materialFromAsset(t,r,s,o,n,l=!0){var c,d,h,m,p,f,v,y,g,w,A;return e(this,void 0,void 0,(function*(){const e=JSON.stringify(t.material);if(l&&Ae.has(e))return Ae.get(e);const S={opacity:t.material.params.opacity,map:null,emissive:null!==(c=t.material.params.emissive)&&void 0!==c?c:null,metalness:null!==(d=t.material.params.metalness)&&void 0!==d?d:0,flatShading:null!==(h=t.material.params.flatShading)&&void 0!==h&&h,color:new a(t.material.params.color).convertSRGBToLinear(),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},b={};if(null!=t.material.params.map){const e=t.material.params.map,i=yield s.getAsset(e);null!=i&&(S.map=yield o.getTexture(i))}let M;switch(t.material.type){case"phong":M=new u(Object.assign(Object.assign({},S),b));break;case"water":M=te(S,r);break;case"grassFoliage":M=Q({color:S.color,map:S.map},r);break;case"grass":M=K(Object.assign(Object.assign({},S),{colorTwo:new a(t.material.params.colorTwo),colorThree:new a(t.material.params.colorThree)}),r);break;case"standard":case"lambert":case"shader":const e=null!==(m={standard:oe,lambert:ne}[t.material.type])&&void 0!==m?m:null===(p=n.find((e=>e.name==t.material.shader)))||void 0===p?void 0:p.type;if(e){const i=new e,a=yield Me(null!==(v=null===(f=t.material)||void 0===f?void 0:f.shaderParams)&&void 0!==v?v:{},e,s,o,null,r,n);Object.assign(i,a);try{M=i.build()}catch(e){console.log("Shader runtime error: "+e),be.has(t.material.shader)||be.set(t.material.shader,Se.clone()),M=be.get(t.material.shader)}M.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),M=Se;break;default:throw new Error("Unsupported material type"+t.material.type)}return null==r||r.csm.setupMaterial(M),l&&Ae.set(e,M),M.side=null!==(g=null!==(y=t.material.side)&&void 0!==y?y:M.side)&&void 0!==g?g:i.FrontSide,M.transparent=null!==(A=null!==(w=t.material.transparent)&&void 0!==w?w:S.transparent)&&void 0!==A&&A||M.transparent,M}))}function Me(t,i,r,a,s,o,n,l){return e(this,void 0,void 0,(function*(){const e={};for(const[i,c]of Object.entries(t)){const t=yield xe(c,r,a,s,o,n,l);null!=t&&(e[i]=t)}return e}))}export function prepareShapeParameters(t){return e(this,void 0,void 0,(function*(){const e={};for(const[i,r]of Object.entries(t)){const t=yield xe(r,null,null,null);null!=t&&(e[i]=t)}return e}))}function xe(t,i,r,o,n,l,c){return e(this,void 0,void 0,(function*(){if(null==t||null==t.value||""==t.value)return null;const e=t.value;switch(t.type){case ie.Number:case ie.FloatNode:let d="string"==typeof e?parseFloat(e):e;return t.type===ie.FloatNode?P(d):d;case ie.Texture:return yield r.getTexture(yield i.getAsset(e));case ie.Sampler2DNode:return C(yield r.getTexture(yield i.getAsset(e)));case ie.Boolean:return e;case ie.BooleanNode:return x(e);case ie.Vector2:case ie.Vec2Node:if("object"==typeof e){const i=e instanceof Array?(new w).fromArray(e):new w(e.x,e.y);return t.type===ie.Vec2Node?O(i):i}return null;case ie.Vector3:case ie.Vec3Node:if("object"==typeof e){const i=e instanceof Array?(new A).fromArray(e):new A(e.x,e.y,e.z);return t.type===ie.Vec3Node?k(i):i}return null;case ie.Color:case ie.RgbNode:const h=new a(e).convertSRGBToLinear();return t.type===ie.RgbNode?V(h):h;case ie.String:return e;case ie.BaseActor:const u=e;return null==o&&console.warn("Class parameters can not be prepared as actors are not passed in"),null==o?void 0:o.get(u);case ie.Euler:const m=e;return(new s).fromArray(m);case ie.Object3D:return(yield r.getMesh(yield i.getAsset(e))).scene;case ie.Material:return yield materialFromAsset(yield i.getAsset(e),n,i,r,l);case ie.AudioBuffer:return yield r.getAudio(yield i.getAsset(e));case ie.VisualEffect:const p=yield i.getAsset(e);if(null==c){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in p){const e=yield c.create(ve);return yield e.fromAsset(p),new ye(e)}console.error("Using a non-vfx asset for visual effect parameter")}return null}))}function Ie(e){var t,i;return"linear"===e.type?new o(new a(e.color),null!==(t=e.near)&&void 0!==t?t:100,null!==(i=e.far)&&void 0!==i?i:1e3):"density"===e.type?new n(e.color,e.density):void console.warn("Invalid fog type",e)}const Pe=new m({color:4229780});function De(t,r,a,o){var n;return e(this,void 0,void 0,(function*(){null==o&&(o=(new re).identity()),yield r(t,a,o);const e=o.clone().multiply(function(e,t){return t.compose((new A).fromArray(e.position),(new v).setFromEuler((new s).fromArray(e.rotation)),(new A).fromArray(e.scale))}(t,new i.Matrix4));return Promise.all((null!==(n=t.children)&&void 0!==n?n:[]).map((i=>De(i,r,t,e))))}))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?ie.Number:t instanceof D||"function"==typeof e.prototype.isFloat?ie.FloatNode:t instanceof g||e===g||e.isTexture?ie.Texture:t instanceof se||e===N?ie.Sampler2DNode:t instanceof Boolean||e===Boolean?ie.Boolean:t instanceof I?ie.BooleanNode:t instanceof a||e==a?ie.Color:t instanceof E||"function"==typeof e.prototype.isRgb?ie.RgbNode:t instanceof w||e==w?ie.Vector2:t instanceof F||"function"==typeof e.prototype.isVec2?ie.Vec2Node:t instanceof A||e==A?ie.Vector3:t instanceof z||"function"==typeof e.prototype.isVec3?ie.Vec3Node:t instanceof String||e===String?ie.String:t instanceof ae||e==ae||e.prototype instanceof ae||e.prototype==ae?ie.BaseActor:t instanceof s||e==s?ie.Euler:t instanceof p||e==p?ie.Object3D:t instanceof c||e==c?ie.Material:t instanceof AudioBuffer||e==AudioBuffer?ie.AudioBuffer:t instanceof ye||e==ye?ie.VisualEffect:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,i={}){return Object.fromEntries(e.map((e=>{var r,a,s;return[e.name,{type:toSerializedParamType(e.type),value:null!==(s=null!==(a=null===(r=t[e.name])||void 0===r?void 0:r.value)&&void 0!==a?a:i[e.name])&&void 0!==s?s:customParameterDefaultValueByType.get(toSerializedParamType(e.type))}]})))}export function prepareCustomParamsFromType(e,t,i=null){const r=T(e);if(0===r.length)return{};let a;null!=i?pe(i,(()=>{a=i.get(e)})):a=new e;const s={};for(const e of r){const t=a[e.name];if(null!=t){const i=serializeCustomParameter(e.type,t);null!=i&&(s[e.name]=i)}}return prepareCustomParams(r,t,s)}export function serializeCustomParameter(e,t){function i(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case w:return t instanceof w?t.toArray():void i();case A:return t instanceof A?t.toArray():void i();case S:return t instanceof S?t.toArray():void i();case a:return t instanceof a?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new a(t).getHexString():void i();case String:return t;case s:return t instanceof s?t.toArray():void i()}}function je(e,t){return function(e,t,i){const r=[],a=new Set;for(const s of[...null!=e?e:[],...null!=t?t:[]]){const e=i(s);a.has(e)||(a.add(e),r.push(s))}return r}((null!=e?e:[]).filter((e=>Ve(e.materialId))),(null!=t?t:[]).filter((e=>Ve(e.materialId))),(e=>e.color+e.name))}function Ve(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[ie.RgbNode,"#000000"],[ie.Color,"#000000"],[ie.Vector4,[0,0,0,0]],[ie.Vec4Node,[0,0,0,0]],[ie.Vector3,[0,0,0]],[ie.Vec3Node,[0,0,0]],[ie.Vector2,[0,0]],[ie.Vec2Node,[0,0]],[ie.Euler,[0,0,0,"XYZ"]]]);
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -3,7 +3,8 @@ import { ParticleSystemConfig } from '../effects/particles/particle-system-confi
3
3
  import { LandscapeInitOptions } from '../scene/landscape/landscape';
4
4
  import { LibraryShapeType } from './objects/shapes';
5
5
  import { Side } from 'three';
6
- export type AssetType = 'mesh' | 'material' | 'shape' | 'particles' | 'light' | 'texture' | 'actor' | 'audio' | 'prefab';
6
+ import { VfxAssetData } from '../effects/vfx/vfx-asset';
7
+ export type AssetType = 'mesh' | 'material' | 'shape' | 'particles' | 'light' | 'texture' | 'actor' | 'audio' | 'prefab' | 'vfx';
7
8
  export type ShapeType = LibraryShapeType | 'landscape';
8
9
  export type LightType = 'point' | 'directional' | 'ambient';
9
10
  export declare enum SerializedParamType {
@@ -26,7 +27,8 @@ export declare enum SerializedParamType {
26
27
  Material = 16,
27
28
  AudioBuffer = 17,
28
29
  Vector4 = 18,
29
- Vec4Node = 19
30
+ Vec4Node = 19,
31
+ VisualEffect = 20
30
32
  }
31
33
  export type CustomParamValue = {
32
34
  type: SerializedParamType;
@@ -72,7 +74,11 @@ export interface Asset {
72
74
  texture?: TextureSettings;
73
75
  receiveShadow?: boolean;
74
76
  castShadow?: boolean;
77
+ vfx?: VfxAssetData;
75
78
  }
79
+ export type VfxAsset = Asset & {
80
+ vfx: VfxAssetData;
81
+ };
76
82
  export type MaterialType = 'standard' | 'phong' | 'lambert' | 'shader' | 'water' | 'grass' | 'grassFoliage';
77
83
  export type MaterialParameters = {
78
84
  opacity: number;
@@ -1,4 +1,4 @@
1
- export var SerializedParamType;!function(e){e[e.FloatNode=0]="FloatNode",e[e.Number=1]="Number",e[e.Texture=2]="Texture",e[e.Sampler2DNode=3]="Sampler2DNode",e[e.Boolean=4]="Boolean",e[e.BooleanNode=5]="BooleanNode",e[e.Vector2=6]="Vector2",e[e.Vec2Node=7]="Vec2Node",e[e.Vector3=8]="Vector3",e[e.Vec3Node=9]="Vec3Node",e[e.Color=10]="Color",e[e.RgbNode=11]="RgbNode",e[e.String=12]="String",e[e.BaseActor=13]="BaseActor",e[e.Euler=14]="Euler",e[e.Object3D=15]="Object3D",e[e.Material=16]="Material",e[e.AudioBuffer=17]="AudioBuffer",e[e.Vector4=18]="Vector4",e[e.Vec4Node=19]="Vec4Node"}(SerializedParamType||(SerializedParamType={}));
1
+ export var SerializedParamType;!function(e){e[e.FloatNode=0]="FloatNode",e[e.Number=1]="Number",e[e.Texture=2]="Texture",e[e.Sampler2DNode=3]="Sampler2DNode",e[e.Boolean=4]="Boolean",e[e.BooleanNode=5]="BooleanNode",e[e.Vector2=6]="Vector2",e[e.Vec2Node=7]="Vec2Node",e[e.Vector3=8]="Vector3",e[e.Vec3Node=9]="Vec3Node",e[e.Color=10]="Color",e[e.RgbNode=11]="RgbNode",e[e.String=12]="String",e[e.BaseActor=13]="BaseActor",e[e.Euler=14]="Euler",e[e.Object3D=15]="Object3D",e[e.Material=16]="Material",e[e.AudioBuffer=17]="AudioBuffer",e[e.Vector4=18]="Vector4",e[e.Vec4Node=19]="Vec4Node",e[e.VisualEffect=20]="VisualEffect"}(SerializedParamType||(SerializedParamType={}));
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,9 +1,11 @@
1
1
  import { BoxCollisionShape, CapsuleCollisionShape, CollisionShape, ConeCollisionShape, ConvexPolyhedronCollisionShape, CylinderCollisionShape, PlaneCollisionShape, SphereCollisionShape, TrimeshCollisionShape } from "../collision/collision-shape";
2
- import { BoxGeometry, PlaneGeometry, BufferGeometry, CylinderGeometry, SphereGeometry, TorusGeometry, ConeGeometry, CircleGeometry, CapsuleGeometry } from "three";
2
+ import { BoxGeometry, PlaneGeometry, BufferGeometry, CylinderGeometry, SphereGeometry, TorusGeometry, ConeGeometry, CircleGeometry, CapsuleGeometry, Vector2 } from "three";
3
3
  import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry';
4
4
  import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry';
5
+ import { Color } from "three-nebula";
6
+ type AVec3 = [number, number, number];
5
7
  type ShapeParameterDef<T = boolean | number | string> = {
6
- type: T extends number ? 'number' : T extends string ? 'string' : T extends boolean ? 'boolean' : never;
8
+ type: T extends number ? 'number' : T extends string ? 'string' : T extends Vector2 ? 'vec2' : T extends AVec3 ? 'vec3' : T extends Color ? 'color' : T extends boolean ? 'boolean' : never;
7
9
  default: T;
8
10
  float?: boolean;
9
11
  };