@hology/core 0.0.93 → 0.0.95
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +14 -14
- package/README.md +2 -2
- package/dist/effects/vfx/initializsers.d.ts +4 -1
- package/dist/effects/vfx/initializsers.d.ts.map +1 -1
- package/dist/effects/vfx/initializsers.js +1 -1
- package/dist/effects/vfx/rates.d.ts +8 -0
- package/dist/effects/vfx/rates.d.ts.map +1 -1
- package/dist/effects/vfx/rates.js +1 -1
- package/dist/effects/vfx/vfx-actor.d.ts +1 -1
- package/dist/effects/vfx/vfx-defs.d.ts +3 -1
- package/dist/effects/vfx/vfx-defs.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-defs.js +1 -1
- package/dist/effects/vfx/vfx-materializer.d.ts +1 -2
- package/dist/effects/vfx/vfx-materializer.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/effects/vfx/vfx-renderers.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-renderers.js +1 -1
- package/dist/gameplay/actors/builtin/navmesh-actor.d.ts +11 -0
- package/dist/gameplay/actors/builtin/navmesh-actor.d.ts.map +1 -1
- package/dist/gameplay/actors/builtin/navmesh-actor.js +1 -1
- package/dist/gameplay/ai/dynamic-tiled-navmesh.d.ts.map +1 -1
- package/dist/gameplay/ai/dynamic-tiled-navmesh.js +1 -1
- package/dist/gameplay/services/physics/physics-system.d.ts.map +1 -1
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/collision/collision-shape-import.d.ts.map +1 -1
- package/dist/scene/collision/collision-shape-import.js +1 -1
- package/dist/scene/materializer.d.ts +11 -2
- package/dist/scene/materializer.d.ts.map +1 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model.d.ts +2 -2
- package/dist/scene/model.d.ts.map +1 -1
- package/dist/scene/objects/prefab.d.ts +8 -0
- package/dist/scene/objects/prefab.d.ts.map +1 -0
- package/dist/scene/objects/prefab.js +4 -0
- package/dist/scene/scene-data-service.d.ts +17 -7
- package/dist/scene/scene-data-service.d.ts.map +1 -1
- package/dist/scene/scene-data-service.js +1 -1
- package/dist/scene/storage/storage.d.ts +9 -8
- package/dist/scene/storage/storage.d.ts.map +1 -1
- package/dist/scene/storage/storage.js +1 -1
- package/dist/shader-nodes/particle.d.ts +4 -2
- package/dist/shader-nodes/particle.d.ts.map +1 -1
- package/dist/shader-nodes/particle.js +1 -1
- package/dist/utils/math.js +1 -1
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import*as i from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as r,filter as n,map as a,Subject as c,takeUntil as l}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as y,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as v,Scene as x,Vector3 as B}from"three";import{Service as b}from"typedi";import{AssetMeshInstance as A}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as C,CapsuleCollisionShape as D,ConeCollisionShape as z,ConvexPolyhedronCollisionShape as R,CylinderCollisionShape as M,PhysicalShapeMesh as S,PlaneCollisionShape as T,SphereCollisionShape as E,TrimeshCollisionShape as W}from"../../../index.js";import{LandscapeGroup as F}from"../../../scene/landscape/landscape.js";import{ViewController as V}from"../render.js";import{World as _}from"../world.js";import*as I from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as j}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as L}from"./abstract-physics-system.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new B,this.hitNormal=new B}}export var PhysicsBodyType;!function(e){e[e.dynamic=1]="dynamic",e[e.static=2]="static",e[e.kinematic=4]="kinematic",e[e.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));let P=class extends L{set showDebug(e){this.shouldRenderDebug=e,this.debugMesh&&(this.debugMesh.visible=e)}get showDebug(){return this.shouldRenderDebug}constructor(e,t){super(),this.viewController=e,this.gameWorld=t,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new c,this.beforeStep=new c,this.afterStep=new c,this.shouldRenderDebug=!1,this._raycaster=new v,this._reusableResult=new RayTestResult,this._raytestDiff=new B,this._raytestDirection=new B,this.controlledActors=new Set,this.ready=this.setup()}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.ready}renderDebug(){null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.gameWorld.scene.add(this.debugMesh));const e=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new u(e.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await X(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((e=>{e=Math.min(.1,e),this.beforeStep.next(e),this.updatePhysics(e),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((e=>{if(e.isFixed())return;const t=this.staticMeshes.get(e)??this.bodyActors.get(e)?.object;var i,s;null!=t&&(t.parent instanceof x&&(Y(t.position,e.translation()),(e.isDynamic()||e.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(e)?.id))&&(i=t.quaternion,s=e.rotation(),i.x=s.x,i.y=s.y,i.z=s.z,i.w=s.w),t.updateMatrix(),t.updateWorldMatrix(!1,!1)))})),this.afterStep.next(e)}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(e){this.world.timestep=e,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((e,t,i)=>{this.collisionEvents.next({handle1:e,handle2:t,started:i}),this.collisionEvents.next({handle1:t,handle2:e,started:i})}))}rayTestFromCamera(e,t,i){this._raycaster.setFromCamera(H,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(e).add(s);return this.rayTest(s,o,t,i)}rayTest(e,t,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,r=this._raytestDirection;if(o.subVectors(t,e),r.copy(o).normalize(),0===r.length())return console.warn("Ray test called with to and from being equal"),i;K(ie.origin,e),K(ie.dir,r);const n=o.length(),a=this.world.castRayAndGetNormal(ie,n,!1,void 0,void 0,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?e=>!e.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const t=ie.pointAt(a.timeOfImpact);i._internal=a,Y(i.hitNormal,a.normal),Y(i.hitPoint,t),i.distance=J.subVectors(i.hitPoint,e).length();const s=this.world.bodies.getAll().find((e=>function(e,t){for(let i=0,s=e.numColliders();i<s;i++){const s=e.collider(i);if(t(s))return s}}(e,(e=>e===a.collider))));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){const t=new h(r,e,n,s?.debugColor??255);this.gameWorld.scene.add(t),setTimeout((()=>this.gameWorld.scene.remove(t)),s?.debugLifetime??200)}return this._reusableResult}setGravity(e,t,i){this.world.gravity.x=e,this.world.gravity.y=t,this.world.gravity.z=i}getGravity(){return G.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(e){this.addRecursively(e);for(const e of this.staticBodies.values())Z(e,(e=>e.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)))}addRecursively(e){if(this.removeSceneObject(e),!function(e){if(null!=e.userData?.src){const t=e.userData?.src;return"actor"===t.type}return!1}(e))if(e instanceof S&&null!=e.collisionShape){const t=this.createStaticBody(e,[e.collisionShape],e.physics);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else if(e instanceof A&&!1!==e.userData?.src?.collisionDetection)if(e.children[0]&&e.children[0].instanceMatrix)this.createForInstancedMesh(e.children[0],e.collisionShapes);else{const t=this.createStaticBody(e,e.collisionShapes,e.physics);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else e instanceof F?this.addLandscapeGroup(e):(e instanceof p||e instanceof x)&&e.children.forEach((e=>this.addRecursively(e)))}createForInstancedMesh(e,t){const i=new m;for(let s=0;s<e.count;s++){const o=new f;o.matrix.identity(),i.fromArray(e.instanceMatrix.array,16*s),o.applyMatrix4(i);this.createStaticBody(o,t)}}getCharacterController(e){return this.world?.createCharacterController(e)}getActorComputedMovement(e,t,i,o=null){const r=this.actorBodies.get(e.id);this.controlledActors.add(e.id);const n=r.collider(0);t.computeColliderMovement(n,i,s.EXCLUDE_SENSORS,o,ee);const a=t.computedMovement();return Y($,a),$}setNextKinematicTranslation(e,t){const i=this.actorBodies.get(e.id),s=i.translation();s.x+=t.x,s.y+=t.y,s.z+=t.z,i?.setNextKinematicTranslation(s)}setAngularVelocity(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.setAngvel(q,!0)}setLinearVelocity(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.setLinvel(q,!0)}getLinearVelocity(e,t=new B){const i=this.actorBodies.get(e.id).linvel();return t.x=i.x,t.y=i.y,t.z=i.z,t}getAngularVelocity(e,t=new B){const i=this.actorBodies.get(e.id).angvel();return t.x=i.x,t.y=i.y,t.z=i.z,t}setLinearDamping(e,t){const i=this.actorBodies.get(e.id);i?.setLinearDamping(t)}setAngularDamping(e,t){const i=this.actorBodies.get(e.id);i?.setAngularDamping(t)}addLandscapeGroup(e){const t=e.userData.src,s=t.landscape.heightMaps;for(const r of e.sections){this.staticBodies.has(r)&&this.world.removeRigidBody(this.staticBodies.get(r));var o=r.getWorldPosition(new B);if(t.landscape.holes&&t.landscape.holes.some((e=>e.m===r.name&&0!==e.w[0]))){const e=r.geometry.clone(),s=r.scale,n=r.geometry.getAttribute("hole"),a=new Float32Array(e.getAttribute("position").array);for(let e=0;e<a.length;e+=3)a[e]*=s.x,a[e+1]*=s.y,a[e+2]*=s.z;const c=e.index;for(let e=0;e<c.count;e+=3){const t=n.getX(c.getX(e)),i=n.getX(c.getY(e)),s=n.getX(c.getZ(e));(t>.5||i>.5||s>.5)&&(c.setX(e,0),c.setY(e,0),c.setZ(e,0))}const l=i.ColliderDesc.trimesh(a,new Uint32Array(e.getIndex().array));if(!1!==t.collisionDetection){const e=this.world.createRigidBody(i.RigidBodyDesc.fixed()),t=new i.Vector3(0,0,0);K(t,o),e.setTranslation(t,!1),this.world.createCollider(l,e),this.staticBodies.set(r,e)}continue}const e=t.landscape.options.density+1,n=t.landscape.options.sectionSize,a=new Array(e);for(let t=0;t<e;t++)a[t]=new Array(e).fill(0);const c=s.find((e=>e.x===r.x&&e.y==r.y));if(null!=c)for(const t of c.points){if(null==a[t.i%e])continue;const i=e-1-Math.floor(t.i/e);i in a[t.i%e]?a[t.i%e][i]=t.y/n:console.warn("wrong index",{points:a,point:t,i:t.i%e,k:i,heightMap:c})}const l=t.landscape.options.density,d=a.flatMap((e=>e.reverse())),h=i.ColliderDesc.heightfield(l,l,new Float32Array(d),new i.Vector3(n,n,n));if(!1!==t.collisionDetection){const e=this.world.createRigidBody(i.RigidBodyDesc.fixed()),t=new i.Vector3(0,0,0);K(t,o),e.setTranslation(t,!1),this.world.createCollider(h,e),this.staticBodies.set(r,e)}}}addActor(e,t,s={}){if(0==t.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(e);const o=e.object;let r;switch(s.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:r=i.RigidBodyDesc.dynamic(),r.mass=s.mass??1;break;case PhysicsBodyType.kinematic:r=i.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:r=i.RigidBodyDesc.kinematicVelocityBased();break;default:r=s.isTrigger?i.RigidBodyDesc.kinematicVelocityBased():i.RigidBodyDesc.fixed()}const n=this.world.createRigidBody(r);n.enableCcd(1==s.continousCollisionDetection);for(const e of t)this.addShape(n,e,o);Z(n,(e=>{null!=s.isTrigger&&(e.setSensor(s.isTrigger),e.setActiveCollisionTypes(i.ActiveCollisionTypes.ALL),e.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)),null!=s.friction&&e.setFriction(s.friction),null!=s.density&&e.setDensity(s.density),null!=s.mass&&e.setMass(s.mass),null!=s.restitution&&e.setRestitution(s.restitution)})),N(n,o),!0===s.ignoreForNavMesh&&(n.userData={ignoreForNavMesh:!0}),this.actorBodies.set(e.id,n),this.bodyActors.set(n,e)}applyTorque(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.addTorque(q,!0)}applyTorqueImpulse(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.applyTorqueImpulse(q,!0)}resetForces(e){const t=this.actorBodies.get(e.id);t?.resetForces(!1)}resetTorques(e){const t=this.actorBodies.get(e.id);t?.resetTorques(!1)}applyForce(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.addForce(q,!0)}applyImpulse(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.applyImpulse(q,!0)}applyLocalForce(e,t,i){const s=this.actorBodies.get(e.id);K(q,t),null==i?s?.addForce(q,!0):(K(Q,i),s?.addForceAtPoint(q,Q,!0))}applyLocalImpulse(e,t,i){const s=this.actorBodies.get(e.id);K(q,t),null==i?s.applyImpulse(q,!0):(K(Q,i),s.applyImpulseAtPoint(q,Q,!0))}applyRadiusImpulse(e,t,s){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const r=U;Y(r,o.translation());const n=r.clone().sub(e);if(n.length()>t)return;const a=n.clone().normalize().multiplyScalar(s);q.x=a.x,q.y=a.y,q.z=a.z,o.applyImpulse(q,!0)}))}removeActor(e){if(null==e)return;this.controlledActors.delete(e.id);const t=this.actorBodies.get(e.id);null!=t&&(this.bodyActors.delete(t),this.world.removeRigidBody(t)),this.actorBodies.delete(e.id)}removeRemoved(e){const t=new Set;e.traverse((e=>{t.add(e.uuid)}));for(const[e,i]of this.staticBodies.entries())!t.has(e.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(e),this.world.removeRigidBody(i))}removeSceneObject(e){if(e instanceof F){for(const t of e.sections)this.removeSceneObject(t);return}let t=this.staticBodies.get(e);null!=t&&this.world.getRigidBody(t.handle)&&this.world.removeRigidBody(t),this.staticBodies.delete(e)}activateActorEvents(e){this.actorBodies.get(e.id)}_onCollisionWithActorEvent(e,t,i){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),n((({started:e})=>e===i)),a((({handle1:e,handle2:t,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(e)?.parent()),a2:this.bodyActors.get(this.world.getCollider(t)?.parent()),started:i}))),n((({a1:i,a2:s})=>null!=i&&null!=s&&i.id===e.id&&t(i,s))),a((({a2:e})=>e)))}onBeginContact(e){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),n((e=>e.started)),n((({handle1:t})=>{const i=this.bodyActors.get(this.world.getCollider(t)?.parent());return null!=i&&i.id===e.id})),a((e=>e.handle2)))}onEndContact(e){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),n((e=>!e.started)),n((({handle1:t})=>{const i=this.bodyActors.get(this.world.getCollider(t)?.parent());return null!=i&&i.id===e.id})),a((e=>e.handle2)))}onHasContactChanged(e){const t=new Set,i=new o(!1);return this.onBeginContact(e).subscribe((e=>{t.add(e),i.next(t.size>0)})),this.onEndContact(e).subscribe((e=>{t.delete(e),i.next(t.size>0)})),i.pipe(r())}onBeginOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>i instanceof t),!0)}onEndOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>i instanceof t),!1)}onBeginOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>t.id===i.id),!0)}onEndOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>t.id===i.id),!1)}onCollisionWithActor(e,t){return this.onBeginOverlapWithActor(e,t)}onCollisionWithActorType(e,t){return this.onBeginOverlapWithActorType(e,t)}updateActorTransform(e){const t=this.actorBodies.get(e.id);null!=t?N(t,e.object):console.warn("Actor has not been added to physics world",e)}setupWorld(){const e=new i.World({x:0,y:-9.81,z:0});this.world=e}getActorContacts(e,t){const s=this.actorBodies.get(e.id);if(s&&s.numColliders()>0){const o=s.collider(0);let r=o.shape,n=o.translation(),a=o.rotation(),c=t,l=.3;const d=this.world.castShape(n,a,c,r,.1,l,!0,null,null,null,this.actorBodies.get(e.id),(e=>e.shape.type!=i.ShapeType.HeightField));if(null!=d){const e=new B,t=new B,i=new B;return Y(e,d.witness2),Y(t,d.witness1),Y(i,d.normal1),i.negate(),[{ri:e,rj:t,ni:i}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){this.world?.bodies.forEach((e=>this.world.removeRigidBody(e))),this.world?.free(),this.fixedupdateSub?.unsubscribe()}createStaticBody(e,t,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed(),r=this.world.createRigidBody(o);for(const i of t){if(null==i){console.warn("Collision shape is missing for object",e);continue}const o=this.addShape(r,i,e);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/t.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return N(r,e),r.userData=e.uuid,r}addShape(e,t,i){const s=i.getWorldScale(te),o=this.createShape(t,s);null!=t.collisionGroup&&o.setCollisionGroups(t.collisionGroup),o.friction=.1;const r=t.offset.clone().multiply(s);var n,a;K(o.translation,r),n=o.rotation,a=(new w).setFromEuler(t.rotation),n.x=a.x,n.y=a.y,n.z=a.z,n.w=a.w;return this.world.createCollider(o,e)}createShape(e,t){if(e instanceof C)return i.ColliderDesc.cuboid(e.dimensions.x*t.x/2,e.dimensions.y*t.y/2,e.dimensions.z*t.z/2);if(e instanceof D){return i.ColliderDesc.capsule(e.length/2*t.y,e.radius*Math.max(t.z,t.x))}if(e instanceof W){const s=null!=e.geometry.getIndex()?e.geometry:I.mergeVertices(e.geometry),o=new Float32Array(s.getAttribute("position").array);for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(e instanceof R){let s;e.mesh instanceof d.Mesh?s=e.mesh.geometry:e.mesh instanceof d.BufferGeometry?s=e.mesh:console.log("Unknownd shape",{shapeInfo:e});const o=new Float32Array(s.getAttribute("position").array);if(e.mesh instanceof d.Mesh){const t=j(e.mesh);for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z}for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z;const r=o;return i.ColliderDesc.convexHull(r)}if(e instanceof E){const s=2*t.x-t.y-t.z;return Math.abs(s)>.01?this.createShape(new R(new d.SphereGeometry(e.radius).scale(t.x,t.y,t.z)),new B(1,1,1)):i.ColliderDesc.ball(e.radius*Math.max(t.x,t.y,t.z))}return e instanceof M?i.ColliderDesc.cylinder(e.height/2*t.y,e.radiusTop*Math.max(t.z,t.x)):e instanceof z?i.ColliderDesc.cone(e.height*t.y,e.radiusBottom/2*Math.max(t.z,t.x)):e instanceof T?i.ColliderDesc.cuboid(e.width/2*t.x,e.height/2*t.y,.001):(console.error("Unsupported shape",e),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};P=e([b(),t("design:paramtypes",[V,_])],P);export{P as PhysicsSystem};const k=new B,O=new d.Quaternion;function N(e,t){const s=t.getWorldPosition(k),o=t.getWorldQuaternion(O);e.setTranslation(new i.Vector3(s.x,s.y,s.z),!1),e.setRotation(new i.Quaternion(o.x,o.y,o.z,o.w),!1)}const G=new B,q=new i.Vector3(0,0,0),Q=new i.Vector3(0,0,0),U=new B,H=new d.Vector2,X=async()=>{let e=await import("@dimforge/rapier3d-compat");return await e.init(),e};function K(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function Y(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function Z(e,t){for(let i=0,s=e.numColliders();i<s;i++){t(e.collider(i))}}const J=new B,$=new B,ee=e=>!e.isSensor(),te=new B;const ie=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));/*
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import*as i from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as c,takeUntil as l}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as y,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as v,Scene as x,Vector3 as B}from"three";import{Service as b}from"typedi";import{AssetMeshInstance as A}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as C,CapsuleCollisionShape as D,ConeCollisionShape as z,ConvexPolyhedronCollisionShape as M,CylinderCollisionShape as R,PhysicalShapeMesh as S,PlaneCollisionShape as T,SphereCollisionShape as E,TrimeshCollisionShape as W}from"../../../index.js";import{LandscapeGroup as F}from"../../../scene/landscape/landscape.js";import{ViewController as V}from"../render.js";import{World as _}from"../world.js";import*as I from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as j}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as L}from"./abstract-physics-system.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new B,this.hitNormal=new B}}export var PhysicsBodyType;!function(e){e[e.dynamic=1]="dynamic",e[e.static=2]="static",e[e.kinematic=4]="kinematic",e[e.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));let P=class extends L{set showDebug(e){this.shouldRenderDebug=e,this.debugMesh&&(this.debugMesh.visible=e)}get showDebug(){return this.shouldRenderDebug}constructor(e,t){super(),this.viewController=e,this.gameWorld=t,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new c,this.beforeStep=new c,this.afterStep=new c,this.shouldRenderDebug=!1,this._raycaster=new v,this._reusableResult=new RayTestResult,this._raytestDiff=new B,this._raytestDirection=new B,this.controlledActors=new Set,this.ready=this.setup()}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.ready}renderDebug(){null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.gameWorld.scene.add(this.debugMesh));const e=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new u(e.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await X(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((e=>{e=Math.min(.1,e),this.beforeStep.next(e),this.updatePhysics(e),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((e=>{if(e.isFixed())return;const t=this.staticMeshes.get(e)??this.bodyActors.get(e)?.object;var i,s;null!=t&&(t.parent instanceof x&&(Y(t.position,e.translation()),(e.isDynamic()||e.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(e)?.id))&&(i=t.quaternion,s=e.rotation(),i.x=s.x,i.y=s.y,i.z=s.z,i.w=s.w),t.updateMatrix(),t.updateWorldMatrix(!1,!1)))})),this.afterStep.next(e)}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(e){this.world.timestep=e,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((e,t,i)=>{this.collisionEvents.next({handle1:e,handle2:t,started:i}),this.collisionEvents.next({handle1:t,handle2:e,started:i})}))}rayTestFromCamera(e,t,i){this._raycaster.setFromCamera(H,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(e).add(s);return this.rayTest(s,o,t,i)}rayTest(e,t,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(t,e),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),i;K(ie.origin,e),K(ie.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(ie,r,!1,void 0,void 0,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?e=>!e.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const t=ie.pointAt(a.timeOfImpact);i._internal=a,Y(i.hitNormal,a.normal),Y(i.hitPoint,t),i.distance=J.subVectors(i.hitPoint,e).length();const s=this.world.bodies.getAll().find((e=>function(e,t){for(let i=0,s=e.numColliders();i<s;i++){const s=e.collider(i);if(t(s))return s}}(e,(e=>e===a.collider))));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){const t=new h(n,e,r,s?.debugColor??255);this.gameWorld.scene.add(t),setTimeout((()=>this.gameWorld.scene.remove(t)),s?.debugLifetime??200)}return this._reusableResult}setGravity(e,t,i){this.world.gravity.x=e,this.world.gravity.y=t,this.world.gravity.z=i}getGravity(){return G.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(e){this.addRecursively(e);for(const e of this.staticBodies.values())Z(e,(e=>e.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)))}addRecursively(e){if(this.removeSceneObject(e),!function(e){if(null!=e.userData?.src){const t=e.userData?.src;return"actor"===t.type}return!1}(e))if(e instanceof S&&null!=e.collisionShape){const t=this.createStaticBody(e,[e.collisionShape],e.physics);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else if(e instanceof A&&!1!==e.userData?.src?.collisionDetection)if(e.children[0]&&e.children[0].instanceMatrix)this.createForInstancedMesh(e.children[0],e.collisionShapes);else{const t=this.createStaticBody(e,e.collisionShapes,e.physics);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else e instanceof F?this.addLandscapeGroup(e):(e instanceof p||e instanceof x)&&e.children.forEach((e=>this.addRecursively(e)))}createForInstancedMesh(e,t){const i=new m;for(let s=0;s<e.count;s++){const o=new f;o.matrix.identity(),i.fromArray(e.instanceMatrix.array,16*s),o.applyMatrix4(i);this.createStaticBody(o,t)}}getCharacterController(e){return this.world?.createCharacterController(e)}getActorComputedMovement(e,t,i,o=null){const n=this.actorBodies.get(e.id);this.controlledActors.add(e.id);const r=n.collider(0);t.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,o,ee);const a=t.computedMovement();return Y($,a),$}setNextKinematicTranslation(e,t){const i=this.actorBodies.get(e.id),s=i.translation();s.x+=t.x,s.y+=t.y,s.z+=t.z,i?.setNextKinematicTranslation(s)}setAngularVelocity(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.setAngvel(q,!0)}setLinearVelocity(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.setLinvel(q,!0)}getLinearVelocity(e,t=new B){const i=this.actorBodies.get(e.id).linvel();return t.x=i.x,t.y=i.y,t.z=i.z,t}getAngularVelocity(e,t=new B){const i=this.actorBodies.get(e.id).angvel();return t.x=i.x,t.y=i.y,t.z=i.z,t}setLinearDamping(e,t){const i=this.actorBodies.get(e.id);i?.setLinearDamping(t)}setAngularDamping(e,t){const i=this.actorBodies.get(e.id);i?.setAngularDamping(t)}addLandscapeGroup(e){const t=e.userData.src,s=t.landscape.heightMaps;for(const n of e.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new B);if(t.landscape.holes&&t.landscape.holes.some((e=>e.m===n.name&&0!==e.w[0]))){const e=n.geometry.clone(),s=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(e.getAttribute("position").array);for(let e=0;e<a.length;e+=3)a[e]*=s.x,a[e+1]*=s.y,a[e+2]*=s.z;const c=e.index;for(let e=0;e<c.count;e+=3){const t=r.getX(c.getX(e)),i=r.getX(c.getY(e)),s=r.getX(c.getZ(e));(t>.5||i>.5||s>.5)&&(c.setX(e,0),c.setY(e,0),c.setZ(e,0))}const l=i.ColliderDesc.trimesh(a,new Uint32Array(e.getIndex().array));if(!1!==t.collisionDetection){const e=this.world.createRigidBody(i.RigidBodyDesc.fixed()),t=new i.Vector3(0,0,0);K(t,o),e.setTranslation(t,!1),this.world.createCollider(l,e),this.staticBodies.set(n,e)}continue}const e=t.landscape.options.density+1,r=t.landscape.options.sectionSize,a=new Array(e);for(let t=0;t<e;t++)a[t]=new Array(e).fill(0);const c=s.find((e=>e.x===n.x&&e.y==n.y));if(null!=c)for(const t of c.points){if(null==a[t.i%e])continue;const i=e-1-Math.floor(t.i/e);i in a[t.i%e]?a[t.i%e][i]=t.y/r:console.warn("wrong index",{points:a,point:t,i:t.i%e,k:i,heightMap:c})}const l=t.landscape.options.density,d=a.flatMap((e=>e.reverse())),h=i.ColliderDesc.heightfield(l,l,new Float32Array(d),new i.Vector3(r,r,r));if(!1!==t.collisionDetection){const e=this.world.createRigidBody(i.RigidBodyDesc.fixed()),t=new i.Vector3(0,0,0);K(t,o),e.setTranslation(t,!1),this.world.createCollider(h,e),this.staticBodies.set(n,e)}}}addActor(e,t,s={}){if(0==t.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(e);const o=e.object;let n;switch(s.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=i.RigidBodyDesc.dynamic(),n.mass=s.mass??1;break;case PhysicsBodyType.kinematic:n=i.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=i.RigidBodyDesc.kinematicVelocityBased();break;default:n=s.isTrigger?i.RigidBodyDesc.kinematicVelocityBased():i.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==s.continousCollisionDetection);for(const e of t)this.addShape(r,e,o);Z(r,(e=>{null!=s.isTrigger&&(e.setSensor(s.isTrigger),e.setActiveCollisionTypes(i.ActiveCollisionTypes.ALL),e.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)),null!=s.friction&&e.setFriction(s.friction),null!=s.density&&e.setDensity(s.density),null!=s.mass&&e.setMass(s.mass),null!=s.restitution&&e.setRestitution(s.restitution)})),N(r,o),!0===s.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(e.id,r),this.bodyActors.set(r,e)}applyTorque(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.addTorque(q,!0)}applyTorqueImpulse(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.applyTorqueImpulse(q,!0)}resetForces(e){const t=this.actorBodies.get(e.id);t?.resetForces(!1)}resetTorques(e){const t=this.actorBodies.get(e.id);t?.resetTorques(!1)}applyForce(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.addForce(q,!0)}applyImpulse(e,t){const i=this.actorBodies.get(e.id);q.x=t.x,q.y=t.y,q.z=t.z,i?.applyImpulse(q,!0)}applyLocalForce(e,t,i){const s=this.actorBodies.get(e.id);K(q,t),null==i?s?.addForce(q,!0):(K(Q,i),s?.addForceAtPoint(q,Q,!0))}applyLocalImpulse(e,t,i){const s=this.actorBodies.get(e.id);K(q,t),null==i?s.applyImpulse(q,!0):(K(Q,i),s.applyImpulseAtPoint(q,Q,!0))}applyRadiusImpulse(e,t,s){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const n=U;Y(n,o.translation());const r=n.clone().sub(e);if(r.length()>t)return;const a=r.clone().normalize().multiplyScalar(s);q.x=a.x,q.y=a.y,q.z=a.z,o.applyImpulse(q,!0)}))}removeActor(e){if(null==e)return;this.controlledActors.delete(e.id);const t=this.actorBodies.get(e.id);null!=t&&(this.bodyActors.delete(t),this.world.removeRigidBody(t)),this.actorBodies.delete(e.id)}removeRemoved(e){const t=new Set;e.traverse((e=>{t.add(e.uuid)}));for(const[e,i]of this.staticBodies.entries())!t.has(e.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(e),this.world.removeRigidBody(i))}removeSceneObject(e){if(e instanceof F){for(const t of e.sections)this.removeSceneObject(t);return}let t=this.staticBodies.get(e);null!=t&&this.world.getRigidBody(t.handle)&&this.world.removeRigidBody(t),this.staticBodies.delete(e)}activateActorEvents(e){this.actorBodies.get(e.id)}_onCollisionWithActorEvent(e,t,i){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),r((({started:e})=>e===i)),a((({handle1:e,handle2:t,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(e)?.parent()),a2:this.bodyActors.get(this.world.getCollider(t)?.parent()),started:i}))),r((({a1:i,a2:s})=>null!=i&&null!=s&&i.id===e.id&&t(i,s))),a((({a2:e})=>e)))}onBeginContact(e){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),r((e=>e.started)),r((({handle1:t})=>{const i=this.bodyActors.get(this.world.getCollider(t)?.parent());return null!=i&&i.id===e.id})),a((e=>e.handle2)))}onEndContact(e){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),r((e=>!e.started)),r((({handle1:t})=>{const i=this.bodyActors.get(this.world.getCollider(t)?.parent());return null!=i&&i.id===e.id})),a((e=>e.handle2)))}onHasContactChanged(e){const t=new Set,i=new o(!1);return this.onBeginContact(e).subscribe((e=>{t.add(e),i.next(t.size>0)})),this.onEndContact(e).subscribe((e=>{t.delete(e),i.next(t.size>0)})),i.pipe(n())}onBeginOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>i instanceof t),!0)}onEndOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>i instanceof t),!1)}onBeginOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>t.id===i.id),!0)}onEndOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>t.id===i.id),!1)}onCollisionWithActor(e,t){return this.onBeginOverlapWithActor(e,t)}onCollisionWithActorType(e,t){return this.onBeginOverlapWithActorType(e,t)}updateActorTransform(e){const t=this.actorBodies.get(e.id);null!=t?N(t,e.object):console.warn("Actor has not been added to physics world",e)}setupWorld(){const e=new i.World({x:0,y:-9.81,z:0});this.world=e}getActorContacts(e,t){const s=this.actorBodies.get(e.id);if(s&&s.numColliders()>0){const o=s.collider(0);let n=o.shape,r=o.translation(),a=o.rotation(),c=t,l=.3;const d=this.world.castShape(r,a,c,n,.1,l,!0,null,null,null,this.actorBodies.get(e.id),(e=>e.shape.type!=i.ShapeType.HeightField));if(null!=d){const e=new B,t=new B,i=new B;return Y(e,d.witness2),Y(t,d.witness1),Y(i,d.normal1),i.negate(),[{ri:e,rj:t,ni:i}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){this.world?.bodies.forEach((e=>this.world.removeRigidBody(e))),this.world?.free(),this.fixedupdateSub?.unsubscribe()}createStaticBody(e,t,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const i of t){if(null==i){console.warn("Collision shape is missing for object",e);continue}const o=this.addShape(n,i,e);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/t.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return N(n,e),n.userData=e.uuid,n}addShape(e,t,i){const s=i.getWorldScale(te),o=this.createShape(t,s);null!=t.collisionGroup&&o.setCollisionGroups(t.collisionGroup),o.friction=.1;const n=t.offset.clone().multiply(s);K(o.translation,n);const r=(new w).setFromEuler(t.rotation);var a,c;t instanceof M&&t.mesh instanceof d.Mesh&&r.multiply(t.mesh.getWorldQuaternion(O)),a=o.rotation,c=r,a.x=c.x,a.y=c.y,a.z=c.z,a.w=c.w;return this.world.createCollider(o,e)}createShape(e,t){if(e instanceof C)return i.ColliderDesc.cuboid(e.dimensions.x*t.x/2,e.dimensions.y*t.y/2,e.dimensions.z*t.z/2);if(e instanceof D){return i.ColliderDesc.capsule(e.length/2*t.y,e.radius*Math.max(t.z,t.x))}if(e instanceof W){const s=null!=e.geometry.getIndex()?e.geometry:I.mergeVertices(e.geometry),o=new Float32Array(s.getAttribute("position").array);for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(e instanceof M){let s;e.mesh instanceof d.Mesh?s=e.mesh.geometry:e.mesh instanceof d.BufferGeometry?s=e.mesh:console.log("Unknownd shape",{shapeInfo:e});const o=new Float32Array(s.getAttribute("position").array);if(e.mesh instanceof d.Mesh){const t=j(e.mesh);for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z}for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z;const n=o;return i.ColliderDesc.convexHull(n)}if(e instanceof E){const s=2*t.x-t.y-t.z;return Math.abs(s)>.01?this.createShape(new M(new d.SphereGeometry(e.radius).scale(t.x,t.y,t.z)),new B(1,1,1)):i.ColliderDesc.ball(e.radius*Math.max(t.x,t.y,t.z))}return e instanceof R?i.ColliderDesc.cylinder(e.height/2*t.y,e.radiusTop*Math.max(t.z,t.x)):e instanceof z?i.ColliderDesc.cone(e.height*t.y,e.radiusBottom/2*Math.max(t.z,t.x)):e instanceof T?i.ColliderDesc.cuboid(e.width/2*t.x,e.height/2*t.y,.001):(console.error("Unsupported shape",e),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};P=e([b(),t("design:paramtypes",[V,_])],P);export{P as PhysicsSystem};const k=new B,O=new d.Quaternion;function N(e,t){const s=t.getWorldPosition(k),o=t.getWorldQuaternion(O);e.setTranslation(new i.Vector3(s.x,s.y,s.z),!1),e.setRotation(new i.Quaternion(o.x,o.y,o.z,o.w),!1)}const G=new B,q=new i.Vector3(0,0,0),Q=new i.Vector3(0,0,0),U=new B,H=new d.Vector2,X=async()=>{let e=await import("@dimforge/rapier3d-compat");return await e.init(),e};function K(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function Y(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function Z(e,t){for(let i=0,s=e.numColliders();i<s;i++){t(e.collider(i))}}const J=new B,$=new B,ee=e=>!e.isSensor(),te=new B;const ie=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as a,Mesh as i,Object3D as r,TextureLoader as n}from"three";import{GLTFLoader as o,MTLLoader as h,OBJLoader as c}from"three-stdlib";import{FBXLoader as l}from"three-stdlib";import{cloneMesh as d}from"../utils/mesh.js";import{pathJoin as m}from"../utils/files.js";import{Subject as p,firstValueFrom as u}from"rxjs";import{importCollisionShapes as g,isCollisionMesh as f}from"./collision/collision-shape-import.js";import*as w from"three";import{iterateMaterials as y}from"../utils/materials.js";import{BufferGeometryUtils as x,EXRLoader as L,KTX2Loader as M,TGALoader as b,UltraHDRLoader as A}from"three/examples/jsm/Addons.js";const S=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new a,this.glbLoader=new o(this.loadingManager),this.fbxLoader=new l(this.loadingManager),this.objLoader=new c(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new b(this.loadingManager),this.exrLoader=new L(this.loadingManager),this.hdrLoader=new A(this.loadingManager),this.ktx2Loader=new M(this.loadingManager),this._textureLoader=new w.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this.makeReady=new p,this.ready=u(this.makeReady),this.asyncMeshResults=new Map,this.collisionShapeCache=new Map,this.optimizedMeshes=new Set}initKtx2(e){this.initialisedKtx2=!0,this.ktx2Loader.setTranscoderPath("/assets/basis/"),this.ktx2Loader.detectSupport(e)}setDataDir(e){this.basePath=m(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){return m(this.basePath,e)+`?windowId=${getElectronArg("windowId")}`}async getTexture(e){return null==e||null==e.fileKey?null:(await this.ready,this.textureCache.has(e.id)||await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then((t=>(t.wrapS=j(e.texture?.wrapS),t.wrapT=j(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0,this.textureCache.set(e.id,t),t))),this.textureCache.get(e.id))}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:this.textureLoader}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!S.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new s,animations:[]};const a=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(a))try{this.asyncMeshResults.has(a)||this.asyncMeshResults.set(a,this.loadMesh(e).finally((()=>this.asyncMeshResults.delete(a)))),this.cache.set(a,await this.asyncMeshResults.get(a))}catch(e){return this.onError(e),{scene:new s,animations:[]}}const r=this.cache.get(a).scene,n=this.computeCollisionShapes(e,r);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(r);const o=d(r),h=this.cache.get(a).animations;o.traverse((e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())}));const c=new AssetMeshInstance;c.add(o),c.collisionShapes=n,c.animations=h;const l=e.receiveShadow??!0,m=e.castShadow??!1;return o.traverse((e=>{e.castShadow=m,e.receiveShadow=l})),{scene:c,animations:h}}async getAudio(e){return await this.ready,this.audioLoader.loadAsync(this.getUri(e.fileKey))}computeCollisionShapes(e,t){const s=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(s)||this.collisionShapeCache.set(s,g(t,e)),this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then((e=>(e.scene=function(e,t){let s=!1;if(t.traverseVisible((e=>{v.test(e.name)&&(s=!0)})),!s)return t;const a=new w.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(v);if(null!=t){const s=parseInt(t[1]);0===s?a.addLevel(e,0):console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`)}else i.push(...e.children)}return a}(0,e.scene),e)))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid);let s=!0,a=0,r=0;if(e.traverse((e=>{if(e instanceof i&&e.geometry instanceof t&&!f(e)){a++;const t=Object.keys(e.geometry.attributes).length;t!==r&&0!==r&&(s=!1),r=t}else(e instanceof w.SkinnedMesh||e instanceof w.Bone)&&(s=!1)})),a>1&&s){const s=[],a=[],r=[];e.updateWorldMatrix(!0,!0),e.traverse((e=>{e instanceof i&&e.geometry instanceof t&&!f(e)&&!Array.isArray(e.material)&&(e.updateWorldMatrix(!0,!0),e.geometry.
|
1
|
+
import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as a,Mesh as i,Object3D as r,TextureLoader as n}from"three";import{GLTFLoader as o,MTLLoader as h,OBJLoader as c}from"three-stdlib";import{FBXLoader as l}from"three-stdlib";import{cloneMesh as d}from"../utils/mesh.js";import{pathJoin as m}from"../utils/files.js";import{Subject as p,firstValueFrom as u}from"rxjs";import{importCollisionShapes as g,isCollisionMesh as f}from"./collision/collision-shape-import.js";import*as w from"three";import{iterateMaterials as y}from"../utils/materials.js";import{BufferGeometryUtils as x,EXRLoader as L,KTX2Loader as M,TGALoader as b,UltraHDRLoader as A}from"three/examples/jsm/Addons.js";const S=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new a,this.glbLoader=new o(this.loadingManager),this.fbxLoader=new l(this.loadingManager),this.objLoader=new c(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new b(this.loadingManager),this.exrLoader=new L(this.loadingManager),this.hdrLoader=new A(this.loadingManager),this.ktx2Loader=new M(this.loadingManager),this._textureLoader=new w.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this.makeReady=new p,this.ready=u(this.makeReady),this.asyncMeshResults=new Map,this.collisionShapeCache=new Map,this.optimizedMeshes=new Set}initKtx2(e){this.initialisedKtx2=!0,this.ktx2Loader.setTranscoderPath("/assets/basis/"),this.ktx2Loader.detectSupport(e)}setDataDir(e){this.basePath=m(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){return m(this.basePath,e)+`?windowId=${getElectronArg("windowId")}`}async getTexture(e){return null==e||null==e.fileKey?null:(await this.ready,this.textureCache.has(e.id)||await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then((t=>(t.wrapS=j(e.texture?.wrapS),t.wrapT=j(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0,this.textureCache.set(e.id,t),t))),this.textureCache.get(e.id))}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:this.textureLoader}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!S.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new s,animations:[]};const a=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(a))try{this.asyncMeshResults.has(a)||this.asyncMeshResults.set(a,this.loadMesh(e).finally((()=>this.asyncMeshResults.delete(a)))),this.cache.set(a,await this.asyncMeshResults.get(a))}catch(e){return this.onError(e),{scene:new s,animations:[]}}const r=this.cache.get(a).scene,n=this.computeCollisionShapes(e,r);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(r);const o=d(r),h=this.cache.get(a).animations;o.traverse((e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())}));const c=new AssetMeshInstance;c.add(o),c.collisionShapes=n,c.animations=h;const l=e.receiveShadow??!0,m=e.castShadow??!1;return o.traverse((e=>{e.castShadow=m,e.receiveShadow=l})),{scene:c,animations:h}}async getAudio(e){return await this.ready,this.audioLoader.loadAsync(this.getUri(e.fileKey))}computeCollisionShapes(e,t){const s=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(s)||this.collisionShapeCache.set(s,g(t,e)),this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then((e=>(e.scene=function(e,t){let s=!1;if(t.traverseVisible((e=>{v.test(e.name)&&(s=!0)})),!s)return t;const a=new w.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(v);if(null!=t){const s=parseInt(t[1]);0===s?a.addLevel(e,0):console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`)}else i.push(...e.children)}return a}(0,e.scene),e)))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid);let s=!0,a=0,r=0;if(e.traverse((e=>{if(e instanceof i&&e.geometry instanceof t&&!f(e)){a++;const t=Object.keys(e.geometry.attributes).length;t!==r&&0!==r&&(s=!1),r=t}else(e instanceof w.SkinnedMesh||e instanceof w.Bone)&&(s=!1)})),a>1&&s){const s=[],a=[],r=[];e.updateWorldMatrix(!0,!0),e.traverse((e=>{e instanceof i&&e.geometry instanceof t&&!f(e)&&!Array.isArray(e.material)&&(e.updateWorldMatrix(!0,!0),s.push(e.geometry.clone().applyMatrix4(e.matrixWorld)),a.push(e.material),r.push(e))}));for(const e of r)e.removeFromParent();const n=x.mergeGeometries(s,!0),o=[];let h=0;e:for(const e of a){for(const t of o)if(t.m.id===e.id){t.indices.push(h),h++;continue e}o.push({m:e,indices:[h]}),h++}let c=0;for(const e of o){for(const t of e.indices)n.groups[t].materialIndex=c;c++}e.add(new i(n,o.map((e=>e.m))))}e.traverse((e=>{if(e instanceof i&&e.geometry instanceof t){const t=e.geometry;Array.isArray(e.material)&&t.groups.length>1&&t.groups.length>e.material.length&&x.mergeGroups(t)}}))}async loadByAsset(e){const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then((e=>({scene:e.scene,animations:e.animations})));case"fbx":return this.fbxLoader.loadAsync(t).then((e=>({scene:e,animations:e.animations})));case"obj":if(null!=e.materialLib){const t=new h;t.materialOptions={normalizeRGB:!1};const s=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(s)}return this.objLoader.loadAsync(t).then((e=>(C(e),e))).then((e=>({scene:e,animations:e.animations})))}}}function C(e){if(e instanceof i)for(const t of y(e.material))t instanceof w.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(C)}export class AssetMeshInstance extends r{}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find((e=>e.startsWith(t)));return s?.substring(t.length)}function j(e){switch(e){case"clamp":return w.ClampToEdgeWrapping;case"repeat":return w.RepeatWrapping;case"mirror":return w.MirroredRepeatWrapping}return w.RepeatWrapping}const v=/_LOD(\d+)$/;/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"collision-shape-import.d.ts","sourceRoot":"","sources":["../../../src/scene/collision/collision-shape-import.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAA+B,MAAM,OAAO,CAAC;AACjF,OAAO,EAAqB,cAAc,EAA+E,MAAM,sBAAsB,CAAC;AAEtJ,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAI7C,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,GAAG,cAAc,EAAE,
|
1
|
+
{"version":3,"file":"collision-shape-import.d.ts","sourceRoot":"","sources":["../../../src/scene/collision/collision-shape-import.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAA+B,MAAM,OAAO,CAAC;AACjF,OAAO,EAAqB,cAAc,EAA+E,MAAM,sBAAsB,CAAC;AAEtJ,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAI7C,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,GAAG,cAAc,EAAE,CAmDrF;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,QAAQ,WAK/C"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{Box3 as e,
|
1
|
+
import{Box3 as e,Mesh as t,Quaternion as n,Vector3 as s}from"three";import{BoxCollisionShape as i,ConvexPolyhedronCollisionShape as o,SphereCollisionShape as r,TrimeshCollisionShape as a}from"./collision-shape.js";new n;export function importCollisionShapes(n,h){let l=h.mesh?.collisions?.shapeType;if(null==l){let e=!1;n.traverse((n=>{(n instanceof t||n.isMesh)&&isCollisionMesh(n)&&(e=!0)})),l=e?"imported":"convex"}const c=[];return n.traverse((n=>{if(n instanceof t||n.isMesh){let t;"imported"===l?t=function(t){if(t.name.startsWith(m.convex))return new o(t);if(t.name.startsWith(m.box)){const n=t.clone();n.quaternion.set(0,0,0,1),n.updateMatrixWorld();const o=(new e).setFromObject(n);return isFinite(o.min.lengthSq())?new i(new s(o.max.x-o.min.x,o.max.y-o.min.y,o.max.z-o.min.z)):null}if(t.name.startsWith(m.sphere)){t.geometry.computeBoundingSphere();const e=t.geometry.boundingSphere.radius*Math.max(t.scale.x,t.scale.y,t.scale.z);return new r(e)}if(t.name.startsWith(m.trimesh))return new a(t.geometry)}(n):"convex"===l?t=new o(n):"mesh"===l&&(t=new a(n.geometry)),null!=t&&(t.offset=n.getWorldPosition(new s),c.push(t),isCollisionMesh(n)&&(n.visible=!1))}})),c}export function isCollisionMesh(e){return e.name.startsWith(m.convex)||e.name.startsWith(m.box)||e.name.startsWith(m.sphere)||e.name.startsWith(m.trimesh)}var m;!function(e){e.convex="UCX_",e.box="UBX_",e.sphere="USP_",e.trimesh="UTM_"}(m||(m={}));new e;/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -175,10 +175,12 @@ export interface AttachedComponent {
|
|
175
175
|
value: any;
|
176
176
|
}[];
|
177
177
|
}
|
178
|
+
export type ChangeCallback = (o: SceneObject, remote: boolean) => void;
|
178
179
|
export interface SceneDataProvider {
|
179
180
|
getObjects(): SceneObject[];
|
180
|
-
|
181
|
-
|
181
|
+
onCreate(callback: ChangeCallback): any;
|
182
|
+
onUpdate(callback: ChangeCallback): any;
|
183
|
+
onRemove(callback: ChangeCallback): any;
|
182
184
|
}
|
183
185
|
export declare const shapeDefaultColor = "#aaaaaa";
|
184
186
|
export declare class SceneMaterializerLoader {
|
@@ -227,6 +229,13 @@ export declare class SceneMaterializer {
|
|
227
229
|
constructor(scene: Scene, dataProvider: SceneDataProvider, assetsService: AssetsProvider, assetManagerService: AssetResourceLoader, renderingView: RenderingView, shaders: ShaderImpl[], actorTypes: ActorImpl[], actorProvider: ActorProvider);
|
228
230
|
private refreshMaterial;
|
229
231
|
get actorInstances(): BaseActor[];
|
232
|
+
/**
|
233
|
+
* Initializing textures uploads all textures in the project to the GPU.
|
234
|
+
* This avoid lag in the game. However, it adds additional loading time when
|
235
|
+
* starting and it risks running out of GPU memory. Ideally, textures are streamed
|
236
|
+
* when needed to support larger worlds.
|
237
|
+
*/
|
238
|
+
private initTextures;
|
230
239
|
private prefetchAssets;
|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 -1,4 +1,4 @@
|
|
1
|
-
import{ConvexPolyhedronCollisionShape as e}from"@hology/core";import{Subject as t}from"rxjs";import*as a from"three";import{BoxGeometry as s,Color as r,Euler as i,Fog as n,FogExp2 as o,Group as l,Material as c,Matrix4 as h,Mesh as d,MeshLambertMaterial as m,MeshPhongMaterial as p,MeshStandardMaterial as u,Object3D as f,PointLight as y,Quaternion as g,SphereGeometry as w,Texture as v,Vector2 as S,Vector3 as A,Vector4 as b}from"three";import M,{SpriteRenderer as x}from"@hology/nebula";import{bool as j,BooleanNode as P,float as I,FloatNode as E,NodeShaderMaterial as V,rgb as D,RgbNode as N,Texture2dLookupNode as k,textureSampler2d as C,vec2 as F,Vec2Node as _,vec3 as O,Vec3Node as z,vec4 as B}from"three-shader-graph";import{VfxActor as T}from"../effects/vfx/vfx-actor.js";import{VisualEffect as W}from"../effects/vfx/vfx-param.js";import{BaseActor as $}from"../gameplay/actors/actor.js";import R from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as U,withInjectionContext as G}from"../gameplay/index.js";import{Sampler2DNode as L}from"../shader-nodes/index.js";import{LambertShader as J}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as H}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as q}from"../shader/builtin/landscape-shader.js";import{StandardShader as X}from"../shader/builtin/standard-shader.js";import{UnlitShader as Y}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Z}from"../shader/parameter.js";import{ArrayMap as Q,groupBy as K}from"../utils/collections.js";import{iterateMaterials as ee}from"../utils/materials.js";import{filterChildrenShallow as te,filterSceneShallow as ae,findFirstVisibleObject as se}from"../utils/three/traverse.js";import{AssetMeshInstance as re}from"./asset-resource-loader.js";import{isCollisionMesh as ie}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ne,PhysicalShapeMesh as oe}from"./collision/collision-shape.js";import{LandscapeManager as le}from"./landscape/landscape-manager.js";import{initLandscape as ce}from"./landscape/landscape.js";import{SectionGrid as he,smoothNormalsCrossMeshes as de}from"./landscape/utils.js";import{createGrassFoliageMaterial as me}from"./materials/grass-foliage.js";import{createGrassMaterial as pe}from"./materials/grass.js";import{getMaterialAttribute as ue}from"./materials/utils/material-painting.js";import{createWaterMaterial as fe}from"./materials/water.js";import{SerializedParamType as ye}from"./model.js";import{ShapeLibrary as ge,ShapeLibraryKeys as we}from"./objects/shapes.js";import{ambientLightName as ve,createSky as Se,defaultSkyMaterial as Ae}from"./sky.js";import{Curve2 as be}from"../utils/curve.js";const Me={};export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,a){this.dataProvider=e,this.assetsService=t,this.assetManagerService=a}get(e,t){return new SceneMaterializer(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}export class SceneMaterializer{constructor(e,s,r,i,n,o,l,c){this.scene=e,this.dataProvider=s,this.assetsService=r,this.assetManagerService=i,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.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,s.onUpdate((e=>this.update(e))),s.onRemove((e=>this.remove(e))),this.createAssetSubscription=r.onCreate.subscribe((e=>{this.assets.set(e.id,e)})),this.updateSubscription=r.onUpdate.subscribe((async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse((e=>{if(e instanceof a.Mesh)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)})):"mesh"==t.type?(this.findByAssetId(t.id).forEach((e=>{_e(e.userData.src.materialAssignments,t.materialAssignments).forEach((t=>{this.applyMaterial(e,t)}))})),this.landscapeManagers.forEach((e=>{e.source.grass.layers.some((e=>e.meshes.some((e=>e.assetId===t.id))))&&e.queueRefreshScatter(this.renderingView?.camera.position??new A,!0)}))):"prefab"===t.type&&this.findByAssetId(t.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}))}))}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===ye.Material&&s.value===a.id){t=!0;break}if(s.type===ye.Array&&"element"in s&&s.element===ye.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);i.userData=t.userData,null!=s?ze(e.material[s],i)||(e.material[s]=i):ze(e.material,i)||(e.material=i)}get actorInstances(){return Array.from(this.materializedActors.values())}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter((e=>null!=e.assetId&&"asset_mesh"==e.type)).filter((e=>e.assetId))));await Promise.all(e.map((e=>this.assetsService.getAsset(e.assetId).then((e=>{if(null!=e)return this.assetManagerService.getMesh(e)})))))}async init(){await this.preInit(),je.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map((e=>this.materialize(e)))),await this.initActorsPostInit()}initActorsPostInit(e=this.actorInstances){const t=e.map((async e=>{const t=e.object.userData.src;if("vfx"===t.type)return Promise.resolve();const a=await this.assetsService.getAsset(t.assetId),s={...a?.actor?.params??{},...t.actor?.params??{}};for(const a of t.actor.innerParams??[])await this.applyActorComponentParams(e,a.path.slice(),a.params);const r=await Ve(s,e.constructor,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,r);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${t.name}", id=${t.id})`,e)}}));return Promise.all(t)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a){const s=t.length,r=t.shift();if(0==s){const t=await Ve(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[r]&&await this.applyActorComponentParams(e[r],t,a)}canObjectBeInstanced(e){return e.physics?.type!==U.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){if(!this._canBeInstancedCache.has(e.assetId)){const t=await this.createFromAsset(e);if(null==t)return!1;const a=[];t.traverse((e=>{!ie(e)&&e.isMesh&&a.push(e)}));const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof d&&null!=a[0].geometry.morphAttributes&&Object.keys(a[0].geometry.morphAttributes).length>0,i=!0;this._canBeInstancedCache.set(e.assetId,s&&i&&!r)}return this._canBeInstancedCache.get(e.assetId)}async preInit(){this.renderingView?.onLoop((()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)})),this.assetsService.getAssets().then((e=>{for(const t of e)this.assets.set(t.id,t)}))}async initWithInstancing(){await this.preInit(),await this.prefetchAssets();const t=[],s=new Q,n=new Q;for(const e of this.dataProvider.getObjects())await Fe(e,(async(e,a,i)=>{const o="asset_mesh"==e.type&&this.canObjectBeInstanced(e)&&await this.canAssetBeInstanced(e),l="shape_mesh"===e.type&&"landscape"!==e.shape&&e.physics?.type!==U.dynamic;if(o||l){if(a&&a.children?.length>0){const t=a.children.findIndex((t=>t.id===e.id));t>=0&&a.children.splice(t,1)}if(l){let t=e.shape+JSON.stringify(e.shapeParams??{})+e.castShadow+e.receiveShadow;const a=e.materialAssignments?.at(0)?.materialId,s=null!=a?this.assets.get(a):null;let o=null;if(null!=s&&"shader"!==s.material.type){if(t+=s.material.type+s.material.shader,null!=s.material.shaderParams){if(t+=Object.entries(s.material.shaderParams).filter((([e,t])=>"color"!=e)).map((e=>JSON.stringify(e))).join(),null!=s.material.shaderParams.color){const e=s.material.shaderParams.color;e.type===ye.Color&&null!=e.value&&(o=new r(e.value))}}}else t+=a;n.push(t,{object:{...e,parentTransform:i},color:o})}else{const t=e.assetId+JSON.stringify(e.materialAssignments??[]);s.push(t,{...e,parentTransform:i})}}else null==a&&t.push({...e,parentTransform:i})}));for(const t of s.values()){if(0==t.length)continue;const a=await this.createFromAsset(t[0]);if(null==a)continue;const s=await this.createInstancedMesh(t,a),r=new re;r.add(s),r.userData.src=t[0],a instanceof re&&(r.collisionShapes=a.collisionShapes),r.collisionShapes.forEach((t=>{t instanceof e&&t.mesh instanceof d&&(t.mesh=t.mesh.geometry)})),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of n.values()){if(0==e.length)continue;const t=e[0].object,s=await this.createFromShape(t),n=se(s,(e=>!ie(e)&&null!=e.geometry)),o=n.material.clone();null!=e[0].color&&null!=o.color&&(o.color=new r(16777215));const l=n.geometry,c=new a.InstancedMesh(l,o,e.length);for(let t=0;t<e.length;t++){const r=e[t],o=(new a.Matrix4).compose((new A).fromArray(r.object.position),(new g).setFromEuler((new i).fromArray(r.object.rotation)),(new A).fromArray(r.object.scale)),l=(new h).copy(r.object.parentTransform).multiply(o);c.setMatrixAt(t,l),null!=r.color&&c.setColorAt(t,r.color),c.castShadow=s.castShadow??!0,c.receiveShadow=n.receiveShadow??!0;const d=new re;d.add(c),d.userData.src=e[0],s instanceof oe&&(d.collisionShapes=[s.collisionShape]),d.castShadow=!1,d.receiveShadow=!1,this.scene.add(d)}}await Promise.all(t.map((e=>this.materialize(e)))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const s=se(t,(e=>!ie(e)&&null!=e.geometry)),r=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,_e(e[0].materialAssignments,r.materialAssignments)),s.updateMatrix();const n=s.geometry.clone(),o=new a.InstancedMesh(n,s.material,e.length);for(let t=0;t<e.length;t++){const r=(new a.Matrix4).compose((new A).fromArray(e[t].position),(new g).setFromEuler((new i).fromArray(e[t].rotation)),(new A).fromArray(e[t].scale)),n=(new h).copy(e[t].parentTransform).multiply(r).multiply(s.matrixWorld);o.setMatrixAt(t,n)}return o.castShadow=e[0].castShadow??r.castShadow??!0,o.receiveShadow=e[0].receiveShadow??r.receiveShadow??!0,s.material instanceof c&&o.castShadow&&o.receiveShadow&&(o.material.side=a.FrontSide),o}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}const t=this.sceneObjectMap.get(e.id);t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter((t=>t.object.userData.src?.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 ae(this.scene,(t=>t.userData.src?.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))))}async applyMaterial(e,t){await applyMaterial(e,t,(e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}}),this._originalMaterials)}unapplyMaterials(e){e.traverse((async e=>{if(e instanceof d)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material}))}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(R));ae(this.scene,(e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type))).forEach((async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)}))}updateShaders(e){this.shaders=e;for(const[e,t]of je.entries())t.userData.customShaderName&&je.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),ae(this.scene,(e=>!0)).forEach((e=>{e.traverse((async e=>{if(e instanceof d)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}}))}))}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(s=!0)})),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse((e=>{e instanceof d&&(e.material.wireframe=!0)})):t.traverse((e=>{e instanceof d&&(e.material.wireframe=!1)}))}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);_e(e.materialAssignments,a.materialAssignments).forEach((e=>this.applyMaterial(t,e)))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)),this.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new r(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0)}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient);else if("landscape"===e.shape){const a=this.landscapeManagers.find((t=>t.source.id===e.id)).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>!0))}))}else if("global_fog"===e.type){const t=(this.scene.fog instanceof o?"density":"linear")!==e.fog.type;this.scene.fog=ke(e.fog),t&&(a=this.scene).traverse((e=>{if(e instanceof d){const t=e.material;t instanceof V&&(a.fog instanceof n?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof o&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}})),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.editorActorParamSnapshot.get(e.id);null!=t&&t===JSON.stringify(e.actor)||(console.log("Rematerializing actor because parameters changed"),s||(this.remove(e),await this.materializeAndInitActor(e)))}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof oe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&xe(t,e.castShadow,e.receiveShadow),e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){console.log("materialize actor and init");const a=await this.materialize(e,t);return Fe(e,(async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}})),a}findParent(e){const t=this.dataProvider.getObjects().flatMap((t=>t.id===e.id?null:te(t,(t=>t.children?.some((t=>t.id===e.id))),(()=>!0))))[0];return null==t?this.scene:null!=t?ae(this.scene,(e=>e.userData?.src?.id===t.id),(e=>null!=e.userData?.src))[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new r(this.scene.fog.color))}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;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=K(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof d){if(null==e.geometry)return;if(Be(ue(e,0,!1)),a>0){Be(ue(e,0,!1))}}}));const r=new Set;for(const[e,i]of s.entries()){const s=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==s||null==s.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=ue(s,0,!0);Be(o);for(const e of i)o.setX(e.i,e.w[0]??0),o.setY(e.i,e.w[1]??0),o.setZ(e.i,e.w[2]??0),o.setW(e.i,e.w[3]??0),n=!0;if(a>0){const e=ue(s,4,!0);Be(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&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)))))}async materialize(e,t,a=!1){let r;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=ke(e.fog),this.fixFogColor(),r=new l;break;case"sky":this.sky=Se(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new l,this.worldEnvObj=r;break;case"actor":r=await this.createFromActor(e);break;case"group":r=new l;break;case"prefab":r=await this.createFromPrefabAsset(e);break;case"vfx":r=await this.createFromVfx(e);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a||(r.userData.src=e),this.inEditor,this.inEditor){let e=null;r instanceof oe&&(e=function(e){if(e instanceof ne)return new d(new s(...e.offset.toArray()),Ce);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}return this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==U.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map((e=>this.materialize(e,r,a)))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==U.dynamic||Ne(r),this.renderingView.renderer.shadowMap.needsUpdate=!0,r}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao),this.renderingView.aoPass.output=!0===e.worldEnv.ao.onlyAO?5:0;const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const s=e.worldEnv.environment;null!=s&&null!=s.textureId?this.assetManagerService.getTexture(this.assets.get(s.textureId)).then((e=>{null==this.pmremGenerator&&(this.pmremGenerator=new a.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=s.intensity??1})):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=Ae);const t=await this.assetsService.getAsset(e.sky.materialId),s=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);s.side=a.BackSide,(s instanceof u||s instanceof a.MeshBasicMaterial||s instanceof a.ShaderMaterial)&&(s.fog=!1),null!=this.sky?this.sky.material=s:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new Me[a.path+"/"+a.className],i=t.id+s;r.id=i,r.object=e;for(const e of a.params)null!=e.value&&(r[e.name]=e.value);return this.components.push(r),i}async createFromActor(e){const t=this.actorTypes.find((t=>t.name===e.actor?.type))?.type??R[e.actor?.type];if(null==t)return null;this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const a=await this.actorProvider.create(t,(new A).fromArray(e.position),(new i).fromArray(e.rotation),!0);return this.materializedActors.set(e.id,a),a?.object}async createFromVfx(e){const t=await this.assetsService.getAsset(e.assetId);null==t&&console.error("Could not find asset",e);const a=await this.actorProvider.create(T,(new A).fromArray(e.position),(new i).fromArray(e.rotation),!1);return await a.fromAsset(t),a.play(),this.materializedActors.set(e.id,a),a?.object}cleanup(){this.materializedActors.clear()}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse((e=>{e instanceof d&&this._originalMaterials.set(e.id,e.material)}));else{let s=new u({name:"Default",color:new r("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const i=await this.createMeshByShape(e.shape,s,e.shapeParams);i.castShadow=e.castShadow??!0,i.receiveShadow=e.castShadow??!1,e.collisionDetection||(i.collisionShape=null),i.physics=e.physics,a=i,this._originalMaterials.set(a.id,i.material),a.traverse((e=>{}))}return t||(await Promise.all((e.materialAssignments??[]).filter((e=>null!=e.materialId)).map((e=>this.applyMaterial(a,e)))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new l;const a=ce(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new le(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,(t=>{(e.materialAssignments??[]).filter((e=>null!=e.materialId)).forEach((e=>this.applyMaterial(t,e)))}));return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new he(e.sections);for(const e of t??[]){const t=s.find(e.x,e.y);if(!t)return;const a=t.geometry.getAttribute("position");for(const t of e.points)a.setY(t.i,t.y);a.needsUpdate=!0}const r=e.sections;r.forEach((e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()})),this.inEditor&&!a||setTimeout((()=>de(r)),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&we.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);return this.geometryCache.has(r)||this.geometryCache.set(r,ge[e].geometry(s)),this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,ge[e].collision(s)),new oe(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async createFromAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:a}=await this.assetManagerService.getMesh(t,{mergeGeomtries:!0});_e(e.materialAssignments,t.materialAssignments).forEach((e=>this.applyMaterial(a,e)));const s=e.receiveShadow??!!t.receiveShadow??!0,r=e.castShadow??!!t.castShadow??!1;return a.receiveShadow=s,xe(a,r,s),e.collisionDetection||(a.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(a.physics=e.physics),this.applyVertexMaterials(e,a),a.traverse((e=>{e instanceof d&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()})),a}async createFromPrefabAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);const a=new l;return t.prefab.objects.filter((e=>"global_fog"!==e.type&&"world_env"!==e.type)).forEach((e=>this.materialize(e,a,!0))),a}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),s=new f;return await M.fromJSONAsync(t.particleSystem,a).then((e=>{const t=new x(s,a);e.addRenderer(t),this.renderingView.onLoop((t=>e.update()))})),s}async createLight(e){if("point"===e.light.type){const t=new y(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=new w(.3,10,10),a=new u({color:new r(16771709)}),s=new d(e,a);t.add(s)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional),new l):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient),new l):void 0}applyDirectionalAmbientLight(e,t){const a=this.scene.children.find((e=>e.name===ve));null!=a?(a.intensity=t.intensity,a.color.set(t.color),a.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(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach((e=>e.disposed.next(!0)))}}function xe(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse((e=>{e.castShadow=t,e.receiveShadow=a}))}const je=new Map,Pe=new Map,Ie=new m({color:16711935}),Ee=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&je.has(n)?je.get(n):i&&Pe.has(n)?await Pe.get(n):Pe.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,s,i,n,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new r(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await i.getAsset(e);null!=a&&(c.map=await n.getTexture(a))}let d;switch(t.material.type){case"phong":d=new p({...c,...h});break;case"water":d=fe(c,s);break;case"grassFoliage":d=me({color:c.color,map:c.map},s);break;case"grass":d=pe({...c,colorTwo:new r(t.material.params.colorTwo),colorThree:new r(t.material.params.colorThree)},s);break;case"standard":case"unlit":case"lambert":case"shader":case"landscape":case"landscape-composite":const e={standard:X,lambert:J,unlit:Y,landscape:q,"landscape-composite":H}[t.material.type]??o.find((e=>e.name==t.material.shader))?.type;if(e){try{let a=new e;const r=await Ve(t.material?.shaderParams??{},e,i,n,null,s,o);Object.assign(a,r),d=a.build()}catch(e){console.log("Shader runtime error: "+e),Ee.has(t.material.shader)||Ee.set(t.material.shader,Ie.clone()),d=Ee.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=Ie;break;default:throw new Error("Unsupported material type"+t.material.type)}return s?.csm.setupMaterial(d),null!=s&&je.set(e,d),d.side=t.material.side??d.side??a.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,t.material.bloom&&(d.userData.hasBloom=!0),d.userData.assetId=t.id,Pe.delete(e),d}async function Ve(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await De(c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await De(s,null,null,null);null!=e&&(t[a]=e)}return t}async function De(e,t,a,s,n,o,l,c=e.value,h=e.type){if(null==e||null==c||""===c)return null;switch(h){case ye.Array:if(Array.isArray(c)&&"element"in e)return await Promise.all(c.map((r=>De(e,t,a,s,n,o,l,r,e.element))));break;case ye.Number:case ye.FloatNode:let h="string"==typeof c?parseFloat(c):c;return e.type===ye.FloatNode?I(h):h;case ye.Texture:return await a.getTexture(await t.getAsset(c));case ye.Sampler2DNode:return C(await a.getTexture(await t.getAsset(c)));case ye.Boolean:return c;case ye.BooleanNode:return j(c);case ye.Vector2:case ye.Vec2Node:if("object"==typeof c){const t=c instanceof Array?(new S).fromArray(c):new S(c.x,c.y);return e.type===ye.Vec2Node?F(t):t}return null;case ye.Vector3:case ye.Vec3Node:if("object"==typeof c){const t=c instanceof Array?(new A).fromArray(c):new A(c.x,c.y,c.z);return e.type===ye.Vec3Node?O(t):t}return null;case ye.Color:case ye.RgbNode:const d=new r(c);return e.type===ye.RgbNode?D(d):d;case ye.String:return c;case ye.BaseActor:const m=c;return null==s&&console.warn("Class parameters can not be prepared as actors are not passed in"),s?.get(m);case ye.Euler:const p=c;return(new i).fromArray(p);case ye.Object3D:return(await a.getMesh(await t.getAsset(c))).scene;case ye.Material:return await materialFromAsset(await t.getAsset(c),n,t,a,o);case ye.AudioBuffer:return await a.getAudio(await t.getAsset(c));case ye.VisualEffect:const u=await t.getAsset(c);if(null==l){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in u)return new W(l,u);console.error("Using a non-vfx asset for visual effect parameter");break;case ye.Curve:return be.decode(c)}return null}function Ne(e){e.updateWorldMatrix(!0,!0),e.updateMatrix(),e.traverse((e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}));const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}function ke(e){return"linear"===e.type?new n(new r(e.color),e.near??100,e.far??1e3):"density"===e.type?new o(e.color,e.density):void console.warn("Invalid fog type",e)}const Ce=new u({color:4229780});async function Fe(e,t,s,r){null==r&&(r=(new h).identity()),await t(e,s,r);const n=r.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new A).fromArray(e.position),(new g).setFromEuler((new i).fromArray(e.rotation)),(new A).fromArray(e.scale))}(e,new a.Matrix4));return Promise.all((e.children??[]).map((a=>Fe(a,t,e,n))))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?ye.Number:t instanceof E||"function"==typeof e.prototype.isFloat?ye.FloatNode:t instanceof v||e===v||e.isTexture?ye.Texture:t instanceof L||e===k?ye.Sampler2DNode:t instanceof Boolean||e===Boolean?ye.Boolean:t instanceof P?ye.BooleanNode:t instanceof r||e==r?ye.Color:t instanceof N||"function"==typeof e.prototype.isRgb?ye.RgbNode:t instanceof S||e==S?ye.Vector2:t instanceof _||"function"==typeof e.prototype.isVec2?ye.Vec2Node:t instanceof A||e==A?ye.Vector3:t instanceof z||"function"==typeof e.prototype.isVec3?ye.Vec3Node:t instanceof String||e===String?ye.String:t instanceof $||e==$||e.prototype instanceof $||e.prototype==$?ye.BaseActor:t instanceof i||e==i?ye.Euler:t instanceof f||e==f?ye.Object3D:t instanceof c||e==c?ye.Material:t instanceof AudioBuffer||e==AudioBuffer?ye.AudioBuffer:t instanceof W||e==W?ye.VisualEffect:t instanceof be||e==be?ye.Curve:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map((e=>[e.name,{type:e.options.array?ye.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}])))}export function prepareCustomParamsFromType(e,t,a=null){const s=Z(e);if(0===s.length)return{};let r;null!=a?G(a,(()=>{r=a.get(e)})):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case S:return t instanceof S?t.toArray():void a();case A:return t instanceof A?t.toArray():void a();case b:return t instanceof b?t.toArray():void a();case r:return t instanceof r?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new r(t).getHexString():void a();case String:return t;case i:return t instanceof i?t.toArray():void a()}}function _e(e,t){return function(e,t,a){const s=[],r=new Set;for(const i of[...e??[],...t??[]]){const e=a(i);r.has(e)||(r.add(e),s.push(i))}return s}((e??[]).filter((e=>Oe(e.materialId))),(t??[]).filter((e=>Oe(e.materialId))),(e=>e.color+e.name))}function Oe(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[ye.RgbNode,"#000000"],[ye.Color,"#000000"],[ye.Vector4,[0,0,0,0]],[ye.Vec4Node,[0,0,0,0]],[ye.Vector3,[0,0,0]],[ye.Vec3Node,[0,0,0]],[ye.Vector2,[0,0]],[ye.Vec2Node,[0,0]],[ye.Euler,[0,0,0,"XYZ"]],[ye.Array,[]]]);export function applyMaterial(e,t,s,i){const n=[];return e.traverse((async e=>{if(e instanceof d||e.isMesh||e instanceof a.SkinnedMesh||e.isSkinnedMesh)for(const t of ee(e.material))t.hasOwnProperty("color")&&n.push(e)})),Promise.all(n.map((async e=>{if(e.material instanceof Array)for(let a=0;a<e.material.length;a++){const n=e.material[a];if(null==n.color||!(n.color instanceof r))continue;const o="#"+n.color.getHexString(),l=n.name;if(o===t.color&&(n.name===t.name||null==t.name)||e.userData["originalColor_"+a]===t.color&&e.userData["originalMaterialName_"+a]===t.name){const r=await s(t.materialId),n=e.material[a];null!=r&&n.id!=r.id&&(e.material[a]=r,e.userData["originalColor_"+a]=e.userData["originalColor_"+a]??o,e.userData["originalMaterialName_"+a]=e.userData["originalMaterialName_"+a]??l,null!=i&&i.set(e.id+"#"+a,n))}}else if("color"in e.material){const a="#"+e.material.color.getHexString(),r=e.material.name;if(a===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await s(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??a,e.userData.originalMaterialName=e.userData.originalMaterialName??r,null!=i&&(i.has(e.id)||i.set(e.id,o)))}}})))}function ze(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return console.log("Different values",t.uniforms[a].value,e.uniforms[a].value),!1}return!0}return!1}(e,t)}return!1}function Be(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
|
1
|
+
import{ConvexPolyhedronCollisionShape as e}from"@hology/core";import{Subject as t}from"rxjs";import*as a from"three";import{BoxGeometry as s,Color as r,Euler as i,Fog as n,FogExp2 as o,Group as l,Material as c,Matrix4 as h,Mesh as d,MeshLambertMaterial as m,MeshPhongMaterial as p,MeshStandardMaterial as u,Object3D as f,PointLight as y,Quaternion as g,SphereGeometry as w,Texture as v,Vector2 as S,Vector3 as A,Vector4 as b}from"three";import M,{SpriteRenderer as x}from"@hology/nebula";import{bool as j,BooleanNode as P,float as I,FloatNode as E,NodeShaderMaterial as V,rgb as D,RgbNode as N,Texture2dLookupNode as C,textureSampler2d as k,vec2 as _,Vec2Node as F,vec3 as O,Vec3Node as T,vec4 as z}from"three-shader-graph";import{VfxActor as B}from"../effects/vfx/vfx-actor.js";import{VisualEffect as W}from"../effects/vfx/vfx-param.js";import{BaseActor as $}from"../gameplay/actors/actor.js";import R from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as U,withInjectionContext as G}from"../gameplay/index.js";import{Sampler2DNode as L}from"../shader-nodes/index.js";import{LambertShader as J}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as H}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as q}from"../shader/builtin/landscape-shader.js";import{StandardShader as X}from"../shader/builtin/standard-shader.js";import{UnlitShader as Y}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Z}from"../shader/parameter.js";import{ArrayMap as Q,groupBy as K}from"../utils/collections.js";import{iterateMaterials as ee}from"../utils/materials.js";import{filterChildrenShallow as te,filterSceneShallow as ae,findFirstVisibleObject as se}from"../utils/three/traverse.js";import{AssetMeshInstance as re}from"./asset-resource-loader.js";import{isCollisionMesh as ie}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ne,PhysicalShapeMesh as oe}from"./collision/collision-shape.js";import{LandscapeManager as le}from"./landscape/landscape-manager.js";import{initLandscape as ce}from"./landscape/landscape.js";import{SectionGrid as he,smoothNormalsCrossMeshes as de}from"./landscape/utils.js";import{createGrassFoliageMaterial as me}from"./materials/grass-foliage.js";import{createGrassMaterial as pe}from"./materials/grass.js";import{getMaterialAttribute as ue}from"./materials/utils/material-painting.js";import{createWaterMaterial as fe}from"./materials/water.js";import{SerializedParamType as ye}from"./model.js";import{ShapeLibrary as ge,ShapeLibraryKeys as we}from"./objects/shapes.js";import{ambientLightName as ve,createSky as Se,defaultSkyMaterial as Ae}from"./sky.js";import{Curve2 as be}from"../utils/curve.js";const Me={};export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,a){this.dataProvider=e,this.assetsService=t,this.assetManagerService=a}get(e,t){return new SceneMaterializer(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}export class SceneMaterializer{constructor(e,s,r,i,n,o,l,c){this.scene=e,this.dataProvider=s,this.assetsService=r,this.assetManagerService=i,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.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,s.onCreate((e=>this.update(e))),s.onUpdate((e=>this.update(e))),s.onRemove((e=>this.remove(e))),this.createAssetSubscription=r.onCreate.subscribe((e=>{this.assets.set(e.id,e)})),this.updateSubscription=r.onUpdate.subscribe((async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse((e=>{if(e instanceof a.Mesh)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)})):"mesh"==t.type?(this.findByAssetId(t.id).forEach((e=>{Fe(e.userData.src.materialAssignments,t.materialAssignments).forEach((t=>{this.applyMaterial(e,t)}))})),this.landscapeManagers.forEach((e=>{const a=e.source?.grass?.layers?.some((e=>e.meshes.some((e=>e.assetId===t.id))));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new A,!0)}))):"prefab"===t.type&&this.findByAssetId(t.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}))}))}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===ye.Material&&s.value===a.id){t=!0;break}if(s.type===ye.Array&&"element"in s&&s.element===ye.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);i.userData=t.userData,null!=s?Te(e.material[s],i)||(e.material[s]=i):Te(e.material,i)||(e.material=i)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter((e=>"shape_mesh"===e.type||"asset_mesh"===e.type)).filter((e=>null!=e.materialAssignments)).flatMap((e=>e.materialAssignments)).map((async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===ye.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}}))),await Promise.all(Array.from(this.assets.values()).map((async t=>{if("texture"===t.type){const a=await this.assetManagerService.getTexture(t);e.push(a)}}))),0!==e.length){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter((e=>null!=e.assetId&&"asset_mesh"==e.type)).filter((e=>e.assetId))));await Promise.all(e.map((e=>this.assetsService.getAsset(e.assetId).then((e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))))),this.initTextures()}async init(){await this.preInit(),je.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map((e=>this.materialize(e)))),await this.initActorsPostInit()}initActorsPostInit(e=this.actorInstances){const t=e.map((async e=>{const t=e.object.userData.src??e.object.userData._src;if("vfx"===t.type)return Promise.resolve();const a=await this.assetsService.getAsset(t.assetId),s={...a?.actor?.params??{},...t.actor?.params??{}};for(const a of t.actor.innerParams??[])await this.applyActorComponentParams(e,a.path.slice(),a.params);const r=await Ve(s,e.constructor,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,r);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${t.name}", id=${t.id})`,e)}}));return Promise.all(t)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a){const s=t.length,r=t.shift();if(0==s){const t=await Ve(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[r]&&await this.applyActorComponentParams(e[r],t,a)}canObjectBeInstanced(e){return e.physics?.type!==U.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){if(!this._canBeInstancedCache.has(e.assetId)){const t=await this.createFromAsset(e);if(null==t)return!1;const a=[];t.traverse((e=>{!ie(e)&&e.isMesh&&a.push(e)}));const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof d&&null!=a[0].geometry.morphAttributes&&Object.keys(a[0].geometry.morphAttributes).length>0,i=!0;this._canBeInstancedCache.set(e.assetId,s&&i&&!r)}return this._canBeInstancedCache.get(e.assetId)}async preInit(){this.renderingView?.onLoop((()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)})),this.assetsService.getAssets().then((e=>{for(const t of e)this.assets.set(t.id,t)}))}async initWithInstancing(){await this.preInit(),await this.prefetchAssets();const t=[],s=new Q,n=new Q;for(const e of this.dataProvider.getObjects())await _e(e,(async(e,a,i)=>{const o="asset_mesh"==e.type&&this.canObjectBeInstanced(e)&&await this.canAssetBeInstanced(e),l="shape_mesh"===e.type&&"landscape"!==e.shape&&e.physics?.type!==U.dynamic;if(o||l){if(a&&a.children?.length>0){const t=a.children.findIndex((t=>t.id===e.id));t>=0&&a.children.splice(t,1)}if(l){let t=e.shape+JSON.stringify(e.shapeParams??{})+e.castShadow+e.receiveShadow;const a=e.materialAssignments?.at(0)?.materialId,s=null!=a?this.assets.get(a):null;let o=null;if(null!=s&&"shader"!==s.material.type){if(t+=s.material.type+s.material.shader,null!=s.material.shaderParams){if(t+=Object.entries(s.material.shaderParams).filter((([e,t])=>"color"!=e)).map((e=>JSON.stringify(e))).join(),null!=s.material.shaderParams.color){const e=s.material.shaderParams.color;e.type===ye.Color&&null!=e.value&&(o=new r(e.value))}}}else t+=a;n.push(t,{object:{...e,parentTransform:i},color:o})}else{const t=e.assetId+JSON.stringify(e.materialAssignments??[]);s.push(t,{...e,parentTransform:i})}}else null==a&&t.push({...e,parentTransform:i})}));for(const t of s.values()){if(0==t.length)continue;const a=await this.createFromAsset(t[0]);if(null==a)continue;const s=await this.createInstancedMesh(t,a),r=new re;r.add(s),r.userData.src=t[0],a instanceof re&&(r.collisionShapes=a.collisionShapes),r.collisionShapes.forEach((t=>{t instanceof e&&t.mesh instanceof d&&(t.mesh=t.mesh.geometry)})),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of n.values()){if(0==e.length)continue;const t=e[0].object,s=await this.createFromShape(t),n=se(s,(e=>!ie(e)&&null!=e.geometry)),o=n.material.clone();null!=e[0].color&&null!=o.color&&(o.color=new r(16777215));const l=n.geometry,c=new a.InstancedMesh(l,o,e.length);for(let t=0;t<e.length;t++){const r=e[t],o=(new a.Matrix4).compose((new A).fromArray(r.object.position),(new g).setFromEuler((new i).fromArray(r.object.rotation)),(new A).fromArray(r.object.scale)),l=(new h).copy(r.object.parentTransform).multiply(o);c.setMatrixAt(t,l),null!=r.color&&c.setColorAt(t,r.color),c.castShadow=s.castShadow??!0,c.receiveShadow=n.receiveShadow??!0;const d=new re;d.add(c),d.userData.src=e[0],s instanceof oe&&(d.collisionShapes=[s.collisionShape]),d.castShadow=!1,d.receiveShadow=!1,this.scene.add(d)}}await Promise.all(t.map((e=>this.materialize(e)))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const s=se(t,(e=>!ie(e)&&null!=e.geometry)),r=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Fe(e[0].materialAssignments,r.materialAssignments)),s.updateMatrix();const n=s.geometry.clone(),o=new a.InstancedMesh(n,s.material,e.length);for(let t=0;t<e.length;t++){const r=(new a.Matrix4).compose((new A).fromArray(e[t].position),(new g).setFromEuler((new i).fromArray(e[t].rotation)),(new A).fromArray(e[t].scale)),n=(new h).copy(e[t].parentTransform).multiply(r).multiply(s.matrixWorld);o.setMatrixAt(t,n)}return o.castShadow=e[0].castShadow??r.castShadow??!0,o.receiveShadow=e[0].receiveShadow??r.receiveShadow??!0,s.material instanceof c&&o.castShadow&&o.receiveShadow&&(o.material.side=a.FrontSide),o}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}const t=this.sceneObjectMap.get(e.id);t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter((t=>t.object.userData.src?.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 ae(this.scene,(t=>t.userData.src?.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))))}async applyMaterial(e,t){await applyMaterial(e,t,(e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}}),this._originalMaterials)}unapplyMaterials(e){e.traverse((async e=>{if(e instanceof d)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material}))}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(R));ae(this.scene,(e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type))).forEach((async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)}))}updateShaders(e){this.shaders=e;for(const[e,t]of je.entries())t.userData.customShaderName&&je.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),ae(this.scene,(e=>!0)).forEach((e=>{e.traverse((async e=>{if(e instanceof d)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}}))}))}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(s=!0)})),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse((e=>{e instanceof d&&(e.material.wireframe=!0)})):t.traverse((e=>{e instanceof d&&(e.material.wireframe=!1)}))}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);Fe(e.materialAssignments,a.materialAssignments).forEach((e=>this.applyMaterial(t,e)))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)),this.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new r(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0)}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient);else if("landscape"===e.shape){const a=this.landscapeManagers.find((t=>t.source.id===e.id)).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>!0))}))}else if("global_fog"===e.type){const t=(this.scene.fog instanceof o?"density":"linear")!==e.fog.type;this.scene.fog=Ce(e.fog),t&&(a=this.scene).traverse((e=>{if(e instanceof d){const t=e.material;t instanceof V&&(a.fog instanceof n?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof o&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}})),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.editorActorParamSnapshot.get(e.id);null!=t&&t===JSON.stringify(e.actor)||s||(this.remove(e),await this.materializeAndInitActor(e))}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof oe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&xe(t,e.castShadow,e.receiveShadow),e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){console.log("materialize actor and init");const a=await this.materialize(e,t);return _e(e,(async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}})),a}findParent(e){const t=this.dataProvider.getObjects().flatMap((t=>t.id===e.id?null:te(t,(t=>t.children?.some((t=>t.id===e.id))),(()=>!0))))[0];return null==t?this.scene:null!=t?ae(this.scene,(e=>e.userData?.src?.id===t.id),(e=>null!=e.userData?.src))[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new r(this.scene.fog.color))}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;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=K(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof d){if(null==e.geometry)return;if(ze(ue(e,0,!1)),a>0){ze(ue(e,0,!1))}}}));const r=new Set;for(const[e,i]of s.entries()){const s=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==s||null==s.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=ue(s,0,!0);ze(o);for(const e of i)o.setX(e.i,e.w[0]??0),o.setY(e.i,e.w[1]??0),o.setZ(e.i,e.w[2]??0),o.setW(e.i,e.w[3]??0),n=!0;if(a>0){const e=ue(s,4,!0);ze(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&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)))))}async materialize(e,t,a=!1){let r;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Ce(e.fog),this.fixFogColor(),r=new l;break;case"sky":this.sky=Se(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new l,this.worldEnvObj=r;break;case"actor":r=await this.createFromActor(e);break;case"group":r=new l;break;case"prefab":r=await this.createFromPrefabAsset(e);break;case"vfx":r=await this.createFromVfx(e);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,this.inEditor,this.inEditor){let e=null;r instanceof oe&&(e=function(e){if(e instanceof ne)return new d(new s(...e.offset.toArray()),ke);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}return this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==U.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map((e=>this.materialize(e,r,a)))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==U.dynamic||Ne(r),this.renderingView.renderer.shadowMap.needsUpdate=!0,r}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao),this.renderingView.aoPass.output=!0===e.worldEnv.ao.onlyAO?5:0;const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const s=e.worldEnv.environment;null!=s&&null!=s.textureId?this.assetManagerService.getTexture(this.assets.get(s.textureId)).then((e=>{null==this.pmremGenerator&&(this.pmremGenerator=new a.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=s.intensity??1})):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=Ae);const t=await this.assetsService.getAsset(e.sky.materialId),s=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);s.side=a.BackSide,(s instanceof u||s instanceof a.MeshBasicMaterial||s instanceof a.ShaderMaterial)&&(s.fog=!1),null!=this.sky?this.sky.material=s:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new Me[a.path+"/"+a.className],i=t.id+s;r.id=i,r.object=e;for(const e of a.params)null!=e.value&&(r[e.name]=e.value);return this.components.push(r),i}async createFromActor(e){const t=this.actorTypes.find((t=>t.name===e.actor?.type))?.type??R[e.actor?.type];if(null==t)return null;this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const a=await this.actorProvider.create(t,(new A).fromArray(e.position),(new i).fromArray(e.rotation),!0);return this.materializedActors.set(e.id,a),a?.object}async createFromVfx(e){const t=await this.assetsService.getAsset(e.assetId);null==t&&console.error("Could not find asset",e);const a=await this.actorProvider.create(B,(new A).fromArray(e.position),(new i).fromArray(e.rotation),!1);return await a.fromAsset(t),a.play(),this.materializedActors.set(e.id,a),a?.object}cleanup(){this.materializedActors.clear()}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse((e=>{e instanceof d&&this._originalMaterials.set(e.id,e.material)}));else{let s=new u({name:"Default",color:new r("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const i=await this.createMeshByShape(e.shape,s,e.shapeParams);i.castShadow=e.castShadow??!0,i.receiveShadow=e.castShadow??!1,e.collisionDetection||(i.collisionShape=null),i.physics=e.physics,a=i,this._originalMaterials.set(a.id,i.material),a.traverse((e=>{}))}return t||(await Promise.all((e.materialAssignments??[]).filter((e=>null!=e.materialId)).map((e=>this.applyMaterial(a,e)))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new l;const a=ce(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new le(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,(t=>{(e.materialAssignments??[]).filter((e=>null!=e.materialId)).forEach((e=>this.applyMaterial(t,e)))}));return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new he(e.sections);for(const e of t??[]){const t=s.find(e.x,e.y);if(!t)return;const a=t.geometry.getAttribute("position");for(const t of e.points)a.setY(t.i,t.y);a.needsUpdate=!0}const r=e.sections;r.forEach((e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()})),this.inEditor&&!a||setTimeout((()=>de(r)),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&we.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);return this.geometryCache.has(r)||this.geometryCache.set(r,ge[e].geometry(s)),this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,ge[e].collision(s)),new oe(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async createFromAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:a}=await this.assetManagerService.getMesh(t,{mergeGeomtries:!0});Fe(e.materialAssignments,t.materialAssignments).forEach((e=>this.applyMaterial(a,e)));const s=e.receiveShadow??!!t.receiveShadow??!0,r=e.castShadow??!!t.castShadow??!1;return a.receiveShadow=s,xe(a,r,s),e.collisionDetection||(a.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(a.physics=e.physics),this.applyVertexMaterials(e,a),a.traverse((e=>{e instanceof d&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()})),a}async createFromPrefabAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);const a=new l;return t.prefab.objects.filter((e=>"global_fog"!==e.type&&"world_env"!==e.type)).forEach((e=>this.materialize(e,a,!0))),a}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),s=new f;return await M.fromJSONAsync(t.particleSystem,a).then((e=>{const t=new x(s,a);e.addRenderer(t),this.renderingView.onLoop((t=>e.update()))})),s}async createLight(e){if("point"===e.light.type){const t=new y(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=new w(.3,10,10),a=new u({color:new r(16771709)}),s=new d(e,a);t.add(s)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional),new l):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient),new l):void 0}applyDirectionalAmbientLight(e,t){const a=this.scene.children.find((e=>e.name===ve));null!=a?(a.intensity=t.intensity,a.color.set(t.color),a.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(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach((e=>e.disposed.next(!0)))}}function xe(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse((e=>{e.castShadow=t,e.receiveShadow=a}))}const je=new Map,Pe=new Map,Ie=new m({color:16711935}),Ee=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&je.has(n)?je.get(n):i&&Pe.has(n)?await Pe.get(n):Pe.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,s,i,n,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new r(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await i.getAsset(e);null!=a&&(c.map=await n.getTexture(a))}let d;switch(t.material.type){case"phong":d=new p({...c,...h});break;case"water":d=fe(c,s);break;case"grassFoliage":d=me({color:c.color,map:c.map},s);break;case"grass":d=pe({...c,colorTwo:new r(t.material.params.colorTwo),colorThree:new r(t.material.params.colorThree)},s);break;case"standard":case"unlit":case"lambert":case"shader":case"landscape":case"landscape-composite":const e={standard:X,lambert:J,unlit:Y,landscape:q,"landscape-composite":H}[t.material.type]??o.find((e=>e.name==t.material.shader))?.type;if(e){try{let a=new e;const r=await Ve(t.material?.shaderParams??{},e,i,n,null,s,o);Object.assign(a,r),d=a.build()}catch(e){console.log("Shader runtime error: "+e),Ee.has(t.material.shader)||Ee.set(t.material.shader,Ie.clone()),d=Ee.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=Ie;break;default:throw new Error("Unsupported material type"+t.material.type)}return s?.csm.setupMaterial(d),null!=s&&je.set(e,d),d.side=t.material.side??d.side??a.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,t.material.bloom&&(d.userData.hasBloom=!0),d.userData.assetId=t.id,Pe.delete(e),d}async function Ve(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await De(c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await De(s,null,null,null);null!=e&&(t[a]=e)}return t}async function De(e,t,a,s,n,o,l,c=e.value,h=e.type){if(null==e||null==c||""===c)return null;switch(h){case ye.Array:if(Array.isArray(c)&&"element"in e)return await Promise.all(c.map((r=>De(e,t,a,s,n,o,l,r,e.element))));break;case ye.Number:case ye.FloatNode:let h="string"==typeof c?parseFloat(c):c;return e.type===ye.FloatNode?I(h):h;case ye.Texture:return await a.getTexture(await t.getAsset(c));case ye.Sampler2DNode:return k(await a.getTexture(await t.getAsset(c)));case ye.Boolean:return c;case ye.BooleanNode:return j(c);case ye.Vector2:case ye.Vec2Node:if("object"==typeof c){const t=c instanceof Array?(new S).fromArray(c):new S(c.x,c.y);return e.type===ye.Vec2Node?_(t):t}return null;case ye.Vector3:case ye.Vec3Node:if("object"==typeof c){const t=c instanceof Array?(new A).fromArray(c):new A(c.x,c.y,c.z);return e.type===ye.Vec3Node?O(t):t}return null;case ye.Color:case ye.RgbNode:const d=new r(c);return e.type===ye.RgbNode?D(d):d;case ye.String:return c;case ye.BaseActor:const m=c;return null==s&&console.warn("Class parameters can not be prepared as actors are not passed in"),s?.get(m);case ye.Euler:const p=c;return(new i).fromArray(p);case ye.Object3D:return(await a.getMesh(await t.getAsset(c))).scene;case ye.Material:return await materialFromAsset(await t.getAsset(c),n,t,a,o);case ye.AudioBuffer:return await a.getAudio(await t.getAsset(c));case ye.VisualEffect:const u=await t.getAsset(c);if(null==l){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in u)return new W(l,u);console.error("Using a non-vfx asset for visual effect parameter");break;case ye.Curve:return be.decode(c)}return null}function Ne(e){e.updateWorldMatrix(!0,!0),e.updateMatrix(),e.traverse((e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}));const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}function Ce(e){return"linear"===e.type?new n(new r(e.color),e.near??100,e.far??1e3):"density"===e.type?new o(e.color,e.density):void console.warn("Invalid fog type",e)}const ke=new u({color:4229780});async function _e(e,t,s,r){null==r&&(r=(new h).identity()),await t(e,s,r);const n=r.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new A).fromArray(e.position),(new g).setFromEuler((new i).fromArray(e.rotation)),(new A).fromArray(e.scale))}(e,new a.Matrix4));return Promise.all((e.children??[]).map((a=>_e(a,t,e,n))))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?ye.Number:t instanceof E||"function"==typeof e.prototype.isFloat?ye.FloatNode:t instanceof v||e===v||e.isTexture?ye.Texture:t instanceof L||e===C?ye.Sampler2DNode:t instanceof Boolean||e===Boolean?ye.Boolean:t instanceof P?ye.BooleanNode:t instanceof r||e==r?ye.Color:t instanceof N||"function"==typeof e.prototype.isRgb?ye.RgbNode:t instanceof S||e==S?ye.Vector2:t instanceof F||"function"==typeof e.prototype.isVec2?ye.Vec2Node:t instanceof A||e==A?ye.Vector3:t instanceof T||"function"==typeof e.prototype.isVec3?ye.Vec3Node:t instanceof String||e===String?ye.String:t instanceof $||e==$||e.prototype instanceof $||e.prototype==$?ye.BaseActor:t instanceof i||e==i?ye.Euler:t instanceof f||e==f?ye.Object3D:t instanceof c||e==c?ye.Material:t instanceof AudioBuffer||e==AudioBuffer?ye.AudioBuffer:t instanceof W||e==W?ye.VisualEffect:t instanceof be||e==be?ye.Curve:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map((e=>[e.name,{type:e.options.array?ye.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}])))}export function prepareCustomParamsFromType(e,t,a=null){const s=Z(e);if(0===s.length)return{};let r;null!=a?G(a,(()=>{r=a.get(e)})):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case S:return t instanceof S?t.toArray():void a();case A:return t instanceof A?t.toArray():void a();case b:return t instanceof b?t.toArray():void a();case r:return t instanceof r?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new r(t).getHexString():void a();case String:return t;case i:return t instanceof i?t.toArray():void a()}}function Fe(e,t){return function(e,t,a){const s=[],r=new Set;for(const i of[...e??[],...t??[]]){const e=a(i);r.has(e)||(r.add(e),s.push(i))}return s}((e??[]).filter((e=>Oe(e.materialId))),(t??[]).filter((e=>Oe(e.materialId))),(e=>e.color+e.name))}function Oe(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[ye.RgbNode,"#000000"],[ye.Color,"#000000"],[ye.Vector4,[0,0,0,0]],[ye.Vec4Node,[0,0,0,0]],[ye.Vector3,[0,0,0]],[ye.Vec3Node,[0,0,0]],[ye.Vector2,[0,0]],[ye.Vec2Node,[0,0]],[ye.Euler,[0,0,0,"XYZ"]],[ye.Array,[]]]);export function applyMaterial(e,t,s,i){const n=[];return e.traverse((async e=>{if(e instanceof d||e.isMesh||e instanceof a.SkinnedMesh||e.isSkinnedMesh)for(const t of ee(e.material))t.hasOwnProperty("color")&&n.push(e)})),Promise.all(n.map((async e=>{if(e.material instanceof Array)for(let a=0;a<e.material.length;a++){const n=e.material[a];if(null==n.color||!(n.color instanceof r))continue;const o="#"+n.color.getHexString(),l=n.name;if(o===t.color&&(n.name===t.name||null==t.name)||e.userData["originalColor_"+a]===t.color&&e.userData["originalMaterialName_"+a]===t.name){const r=await s(t.materialId),n=e.material[a];null!=r&&n.id!=r.id&&(e.material[a]=r,e.userData["originalColor_"+a]=e.userData["originalColor_"+a]??o,e.userData["originalMaterialName_"+a]=e.userData["originalMaterialName_"+a]??l,null!=i&&i.set(e.id+"#"+a,n))}}else if("color"in e.material){const a="#"+e.material.color.getHexString(),r=e.material.name;if(a===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await s(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??a,e.userData.originalMaterialName=e.userData.originalMaterialName??r,null!=i&&(i.has(e.id)||i.set(e.id,o)))}}})))}function Te(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function ze(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
package/dist/scene/model.d.ts
CHANGED
@@ -47,7 +47,7 @@ export type TextureSettings = {
|
|
47
47
|
wrapS?: WrapMode;
|
48
48
|
wrapT?: WrapMode;
|
49
49
|
};
|
50
|
-
export
|
50
|
+
export type Asset = {
|
51
51
|
id: string;
|
52
52
|
name: string;
|
53
53
|
filename?: string;
|
@@ -88,7 +88,7 @@ export interface Asset {
|
|
88
88
|
receiveShadow?: boolean;
|
89
89
|
castShadow?: boolean;
|
90
90
|
vfx?: VfxAssetData;
|
91
|
-
}
|
91
|
+
};
|
92
92
|
export type VfxAsset = Asset & {
|
93
93
|
vfx: VfxAssetData;
|
94
94
|
};
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/scene/model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAE,oBAAoB,EAAE,MAAM,gDAAgD,CAAC;AACtF,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,MAAM,MAAM,SAAS,GAAG,MAAM,GAAC,UAAU,GAAC,OAAO,GAAC,WAAW,GAAC,OAAO,GAAC,SAAS,GAAC,OAAO,GAAC,OAAO,GAAC,QAAQ,GAAC,KAAK,CAAA;AAC9G,MAAM,MAAM,SAAS,GAAG,gBAAgB,GAAC,WAAW,CAAA;AACpD,MAAM,MAAM,SAAS,GAAG,OAAO,GAAC,aAAa,GAAC,SAAS,CAAA;AAKvD,oBAAY,mBAAmB;IAC7B,SAAS,IAAI;IACb,MAAM,IAAI;IACV,OAAO,IAAI;IACX,aAAa,IAAI;IACjB,OAAO,IAAI;IACX,WAAW,IAAI;IACf,OAAO,IAAI;IACX,QAAQ,IAAI;IACZ,OAAO,IAAI;IACX,QAAQ,IAAI;IACZ,KAAK,KAAK;IACV,OAAO,KAAK;IACZ,MAAM,KAAK;IACX,SAAS,KAAK;IACd,KAAK,KAAK;IACV,QAAQ,KAAK;IACb,QAAQ,KAAK;IACb,WAAW,KAAK;IAChB,OAAO,KAAK;IACZ,QAAQ,KAAK;IACb,YAA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"file":"prefab.d.ts","sourceRoot":"","sources":["../../../src/scene/objects/prefab.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,QAAQ,EAAE,MAAM,OAAO,CAAA;AAMvC,qBAAa,MAAM;IACjB,OAAO,EAAE,MAAM,CAAA;IAQf,MAAM,IAAI;QAAC,MAAM,EAAE,QAAQ,CAAA;KAA0B;CActD"}
|
@@ -1,21 +1,30 @@
|
|
1
|
-
import { SceneDataProvider, SceneObject } from '../scene/materializer.js';
|
1
|
+
import { SceneDataProvider, SceneObject, ChangeCallback } from '../scene/materializer.js';
|
2
2
|
import { BehaviorSubject } from 'rxjs';
|
3
3
|
import { Matrix4 } from 'three';
|
4
4
|
export declare class SceneDataService implements SceneDataProvider {
|
5
5
|
private objects;
|
6
6
|
private callbacks;
|
7
|
+
private createCallbacks;
|
7
8
|
private removeCallbacks;
|
8
9
|
objectChange: BehaviorSubject<SceneObject[]>;
|
9
10
|
constructor();
|
10
11
|
initiate(data: SceneObject[]): void;
|
11
12
|
private createDefaultObjects;
|
12
|
-
removeOnUpdateCallback(callback:
|
13
|
-
|
14
|
-
|
13
|
+
removeOnUpdateCallback(callback: ChangeCallback): void;
|
14
|
+
onCreate(callback: ChangeCallback): void;
|
15
|
+
onUpdate(callback: ChangeCallback): void;
|
16
|
+
onRemove(callback: ChangeCallback): void;
|
15
17
|
getObjects(): SceneObject[];
|
16
18
|
getObjectsRecursive(): SceneObject[];
|
17
|
-
addObject(object: SceneObject): void;
|
18
|
-
|
19
|
+
addObject(object: SceneObject, remote?: boolean): void;
|
20
|
+
/**
|
21
|
+
* Replaces the object with its new state.
|
22
|
+
* @param object
|
23
|
+
* @param remote Whether the update is made by a synchronization service. This
|
24
|
+
* is forwarded in onUpdate callbacks so they can decide if they should ignore the events
|
25
|
+
* to avoid infite loops by differentiating between updates made locally and remotely.
|
26
|
+
*/
|
27
|
+
updateObject(object: SceneObject, remote?: boolean): void;
|
19
28
|
findObjectById(id: string): SceneObject;
|
20
29
|
findAncestorsById(id: string): SceneObject[];
|
21
30
|
/**
|
@@ -28,7 +37,8 @@ export declare class SceneDataService implements SceneDataProvider {
|
|
28
37
|
updateParent(object: SceneObject, newParent: SceneObject): void;
|
29
38
|
getMatrixWorld(object: SceneObject): Matrix4;
|
30
39
|
getLocalMatrix(object: SceneObject): Matrix4;
|
31
|
-
|
40
|
+
removeObjectById(objectId: string, remote?: boolean): void;
|
41
|
+
removeObject(object: SceneObject, remote?: boolean): void;
|
32
42
|
private removeRecursive;
|
33
43
|
save(): void;
|
34
44
|
serialize(): string;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"scene-data-service.d.ts","sourceRoot":"","sources":["../../src/scene/scene-data-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;
|
1
|
+
{"version":3,"file":"scene-data-service.d.ts","sourceRoot":"","sources":["../../src/scene/scene-data-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AACvC,OAAO,EAAE,OAAO,EAA6C,MAAM,OAAO,CAAC;AAI3E,qBAAa,gBAAiB,YAAW,iBAAiB;IACxD,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,eAAe,CAAuB;IAC9C,OAAO,CAAC,eAAe,CAAuB;IACvC,YAAY,iCAAyC;;IAW5D,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE;IAK5B,OAAO,CAAC,oBAAoB;IAY5B,sBAAsB,CAAC,QAAQ,EAAE,cAAc;IAI/C,QAAQ,CAAC,QAAQ,EAAE,cAAc;IAIjC,QAAQ,CAAC,QAAQ,EAAE,cAAc;IAIjC,QAAQ,CAAC,QAAQ,EAAE,cAAc;IAIjC,UAAU,IAAI,WAAW,EAAE;IAI3B,mBAAmB,IAAI,WAAW,EAAE;IAapC,SAAS,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,UAAQ;IAM7C;;;;;;OAMG;IACH,YAAY,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,UAAQ;IAWhD,cAAc,CAAC,EAAE,EAAE,MAAM;IAazB,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW,EAAE;IAQ5C;;;;OAIG;IACH,cAAc,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW;IAGvC,OAAO,CAAC,eAAe;IAOvB,YAAY,CAAC,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW;IA8CxD,cAAc,CAAC,MAAM,EAAE,WAAW;IAWlC,cAAc,CAAC,MAAM,EAAE,WAAW;IASlC,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,UAAQ;IAKjD,YAAY,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,UAAQ;IAMhD,OAAO,CAAC,eAAe;IAavB,IAAI;IAKJ,SAAS,IAAI,MAAM;CAIpB;AAGD,wBAAgB,gBAAgB,IAAI,WAAW,CAa9C;AAED,wBAAgB,gBAAgB,IAAI,WAAW,CAS9C;AAED,wBAAgB,sBAAsB,IAAI,WAAW,CA2BpD"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{BehaviorSubject as e}from"rxjs";import{Matrix4 as t,Vector3 as s,Quaternion as i,Euler as n,NoToneMapping as o}from"three";export class SceneDataService{constructor(){this.objects=[],this.callbacks=[],this.removeCallbacks=[],this.objectChange=new e([])}initiate(e){this.objects=e??[],this.objectChange.next(this.objects)}createDefaultObjects(){this.objects.some((e=>"global_fog"===e.type))||this.objects.unshift(createInitialFog());this.objects.some((e=>"sky"===e.type))||this.objects.unshift(createInitialSky())}removeOnUpdateCallback(e){this.callbacks.splice(this.callbacks.indexOf(e),1)}onUpdate(e){this.callbacks.push(e)}onRemove(e){this.removeCallbacks.push(e)}getObjects(){return this.objects}getObjectsRecursive(){const e=[],t=this.objects.slice();for(;t.length>0;){const s=t.pop();e.push(s),null!=s.children&&t.push(...s.children)}return e}addObject(e){this.objects.push(e),this.
|
1
|
+
import{BehaviorSubject as e}from"rxjs";import{Matrix4 as t,Vector3 as s,Quaternion as i,Euler as n,NoToneMapping as o}from"three";export class SceneDataService{constructor(){this.objects=[],this.callbacks=[],this.createCallbacks=[],this.removeCallbacks=[],this.objectChange=new e([])}initiate(e){this.objects=e??[],this.objectChange.next(this.objects)}createDefaultObjects(){this.objects.some((e=>"global_fog"===e.type))||this.objects.unshift(createInitialFog());this.objects.some((e=>"sky"===e.type))||this.objects.unshift(createInitialSky())}removeOnUpdateCallback(e){this.callbacks.splice(this.callbacks.indexOf(e),1)}onCreate(e){this.createCallbacks.push(e)}onUpdate(e){this.callbacks.push(e)}onRemove(e){this.removeCallbacks.push(e)}getObjects(){return this.objects}getObjectsRecursive(){const e=[],t=this.objects.slice();for(;t.length>0;){const s=t.pop();e.push(s),null!=s.children&&t.push(...s.children)}return e}addObject(e,t=!1){this.objects.push(e),this.createCallbacks.forEach((s=>s(e,t))),this.objectChange.next(this.objects)}updateObject(e,t=!1){const s=this.findObjectById(e.id);s?(Object.assign(s,e),this.callbacks.forEach((s=>s(e,t)))):this.addObject(e),this.objectChange.next(this.objects)}findObjectById(e){const t=[...this.objects];for(;t.length>0;){const s=t.pop();if(s.id===e)return s;s.children&&t.push(...s.children)}}findAncestorsById(e){const t=this.findParentById(e);return null==t?[]:[t,...this.findAncestorsById(t.id)]}findParentById(e){return this._findParentById(e,this.objects)}_findParentById(e,t,s=null){return t.some((t=>t.id===e))?s:t.filter((e=>null!=e.children)).map((t=>this._findParentById(e,t.children,t))).find((e=>null!=e))}updateParent(e,o){const r=this.findParentById(e.id);{const c=null!=o?this.getMatrixWorld(o).invert():(new t).identity();null!=r&&c.multiply(this.getMatrixWorld(r));const l=this.getLocalMatrix(e),a=c.multiply(l),h=new s,d=new i,b=new s;a.decompose(h,d,b),e.position=h.toArray(),e.rotation=(new n).setFromQuaternion(d).toArray(),e.scale=b.toArray()}this.removeRecursive(e.id,r?.children??this.objects),null!=r?r.children=r.children.slice():this.objects=this.objects.slice(),null!=o?(o.children??(o.children=[]),o.children.push(e),o.children=o.children.slice()):(this.objects.push(e),this.objects=this.objects.slice()),this.objectChange.next(this.objects),this.callbacks.forEach((t=>t(e,!1)))}getMatrixWorld(e){const t=this.findAncestorsById(e.id).reverse();t.push(e);const s=this.getLocalMatrix(t.shift());for(const e of t){const t=this.getLocalMatrix(e);s.multiply(t)}return s}getLocalMatrix(e){const o=new t,r=(new s).fromArray(e.position),c=(new i).setFromEuler((new n).fromArray(e.rotation)),l=(new s).fromArray(e.scale);return o.compose(r,c,l),o}removeObjectById(e,t=!1){const s=this.findObjectById(e);this.removeObject(s,t)}removeObject(e,t=!1){this.removeRecursive(e.id,this.objects),this.removeCallbacks.forEach((s=>s(e,t))),this.objectChange.next([...this.objects])}removeRecursive(e,t){const s=t.findIndex((t=>t.id===e));if(s>-1)t.splice(s,1);else for(const s of t)null!=s.children&&this.removeRecursive(e,s.children??[])}save(){}serialize(){return JSON.stringify(this.objects)}}export function createInitialFog(){return{id:"auto-global-fog",name:"Global fog",type:"global_fog",fog:{type:"density",color:"#b8f8ff",density:.005,near:100,far:1e3}}}export function createInitialSky(){return{id:"auto-sky",name:"Sky",type:"sky",sky:{materialId:null}}}export function createWorldEnvironment(){return{id:"auto-world-env",name:"World Environment",type:"world_env",worldEnv:{ao:{enabled:!1,blendIntensity:1,radius:.25,distanceExponent:1,thickness:1,distanceFallOff:1,scale:1,samples:16,onlyAO:!1},toneMapping:{mapping:o,exposure:1},environment:{textureId:null,intensity:1}}}}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,5 +1,5 @@
|
|
1
1
|
import { Observable } from 'rxjs';
|
2
|
-
interface
|
2
|
+
export interface StorageEntity {
|
3
3
|
id: string;
|
4
4
|
name: string;
|
5
5
|
fileKey?: string;
|
@@ -10,7 +10,7 @@ type ObjectIndexEntry = {
|
|
10
10
|
name: string;
|
11
11
|
path?: string;
|
12
12
|
};
|
13
|
-
export declare class ObjectStorage<T extends
|
13
|
+
export declare class ObjectStorage<T extends StorageEntity> {
|
14
14
|
private name;
|
15
15
|
private filePathFn?;
|
16
16
|
private path;
|
@@ -45,12 +45,7 @@ export declare class ObjectStorage<T extends Entity> {
|
|
45
45
|
* @returns An array of folders
|
46
46
|
*/
|
47
47
|
watchFolders(): Observable<string[]>;
|
48
|
-
watch(): Observable<
|
49
|
-
event: "add" | "addDir" | "change" | "unlink" | "unlinkDir";
|
50
|
-
object: T;
|
51
|
-
path: string;
|
52
|
-
filename: string;
|
53
|
-
}>;
|
48
|
+
watch(): Observable<StorageWatchEvent<T>>;
|
54
49
|
private reloadSubdirectory;
|
55
50
|
private readFileIfExists;
|
56
51
|
getAll(relativePath?: string): Promise<T[]>;
|
@@ -75,5 +70,11 @@ export declare class ObjectStorage<T extends Entity> {
|
|
75
70
|
private watchDir;
|
76
71
|
}
|
77
72
|
export declare function tokenizeName(name: string): string;
|
73
|
+
export type StorageWatchEvent<T> = {
|
74
|
+
event: "add" | "addDir" | "change" | "unlink" | "unlinkDir";
|
75
|
+
object: T | null;
|
76
|
+
path: string;
|
77
|
+
filename: string;
|
78
|
+
};
|
78
79
|
export {};
|
79
80
|
//# sourceMappingURL=storage.d.ts.map
|