@hology/core 0.0.99 → 0.0.101
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/effects/vfx/trail-renderer.d.ts +11 -4
- package/dist/effects/vfx/trail-renderer.d.ts.map +1 -1
- package/dist/effects/vfx/trail-renderer.js +1 -1
- package/dist/effects/vfx/vfx-actor.d.ts +2 -0
- package/dist/effects/vfx/vfx-actor.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-actor.js +1 -1
- package/dist/effects/vfx/vfx-asset.d.ts +5 -2
- package/dist/effects/vfx/vfx-asset.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-materializer.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/effects/vfx/vfx-param.d.ts +1 -0
- package/dist/effects/vfx/vfx-param.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-param.js +1 -1
- package/dist/effects/vfx/vfx-renderers.d.ts +4 -0
- package/dist/effects/vfx/vfx-renderers.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-renderers.js +1 -1
- package/dist/gameplay/initiate.d.ts.map +1 -1
- package/dist/gameplay/initiate.js +1 -1
- package/dist/gameplay/services/asset-loader.d.ts +3 -0
- package/dist/gameplay/services/asset-loader.d.ts.map +1 -1
- package/dist/gameplay/services/asset-loader.js +1 -1
- package/dist/gameplay/services/physics/physics-system.d.ts +2 -0
- package/dist/gameplay/services/physics/physics-system.d.ts.map +1 -1
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/gameplay/services/world.d.ts +7 -1
- package/dist/gameplay/services/world.d.ts.map +1 -1
- package/dist/gameplay/services/world.js +1 -1
- package/dist/rendering.d.ts +3 -0
- package/dist/rendering.d.ts.map +1 -1
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts.map +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/collision/collision-shape.d.ts +14 -0
- package/dist/scene/collision/collision-shape.d.ts.map +1 -1
- package/dist/scene/collision/collision-shape.js +1 -1
- package/dist/scene/landscape/landscape-manager.js +1 -1
- package/dist/scene/materializer.d.ts +30 -4
- package/dist/scene/materializer.d.ts.map +1 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/objects/prefab.d.ts +7 -4
- package/dist/scene/objects/prefab.d.ts.map +1 -1
- package/dist/scene/objects/prefab.js +1 -1
- package/dist/scene/storage/storage.d.ts.map +1 -1
- package/dist/scene/storage/storage.js +1 -1
- package/dist/shader/index.d.ts +1 -0
- package/dist/shader/index.d.ts.map +1 -1
- package/dist/shader/index.js +1 -1
- package/dist/shader/trail-shader.d.ts +7 -0
- package/dist/shader/trail-shader.d.ts.map +1 -0
- package/dist/shader/trail-shader.js +4 -0
- package/dist/shader-nodes/depth.d.ts +3 -1
- package/dist/shader-nodes/depth.d.ts.map +1 -1
- package/dist/shader-nodes/depth.js +1 -1
- package/dist/shader-nodes/index.d.ts +2 -1
- package/dist/shader-nodes/index.d.ts.map +1 -1
- package/dist/shader-nodes/index.js +1 -1
- package/dist/shader-nodes/scene-sample.d.ts +6 -0
- package/dist/shader-nodes/scene-sample.d.ts.map +1 -0
- package/dist/shader-nodes/scene-sample.js +4 -0
- package/dist/shader-nodes/texture-sequence.d.ts.map +1 -1
- package/dist/shader-nodes/texture-sequence.js +1 -1
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as t,__metadata as e}from"tslib";import*as i from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as c,takeUntil as l}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as y,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as v,Scene as x,Vector3 as b}from"three";import{Service as B}from"typedi";import{AssetMeshInstance as A}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as C,CapsuleCollisionShape as D,ConeCollisionShape as M,ConvexPolyhedronCollisionShape as z,CylinderCollisionShape as S,PhysicalShapeMesh as R,PlaneCollisionShape as T,SphereCollisionShape as E,TrimeshCollisionShape as W}from"../../../index.js";import{LandscapeGroup as F}from"../../../scene/landscape/landscape.js";import{ViewController as j}from"../render.js";import{World as V}from"../world.js";import*as _ from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as P}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as I}from"./abstract-physics-system.js";import{ActorComponent as L,Component as k}from"../../../gameplay/actors/component.js";import{inject as O}from"../../../gameplay/inject.js";export{Component,ActorComponent,attach,Attach}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.hitNormal=new b}}export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));let N=class extends I{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(t,e){super(),this.viewController=t,this.gameWorld=e,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new c,this.beforeStep=new c,this.afterStep=new c,this.shouldRenderDebug=!1,this._raycaster=new v,this._reusableResult=new RayTestResult,this._raytestDiff=new b,this._raytestDirection=new b,this.controlledActors=new Set,this.ready=this.setup()}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.ready}renderDebug(){null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.gameWorld.scene.add(this.debugMesh));const t=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new u(t.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await Z(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;var i,s;null!=e&&(e.parent instanceof x&&($(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&(i=e.quaternion,s=t.rotation(),i.x=s.x,i.y=s.y,i.z=s.z,i.w=s.w),e.updateMatrix(),e.updateWorldMatrix(!1,!1)))})),this.afterStep.next(t)}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((t,e,i)=>{this.collisionEvents.next({handle1:t,handle2:e,started:i}),this.collisionEvents.next({handle1:e,handle2:t,started:i})}))}rayTestFromCamera(t,e,i){this._raycaster.setFromCamera(Y,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(s);return this.rayTest(s,o,e,i)}rayTest(t,e,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),i;J(nt.origin,t),J(nt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(nt,r,!1,void 0,void 0,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?t=>!t.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const e=nt.pointAt(a.timeOfImpact);i._internal=a,$(i.hitNormal,a.normal),$(i.hitPoint,e),i.distance=et.subVectors(i.hitPoint,t).length();const s=this.world.bodies.getAll().find((t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,(t=>t===a.collider))));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){const e=new h(n,t,r,s?.debugColor??255);this.gameWorld.scene.add(e),setTimeout((()=>this.gameWorld.scene.remove(e)),s?.debugLifetime??200)}return i}setGravity(t,e,i){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=i}getGravity(){return U.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())tt(t,(t=>t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof R&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof A&&!1!==t.userData?.src?.collisionDetection)if(t.children[0]&&t.children[0].instanceMatrix)this.createForInstancedMesh(t.children[0],t.collisionShapes);else{const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else t instanceof F?this.addLandscapeGroup(t):(t instanceof p||t instanceof x)&&t.children.forEach((t=>this.addRecursively(t)))}createForInstancedMesh(t,e){const i=new m;for(let s=0;s<t.count;s++){const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*s),o.applyMatrix4(i);this.createStaticBody(o,e)}}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,i,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,o,st);const a=e.computedMovement();return $(it,a),it}setNextKinematicTranslation(t,e){const i=this.actorBodies.get(t.id),s=i.translation();s.x+=e.x,s.y+=e.y,s.z+=e.z,i?.setNextKinematicTranslation(s)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.setAngvel(H,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.setLinvel(H,!0)}getLinearVelocity(t,e=new b){const i=this.actorBodies.get(t.id).linvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}getAngularVelocity(t,e=new b){const i=this.actorBodies.get(t.id).angvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}setLinearDamping(t,e){const i=this.actorBodies.get(t.id);i?.setLinearDamping(e)}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}addLandscapeGroup(t){const e=t.userData.src,s=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new b);if(e.landscape.holes&&e.landscape.holes.some((t=>t.m===n.name&&0!==t.w[0]))){const t=n.geometry.clone(),s=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=s.x,a[t+1]*=s.y,a[t+2]*=s.z;const c=t.index;for(let t=0;t<c.count;t+=3){const e=r.getX(c.getX(t)),i=r.getX(c.getY(t)),s=r.getX(c.getZ(t));(e>.5||i>.5||s>.5)&&(c.setX(t,0),c.setY(t,0),c.setZ(t,0))}const l=i.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);J(e,o),t.setTranslation(e,!1),this.world.createCollider(l,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const c=s.find((t=>t.x===n.x&&t.y==n.y));if(null!=c)for(const e of c.points){if(null==a[e.i%t])continue;const i=t-1-Math.floor(e.i/t);i in a[e.i%t]?a[e.i%t][i]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:i,heightMap:c})}const l=e.landscape.options.density,d=a.flatMap((t=>t.reverse())),h=i.ColliderDesc.heightfield(l,l,new Float32Array(d),new i.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);J(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const i=this.actorBodies.get(t.id);i?.setEnabled(e)}addActor(t,e,s={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const o=t.object;let n;switch(s.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=i.RigidBodyDesc.dynamic(),n.mass=s.mass??1;break;case PhysicsBodyType.kinematic:n=i.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=i.RigidBodyDesc.kinematicVelocityBased();break;default:n=s.isTrigger?i.RigidBodyDesc.kinematicVelocityBased():i.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==s.continousCollisionDetection);for(const t of e)this.addShape(r,t,o);tt(r,(t=>{null!=s.isTrigger&&(t.setSensor(s.isTrigger),t.setActiveCollisionTypes(i.ActiveCollisionTypes.ALL),t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)),null!=s.friction&&t.setFriction(s.friction),null!=s.density&&t.setDensity(s.density),null!=s.mass&&t.setMass(s.mass),null!=s.restitution&&t.setRestitution(s.restitution)})),Q(r,o),!0===s.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,r),this.bodyActors.set(r,t)}applyTorque(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.addTorque(H,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.applyTorqueImpulse(H,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.addForce(H,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);H.x=e.x,H.y=e.y,H.z=e.z,i?.applyImpulse(H,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);J(H,e),null==i?s?.addForce(H,!0):(J(X,i),s?.addForceAtPoint(H,X,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);J(H,e),null==i?s.applyImpulse(H,!0):(J(X,i),s.applyImpulseAtPoint(H,X,!0))}applyRadiusImpulse(t,e,s){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const n=K;$(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);H.x=a.x,H.y=a.y,H.z=a.z,o.applyImpulse(H,!0)}))}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){const e=new Set;t.traverse((t=>{e.add(t.uuid)}));for(const[t,i]of this.staticBodies.entries())!e.has(t.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(i))}removeSceneObject(t){if(t instanceof F){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,i){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((({started:t})=>t===i)),a((({handle1:t,handle2:e,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:i}))),r((({a1:i,a2:s})=>null!=i&&null!=s&&i.id===t.id&&e(i,s))),a((({a2:t})=>t)))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>t.started)),r((({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id})),a((t=>t.handle2)))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>!t.started)),r((({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id})),a((t=>t.handle2)))}onHasContactChanged(t){const e=new Set,i=new o(!1);return this.onBeginContact(t).subscribe((t=>{e.add(t),i.next(e.size>0)})),this.onEndContact(t).subscribe((t=>{e.delete(t),i.next(e.size>0)})),i.pipe(n())}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>i instanceof e),!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>i instanceof e),!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>e.id===i.id),!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,i)=>e.id===i.id),!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e?Q(e,t.object):console.warn("Actor has not been added to physics world",t)}setupWorld(){const t=new i.World({x:0,y:-9.81,z:0});this.world=t}getActorContacts(t,e){const s=this.actorBodies.get(t.id);if(s&&s.numColliders()>0){const o=s.collider(0);let n=o.shape,r=o.translation(),a=o.rotation(),c=e,l=.3;const d=this.world.castShape(r,a,c,n,.1,l,!0,null,null,null,this.actorBodies.get(t.id),(t=>t.shape.type!=i.ShapeType.HeightField));if(null!=d){const t=new b,e=new b,i=new b;return $(t,d.witness2),$(e,d.witness1),$(i,d.normal1),i.negate(),[{ri:t,rj:e,ni:i}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){this.world?.bodies.forEach((t=>this.world.removeRigidBody(t))),this.world?.free(),this.fixedupdateSub?.unsubscribe()}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const i of e){if(null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return Q(n,t),n.userData=t.uuid,n}addShape(t,e,s){const o=s.getWorldScale(ot),n=this.createShape(e,o);null!=e.collisionGroup&&n.setCollisionGroups(e.collisionGroup),n.friction=e.friction??.1,null!=e.restitution&&(n.restitution=e.restitution),null!=e.density&&(n.density=e.density,n.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(n.mass=e.mass,n.massPropsMode=i.MassPropsMode.Mass);const r=e.offset.clone().multiply(o);J(n.translation,r);const a=(new w).setFromEuler(e.rotation);var c,l;e instanceof z&&e.mesh instanceof d.Mesh&&a.multiply(e.mesh.getWorldQuaternion(q)),c=n.rotation,l=a,c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w;return this.world.createCollider(n,t)}createShape(t,e){if(t instanceof C)return i.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof D){return i.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof W){const s=null!=t.geometry.getIndex()?t.geometry:_.mergeVertices(t.geometry),o=extractFloat32Array(s.getAttribute("position"));for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(t instanceof z){let s;t.mesh instanceof d.Mesh?s=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?s=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=extractFloat32Array(s.getAttribute("position"));if(t.mesh instanceof d.Mesh){const e=P(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;n.length;return i.ColliderDesc.convexHull(n)}if(t instanceof E){const s=2*e.x-e.y-e.z;return Math.abs(s)>.01?this.createShape(new z(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):i.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof S?i.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof M?i.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof T?i.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};N=t([B(),e("design:paramtypes",[j,V])],N);export{N as PhysicsSystem};const G=new b,q=new d.Quaternion;function Q(t,e){const s=e.getWorldPosition(G),o=e.getWorldQuaternion(q);t.setTranslation(new i.Vector3(s.x,s.y,s.z),!1),t.setRotation(new i.Quaternion(o.x,o.y,o.z,o.w),!1)}const U=new b,H=new i.Vector3(0,0,0),X=new i.Vector3(0,0,0),K=new b,Y=new d.Vector2,Z=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function J(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function $(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function tt(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const et=new b,it=new b,st=t=>!t.isSensor(),ot=new b;const nt=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));let rt=class extends L{constructor(){super(...arguments),this._active=!0,this.physics=O(N),this.world=O(V)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};rt=t([k()],rt);export function extractFloat32Array(t){const e=t.itemSize,i=t.count,s=new Float32Array(i*e);for(let o=0;o<i;o++)for(let i=0;i<e;i++)s[o*e+i]=t.getComponent(o,i);return s}/*
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import*as s from"@dimforge/rapier3d-compat";import{QueryFilterFlags as i}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 x,Scene as v,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,CollisionShapeSource as z,ConeCollisionShape as M,ConvexPolyhedronCollisionShape as S,CylinderCollisionShape as R,PhysicalShapeMesh as T,PlaneCollisionShape as E,SphereCollisionShape as W,TrimeshCollisionShape as F}from"../../../index.js";import{LandscapeGroup as j}from"../../../scene/landscape/landscape.js";import{ViewController as V}from"../render.js";import{World as _}from"../world.js";import*as P from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as I}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as L}from"./abstract-physics-system.js";import{ActorComponent as k,Component as O}from"../../../gameplay/actors/component.js";import{inject as N}from"../../../gameplay/inject.js";export{Component,ActorComponent,attach,Attach}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new B,this.hitNormal=new B}}export var PhysicsBodyType;!function(e){e[e.dynamic=1]="dynamic",e[e.static=2]="static",e[e.kinematic=4]="kinematic",e[e.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));const G=new B,q=new B,Q=new w;let U=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.shapeCacheBox=new Map,this._raycaster=new x,this._reusableResult=new RayTestResult,this._raytestDiff=new B,this._raytestDirection=new B,this.controlledActors=new Set,this.ready=this.setup()}hasBoxIntersection(e){const t=e.getCenter(G),i=e.getSize(q),o=i.x+1e6*i.y+1e12*i.z;if(!this.shapeCacheBox.has(o)){const e=new s.Cuboid(i.x/2,i.y/2,i.z/2);this.shapeCacheBox.set(o,e)}const n=this.shapeCacheBox.get(o);return null!=this.world.intersectionWithShape(t,Q,n)}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 te(),this.eventQueue=new s.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 s,i;null!=t&&(t.parent instanceof v&&(ie(t.position,e.translation()),(e.isDynamic()||e.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(e)?.id))&&(s=t.quaternion,i=e.rotation(),s.x=i.x,s.y=i.y,s.z=i.z,s.w=i.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,s)=>{this.collisionEvents.next({handle1:e,handle2:t,started:s}),this.collisionEvents.next({handle1:t,handle2:e,started:s})}))}rayTestFromCamera(e,t,s){this._raycaster.setFromCamera(ee,this.viewController.getCamera());const i=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(e).add(i);return this.rayTest(i,o,t,s)}rayTest(e,t,s,i){null==s&&(s=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"),s;se(le.origin,e),se(le.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(le,r,!1,void 0,void 0,void 0,null!=i?.excludeActor?this.actorBodies.get(i.excludeActor.id):void 0,i?.excludeTriggers?e=>!e.isSensor():void 0);if(s.hasHit=null!=a,s.hasHit){const t=le.pointAt(a.timeOfImpact);s._internal=a,ie(s.hitNormal,a.normal),ie(s.hitPoint,t),s.distance=ne.subVectors(s.hitPoint,e).length();const i=this.world.bodies.getAll().find((e=>function(e,t){for(let s=0,i=e.numColliders();s<i;s++){const i=e.collider(s);if(t(i))return i}}(e,(e=>e===a.collider))));s.actor=null!=i?this.bodyActors.get(i):null}if(this.showDebug){const t=new h(n,e,r,i?.debugColor??255);this.gameWorld.scene.add(t),setTimeout((()=>this.gameWorld.scene.remove(t)),i?.debugLifetime??200)}return s}setGravity(e,t,s){this.world.gravity.x=e,this.world.gravity.y=t,this.world.gravity.z=s}getGravity(){return Y.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())oe(e,(e=>e.setActiveEvents(s.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 T&&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 j?this.addLandscapeGroup(e):(e instanceof p||e instanceof v)&&e.children.forEach((e=>this.addRecursively(e)))}createForInstancedMesh(e,t){const s=new m,i=t.map((e=>e.source===z.rendered?e.withOffset(he):e));for(let t=0;t<e.count;t++){const o=new f;o.matrix.identity(),s.fromArray(e.instanceMatrix.array,16*t),o.applyMatrix4(s);this.createStaticBody(o,i)}}getCharacterController(e){return this.world?.createCharacterController(e)}getActorComputedMovement(e,t,s,o=null){const n=this.actorBodies.get(e.id);this.controlledActors.add(e.id);const r=n.collider(0);t.computeColliderMovement(r,s,i.EXCLUDE_SENSORS,o,ae);const a=t.computedMovement();return ie(re,a),re}setNextKinematicTranslation(e,t){const s=this.actorBodies.get(e.id),i=s.translation();i.x+=t.x,i.y+=t.y,i.z+=t.z,s?.setNextKinematicTranslation(i)}setAngularVelocity(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.setAngvel(Z,!0)}setLinearVelocity(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.setLinvel(Z,!0)}getLinearVelocity(e,t=new B){const s=this.actorBodies.get(e.id).linvel();return t.x=s.x,t.y=s.y,t.z=s.z,t}getAngularVelocity(e,t=new B){const s=this.actorBodies.get(e.id).angvel();return t.x=s.x,t.y=s.y,t.z=s.z,t}setLinearDamping(e,t){const s=this.actorBodies.get(e.id);s?.setLinearDamping(t)}setAngularDamping(e,t){const s=this.actorBodies.get(e.id);s?.setAngularDamping(t)}addLandscapeGroup(e){const t=e.userData.src,i=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(),i=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]*=i.x,a[e+1]*=i.y,a[e+2]*=i.z;const c=e.index;for(let e=0;e<c.count;e+=3){const t=r.getX(c.getX(e)),s=r.getX(c.getY(e)),i=r.getX(c.getZ(e));(t>.5||s>.5||i>.5)&&(c.setX(e,0),c.setY(e,0),c.setZ(e,0))}const l=s.ColliderDesc.trimesh(a,new Uint32Array(e.getIndex().array));if(!1!==t.collisionDetection){const e=this.world.createRigidBody(s.RigidBodyDesc.fixed()),t=new s.Vector3(0,0,0);se(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=i.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 s=e-1-Math.floor(t.i/e);s in a[t.i%e]?a[t.i%e][s]=t.y/r:console.warn("wrong index",{points:a,point:t,i:t.i%e,k:s,heightMap:c})}const l=t.landscape.options.density,d=a.flatMap((e=>e.reverse())),h=s.ColliderDesc.heightfield(l,l,new Float32Array(d),new s.Vector3(r,r,r));if(!1!==t.collisionDetection){const e=this.world.createRigidBody(s.RigidBodyDesc.fixed()),t=new s.Vector3(0,0,0);se(t,o),e.setTranslation(t,!1),this.world.createCollider(h,e),this.staticBodies.set(n,e)}}}setEnabled(e,t){const s=this.actorBodies.get(e.id);s?.setEnabled(t)}addActor(e,t,i={}){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(i.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=s.RigidBodyDesc.dynamic(),n.mass=i.mass??1;break;case PhysicsBodyType.kinematic:n=s.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=s.RigidBodyDesc.kinematicVelocityBased();break;default:n=i.isTrigger?s.RigidBodyDesc.kinematicVelocityBased():s.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==i.continousCollisionDetection);for(const e of t)this.addShape(r,e,o);oe(r,(e=>{null!=i.isTrigger&&(e.setSensor(i.isTrigger),e.setActiveCollisionTypes(s.ActiveCollisionTypes.ALL),e.setActiveEvents(s.ActiveEvents.COLLISION_EVENTS)),null!=i.friction&&e.setFriction(i.friction),null!=i.density&&e.setDensity(i.density),null!=i.mass&&e.setMass(i.mass),null!=i.restitution&&e.setRestitution(i.restitution)})),K(r,o),!0===i.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(e.id,r),this.bodyActors.set(r,e)}applyTorque(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.addTorque(Z,!0)}applyTorqueImpulse(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.applyTorqueImpulse(Z,!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 s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.addForce(Z,!0)}applyImpulse(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.applyImpulse(Z,!0)}applyLocalForce(e,t,s){const i=this.actorBodies.get(e.id);se(Z,t),null==s?i?.addForce(Z,!0):(se(J,s),i?.addForceAtPoint(Z,J,!0))}applyLocalImpulse(e,t,s){const i=this.actorBodies.get(e.id);se(Z,t),null==s?i.applyImpulse(Z,!0):(se(J,s),i.applyImpulseAtPoint(Z,J,!0))}applyRadiusImpulse(e,t,i){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==s.RigidBodyType.Dynamic)return;const n=$;ie(n,o.translation());const r=n.clone().sub(e);if(r.length()>t)return;const a=r.clone().normalize().multiplyScalar(i);Z.x=a.x,Z.y=a.y,Z.z=a.z,o.applyImpulse(Z,!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,s]of this.staticBodies.entries())!t.has(e.uuid)&&this.world.getRigidBody(s.handle)&&(this.staticBodies.delete(e),this.world.removeRigidBody(s))}removeSceneObject(e){if(e instanceof j){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,s){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),r((({started:e})=>e===s)),a((({handle1:e,handle2:t,started:s})=>({a1:this.bodyActors.get(this.world.getCollider(e)?.parent()),a2:this.bodyActors.get(this.world.getCollider(t)?.parent()),started:s}))),r((({a1:s,a2:i})=>null!=s&&null!=i&&s.id===e.id&&t(s,i))),a((({a2:e})=>e)))}onBeginContact(e){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),r((e=>e.started)),r((({handle1:t})=>{const s=this.bodyActors.get(this.world.getCollider(t)?.parent());return null!=s&&s.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 s=this.bodyActors.get(this.world.getCollider(t)?.parent());return null!=s&&s.id===e.id})),a((e=>e.handle2)))}onHasContactChanged(e){const t=new Set,s=new o(!1);return this.onBeginContact(e).subscribe((e=>{t.add(e),s.next(t.size>0)})),this.onEndContact(e).subscribe((e=>{t.delete(e),s.next(t.size>0)})),s.pipe(n())}onBeginOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,s)=>s instanceof t),!0)}onEndOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,s)=>s instanceof t),!1)}onBeginOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,s)=>t.id===s.id),!0)}onEndOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,s)=>t.id===s.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?K(t,e.object):console.warn("Actor has not been added to physics world",e)}setupWorld(){const e=new s.World({x:0,y:-9.81,z:0});this.world=e}getActorContacts(e,t){const i=this.actorBodies.get(e.id);if(i&&i.numColliders()>0){const o=i.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!=s.ShapeType.HeightField));if(null!=d){const e=new B,t=new B,s=new B;return ie(e,d.witness2),ie(t,d.witness1),ie(s,d.normal1),s.negate(),[{ri:e,rj:t,ni:s}]}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,i){const o=i?.type===PhysicsBodyType.dynamic?s.RigidBodyDesc.dynamic():s.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const s of t){if(null==s){console.warn("Collision shape is missing for object",e);continue}const o=this.addShape(n,s,e);null!=i?.friction&&o.setFriction(i.friction),null!=i?.density&&o.setDensity(i.density),null!=i?.mass&&o.setMass(i.mass/t.length),null!=i?.restitution&&o.setRestitution(i.restitution)}return K(n,e),n.userData=e.uuid,n}addShape(e,t,i){const o=i.getWorldScale(ce),n=this.createShape(t,o);null!=t.collisionGroup&&n.setCollisionGroups(t.collisionGroup),n.friction=t.friction??.1,null!=t.restitution&&(n.restitution=t.restitution),null!=t.density&&(n.density=t.density,n.massPropsMode=s.MassPropsMode.Density),null!=t.mass&&(n.mass=t.mass,n.massPropsMode=s.MassPropsMode.Mass);const r=t.offset.clone().multiply(o);se(n.translation,r);const a=(new w).setFromEuler(t.rotation);var c,l;t instanceof S&&t.mesh instanceof d.Mesh&&a.multiply(t.mesh.getWorldQuaternion(X)),c=n.rotation,l=a,c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w;return this.world.createCollider(n,e)}createShape(e,t){if(e instanceof C)return s.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 s.ColliderDesc.capsule(e.length/2*t.y,e.radius*Math.max(t.z,t.x))}if(e instanceof F){const i=null!=e.geometry.getIndex()?e.geometry:P.mergeVertices(e.geometry),o=extractFloat32Array(i.getAttribute("position"));for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z;return s.ColliderDesc.trimesh(o,new Uint32Array(i.getIndex().array))}if(e instanceof S){let i;e.mesh instanceof d.Mesh?i=e.mesh.geometry:e.mesh instanceof d.BufferGeometry?i=e.mesh:console.log("Unknownd shape",{shapeInfo:e});const o=extractFloat32Array(i.getAttribute("position"));if(e.mesh instanceof d.Mesh){const t=I(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;n.length;return s.ColliderDesc.convexHull(n)}if(e instanceof W){const i=2*t.x-t.y-t.z;return Math.abs(i)>.01?this.createShape(new S(new d.SphereGeometry(e.radius).scale(t.x,t.y,t.z)),new B(1,1,1)):s.ColliderDesc.ball(e.radius*Math.max(t.x,t.y,t.z))}return e instanceof R?s.ColliderDesc.cylinder(e.height/2*t.y,e.radiusTop*Math.max(t.z,t.x)):e instanceof M?s.ColliderDesc.cone(e.height*t.y,e.radiusBottom/2*Math.max(t.z,t.x)):e instanceof E?s.ColliderDesc.cuboid(e.width/2*t.x,e.height/2*t.y,.001):(console.error("Unsupported shape",e),s.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new s.CharacterCollision}};U=e([b(),t("design:paramtypes",[V,_])],U);export{U as PhysicsSystem};const H=new B,X=new d.Quaternion;function K(e,t){const i=t.getWorldPosition(H),o=t.getWorldQuaternion(X);e.setTranslation(new s.Vector3(i.x,i.y,i.z),!1),e.setRotation(new s.Quaternion(o.x,o.y,o.z,o.w),!1)}const Y=new B,Z=new s.Vector3(0,0,0),J=new s.Vector3(0,0,0),$=new B,ee=new d.Vector2,te=async()=>{let e=await import("@dimforge/rapier3d-compat");return await e.init(),e};function se(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function ie(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function oe(e,t){for(let s=0,i=e.numColliders();s<i;s++){t(e.collider(s))}}const ne=new B,re=new B,ae=e=>!e.isSensor(),ce=new B;const le=new s.Ray(new s.Vector3(0,0,0),new s.Vector3(0,1,0));let de=class extends k{constructor(){super(...arguments),this._active=!0,this.physics=N(U),this.world=N(_)}set active(e){this._active=e,e?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,e)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,e))}get active(){return this._active}};de=e([O()],de);export function extractFloat32Array(e){const t=e.itemSize,s=e.count,i=new Float32Array(s*t);for(let o=0;o<s;o++)for(let s=0;s<t;s++)i[o*t+s]=e.getComponent(o,s);return i}const he=new B;/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -4,6 +4,9 @@ import { ActorFactory } from '../actors/factory.js';
|
|
4
4
|
import { Euler, Scene, Vector3 } from 'three';
|
5
5
|
import { Observable } from 'rxjs';
|
6
6
|
import { RenderingView } from "../../rendering.js";
|
7
|
+
import { Prefab } from "../../scene/objects/prefab.js";
|
8
|
+
import { SceneMaterializer } from "../../scene/materializer.js";
|
9
|
+
import { PrefabInstance } from '../../scene/objects/prefab';
|
7
10
|
declare class DirectionalLightController {
|
8
11
|
private view;
|
9
12
|
constructor(view: RenderingView);
|
@@ -24,17 +27,20 @@ declare class DirectionalLightController {
|
|
24
27
|
export declare class World {
|
25
28
|
private actorFactory;
|
26
29
|
private view;
|
30
|
+
private materializer;
|
27
31
|
readonly actors: BaseActor[];
|
28
32
|
readonly actorAdded: Observable<BaseActor>;
|
29
33
|
readonly actorRemoved: Observable<BaseActor>;
|
30
34
|
scene: Scene;
|
31
35
|
readonly directionalLight: DirectionalLightController;
|
32
|
-
constructor(actorFactory: ActorFactory, view: RenderingView);
|
36
|
+
constructor(actorFactory: ActorFactory, view: RenderingView, materializer: SceneMaterializer);
|
33
37
|
spawnActor<T extends BaseActor>(type: Constructable<T>, position?: Vector3, rotation?: Euler): Promise<T>;
|
34
38
|
addActor(actor: BaseActor, position?: Vector3, rotation?: Euler): void;
|
35
39
|
removeActor(actor: BaseActor): void;
|
36
40
|
findActorByType<T extends BaseActor>(type: Constructable<T>, name?: string): T;
|
37
41
|
findActorsByType<T extends BaseActor>(type: Constructable<T>, name?: string): T[];
|
42
|
+
spawnPrefab(prefab: Prefab, position?: Vector3, rotation?: Euler): Promise<PrefabInstance>;
|
43
|
+
removePrefab(instance: PrefabInstance): void;
|
38
44
|
}
|
39
45
|
export {};
|
40
46
|
//# sourceMappingURL=world.d.ts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"world.d.ts","sourceRoot":"","sources":["../../../src/gameplay/services/world.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,aAAa,EAAE,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAE9C,OAAO,EAAE,UAAU,EAAW,MAAM,MAAM,CAAA;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;
|
1
|
+
{"version":3,"file":"world.d.ts","sourceRoot":"","sources":["../../../src/gameplay/services/world.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,aAAa,EAAE,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAE9C,OAAO,EAAE,UAAU,EAAW,MAAM,MAAM,CAAA;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,EAAC,cAAc,EAAC,MAAM,4BAA4B,CAAC;AAI1D,cAAM,0BAA0B;IAClB,OAAO,CAAC,IAAI;gBAAJ,IAAI,EAAE,aAAa;IAIvC;;;OAGG;IACH,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED,IAAI,SAAS,CAAC,KAAK,EAAE,MAAM,EAG1B;IAED,IAAI,SAAS,IAAI,MAAM,CAEtB;IAED;;;;OAIG;IACH,IAAI,QAAQ,IAAI,OAAO,CAKtB;CAEF;AAED,qBACa,KAAK;IAOJ,OAAO,CAAC,YAAY;IAAgB,OAAO,CAAC,IAAI;IAAiB,OAAO,CAAC,YAAY;IANjG,SAAgB,MAAM,EAAE,SAAS,EAAE,CAAK;IACxC,SAAgB,UAAU,EAAE,UAAU,CAAC,SAAS,CAAC,CAAgB;IACjE,SAAgB,YAAY,EAAE,UAAU,CAAC,SAAS,CAAC,CAAgB;IAC5D,KAAK,EAAE,KAAK,CAAA;IACnB,SAAgB,gBAAgB,6BAA4C;gBAExD,YAAY,EAAE,YAAY,EAAU,IAAI,EAAE,aAAa,EAAU,YAAY,EAAE,iBAAiB;IAIvG,UAAU,CAAC,CAAC,SAAS,SAAS,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC;IAM/G,QAAQ,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,KAAK;IAa/D,WAAW,CAAC,KAAK,EAAE,SAAS;IAS5B,eAAe,CAAC,CAAC,SAAS,SAAS,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,CAAC;IAI9E,gBAAgB,CAAC,CAAC,SAAS,SAAS,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,CAAC,EAAE;IAI3E,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,KAAK;IA4BtE,YAAY,CAAC,QAAQ,EAAE,cAAc;CAI7C"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as t,__metadata as
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import{Service as i}from"typedi";import{ActorFactory as o}from"../actors/factory.js";import{Vector3 as r}from"three";import{ActorComponent as s}from"../../gameplay/actors/component.js";import{Subject as c}from"rxjs";import{RenderingView as n}from"../../rendering.js";import{SceneMaterializer as a}from"../../scene/materializer.js";import{randomUUID as h}from"../../utils/uuid";import{PrefabInstance as m}from"../../scene/objects/prefab";const l=new r;class d{constructor(t){this.view=t}get direction(){return this.view.csm.lightDirection}set intensity(t){this.view.csm.lightIntensity=t,this.view.csm.lights.forEach((t=>t.intensity=this.view.csm.lightIntensity))}get intensity(){return this.view.csm.lightIntensity}get position(){return 0==this.view.csm.lights.length?l:this.view.csm.lights[0].position}}let p=class{constructor(t,e,i){this.actorFactory=t,this.view=e,this.materializer=i,this.actors=[],this.actorAdded=new c,this.actorRemoved=new c,this.directionalLight=new d(this.view),console.log("Create world",t,i)}async spawnActor(t,e,i){const o=await this.actorFactory.create(t,e,i);return this.addActor(o,e,i),o}addActor(t,e,i){e&&t.object.position.copy(e),i&&t.object.rotation.copy(i),this.scene.add(t.object),this.actors.push(t),f(t,(t=>t.onBeginPlay())),this.actorAdded.next(t)}removeActor(t){f(t,(t=>t.onEndPlay()));const e=this.actors.indexOf(t);e>=0&&this.actors.splice(e,1),this.scene.remove(t.object),t.disposed.next(!0),this.actorRemoved.next(t)}findActorByType(t,e){return this.actors.find((i=>i instanceof t&&(null==e||i.object.name==e)))}findActorsByType(t,e){return this.actors.filter((i=>i instanceof t&&(null==e||i.object.name==e)))}async spawnPrefab(t,e,i){const o=new m,{object:r,actors:s}=await this.materializer.createFromPrefabAsset(t.asset,{sceneObjectChain:["r-"+h()]});return o.object=r,o.actors=s,this.scene.add(r),null!=e&&r.position.copy(e),null!=i&&r.rotation.copy(i),s.forEach((t=>{this.addActor(t)})),o}removePrefab(t){t.actors.forEach((t=>this.removeActor(t))),t.object?.removeFromParent()}};p=t([i(),e("design:paramtypes",[o,n,a])],p);export{p as World};function f(t,e){return e(t),Object.entries(t).filter((([t,e])=>e instanceof s)).forEach((([t,i])=>{f(i,e)}))}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
package/dist/rendering.d.ts
CHANGED
@@ -28,6 +28,7 @@ export declare class RenderingView {
|
|
28
28
|
paused: boolean;
|
29
29
|
aoMaskDepthRenderTarget: WebGLRenderTarget;
|
30
30
|
depthRenderTarget: WebGLRenderTarget;
|
31
|
+
sceneColorRenderTarget: WebGLRenderTarget;
|
31
32
|
csm: CSM | null;
|
32
33
|
fpsCap: number | null;
|
33
34
|
aoPass: GTAOPass;
|
@@ -49,6 +50,7 @@ export declare class RenderingView {
|
|
49
50
|
private static createDepthRenderTarget;
|
50
51
|
/** */
|
51
52
|
private static createAOMaskDepthRenderTarget;
|
53
|
+
private static createSceneColorRenderTarget;
|
52
54
|
private setupEventListeners;
|
53
55
|
stop(): void;
|
54
56
|
private onLoopCallbacks;
|
@@ -79,6 +81,7 @@ export declare class RenderingView {
|
|
79
81
|
private darkenNonBloomed;
|
80
82
|
private restoreMaterial;
|
81
83
|
private initDepthUniform;
|
84
|
+
private initResolutionUniform;
|
82
85
|
}
|
83
86
|
export declare function setRenderingPaused(value: boolean): void;
|
84
87
|
/**
|
package/dist/rendering.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"rendering.d.ts","sourceRoot":"","sources":["../src/rendering.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EACL,MAAM,EAKN,QAAQ,EAIR,aAAa,EACb,iBAAiB,EAClB,MAAM,OAAO,CAAC;AAOf,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAC;AAGpD,OAAO,EAAE,QAAQ,EAAE,MAAM,+CAA+C,CAAC;
|
1
|
+
{"version":3,"file":"rendering.d.ts","sourceRoot":"","sources":["../src/rendering.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EACL,MAAM,EAKN,QAAQ,EAIR,aAAa,EACb,iBAAiB,EAClB,MAAM,OAAO,CAAC;AAOf,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAC;AAGpD,OAAO,EAAE,QAAQ,EAAE,MAAM,+CAA+C,CAAC;AA8CzE,MAAM,MAAM,oBAAoB,GAAG;IACjC,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE;QACR,UAAU,CAAC,EAAE,OAAO,CAAA;KACrB,CAAA;IACD,EAAE,CAAC,EAAE;QACH,OAAO,EAAE,OAAO,CAAA;KACjB,CAAA;CACF,CAAA;AAED,qBACa,aAAa;IAoHf,SAAS,EAAE,WAAW;aACb,OAAO,EAAE,oBAAoB;IApHxC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAA;IACpB,aAAa,UAAO;IACpB,QAAQ,EAAE,aAAa,CAAA;IACvB,aAAa,EAAE,aAAa,CAAA;IACnC,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,WAAW,CAAa;IACzB,KAAK,EAAE,KAAK,CAAC,KAAK,CAAA;IAClB,OAAO,UAAO;IACd,MAAM,UAAQ;IACd,uBAAuB,EAAE,iBAAiB,CAAA;IAC1C,iBAAiB,EAAE,iBAAiB,CAAA;IACpC,sBAAsB,EAAE,iBAAiB,CAAA;IACzC,GAAG,EAAE,GAAG,GAAG,IAAI,CAAA;IACf,MAAM,EAAE,MAAM,GAAG,IAAI,CAAO;IAE5B,MAAM,EAAE,QAAQ,CAAA;IACvB,OAAO,CAAC,SAAS,CAAiB;IAG3B,SAAS,CAAC,KAAK,EAAE,OAAO;IAsBxB,eAAe,SAAqB;IAEpC,aAAa,SAA0C;IAE9D,OAAO,CAAC,QAAQ,CAKf;IAED,OAAO,CAAC,kBAAkB,CAAA;IAC1B,OAAO,CAAC,oBAAoB,CAAA;IAC5B,OAAO,CAAC,YAAY;IAmDpB,OAAO,CAAC,gBAAgB,CAEvB;IAED,OAAO,CAAC,gCAAgC,CAAQ;IAEhD,OAAO,CAAC,aAAa,CAAe;gBAG3B,SAAS,EAAE,WAAW,EACb,OAAO,GAAE,oBAAyB;IAyUpD,OAAO,CAAC,aAAa;IASd,SAAS,CAAC,MAAM,EAAE,MAAM;IAiDxB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,EAAE;IAkBzC,OAAO,CAAC,MAAM,CAAC,uBAAuB;IAyBtC,OAAO;IACP,OAAO,CAAC,MAAM,CAAC,6BAA6B;IAuB5C,OAAO,CAAC,MAAM,CAAC,4BAA4B;IAuB3C,OAAO,CAAC,mBAAmB;IAMpB,IAAI;IAeX,OAAO,CAAC,eAAe,CAAK;IACrB,MAAM,CAAC,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,GAAG;IAG1C,YAAY,CAAC,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,GAAG;IAKvD,OAAO,CAAC,KAAK,CAST;IACJ,OAAO,CAAC,UAAU,CAAO;IAEzB,IAAI,SAAS,CAAC,KAAK,EAAE,OAAO,EAO3B;IACD,IAAI,SAAS,IARQ,OAAO,CAU3B;IAED,OAAO,CAAC,WAAW;IAsBZ,IAAI,CAAC,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,GAAG,EAAE,SAAS,UAAQ;IAgSlE,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,UAAU,CAA8B;IAChD,OAAO,CAAC,YAAY,CAAM;IAC1B,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,eAAe,CAAI;IAE3B,OAAO,CAAC,cAAc,CAAyB;IAE/C,OAAO,CAAC,aAAa;IAyBd,gBAAgB,CAAC,MAAM,EAAE,MAAM;IAI/B,mBAAmB;IAInB,mBAAmB,CAAC,MAAM,EAAE,MAAM;IAIzC,OAAO,CAAC,cAAc,CAAc;IACpC,OAAO,CAAC,QAAQ,CAAQ;IACjB,MAAM,CAAC,SAAS,CAAC,EAAE,MAAM;IAmChC,OAAO,CAAC,oBAAoB,CAAK;IACjC,OAAO,CAAC,WAAW,CAAiB;IAEpC,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,gBAAgB;IAkBxB,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,gBAAgB;IAkBxB,OAAO,CAAC,qBAAqB;CAe9B;AAcD,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,QAIhD;AAuGD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,GAAG,OAAO,CAIzF"}
|
package/dist/rendering.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
var e;import{__decorate as t,__metadata as i}from"tslib";import*as s from"three";import{Color as r,Material as n,Matrix4 as a,Mesh as o,PerspectiveCamera as h,ShaderChunk as l,ShaderMaterial as d}from"three";import{EffectComposer as c,FXAAShader as m,GammaCorrectionShader as p,RenderPass as u,ShaderPass as f,UnrealBloomPass as g,VRButton as v}from"three-stdlib";import{CSMShader as x,CSMUtil as w}from"./csm.js";import{NodeShaderMaterial as b}from"three-shader-graph";import{Reflector as T}from"three-stdlib";import{OutputPass as y}from"three/examples/jsm/Addons.js";import{CSM as M}from"three/examples/jsm/csm/CSM.js";import C from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as R}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as P}from"typedi";import{depthUniformName as S,farUniformName as D,nearUniformName as F,resolutionUniformName as W,supportsDepthTextureExtension as H}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as A}from"./shader-nodes/time.js";import{DepthPass as L}from"./utils/three/depth-pass.js";import{GPUStatsPanel as k}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as O}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as j}from"./utils/three/traverse.js";(new s.Layers).set(9);const E=new s.MeshBasicMaterial({color:"black"}),B=new s.MeshDepthMaterial;B.depthPacking=s.RGBADepthPacking,B.blending=s.NoBlending,B.side=s.DoubleSide;const U=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let z=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||0!==this.container.clientWidth&&0!==this.container.clientHeight&&(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof h&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.bloomComposer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.aoMaskDepthRenderTarget.dispose(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.aoPass.blendMaterial.uniforms.tDepth.value=this.aoMaskDepthRenderTarget.depthTexture,this.depthRenderTarget.dispose(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container))}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=U?.5:1,this.maxPixelRatio=U?1:window.devicePixelRatio,this.onResize=()=>{this.resizeRender(),this.paused||this.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=new C,this._showStats=!0,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],null!=i.maxPixelRatio&&(this.maxPixelRatio=i.maxPixelRatio),window.renderer=this.renderer=new s.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new s.Scene,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(v.createButton(this.renderer)),this.composer=new c(this.renderer);var n=(t.clientWidth||1)/(t.clientHeight||1);const a=new s.PerspectiveCamera(45,n,.5,800);a.layers.enable(19),this.setCamera(a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=s.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=i.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=s.SRGBColorSpace,this.renderer.toneMapping=s.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,w.renderingView=this,w.patchThreeAdd(),this.isDepthTextureExtensionSupported=H(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container);const o=new u(this.scene,this.camera);this.composer.addPass(o);const h=new g(new s.Vector2(t.clientWidth,t.clientHeight),1.5,.4,.85);h.threshold=1,h.strength=.9,h.radius=.5,this.bloomPass=h;const l=new R(this.scene,this.camera,t.clientWidth,t.clientWidth);l.blendMaterial.uniforms.tDepth={value:this.aoMaskDepthRenderTarget.depthTexture},l.blendMaterial.uniforms.tAODepth={value:l.depthTexture},l.blendMaterial.fragmentShader="\n uniform float intensity;\n uniform sampler2D tDiffuse;\n uniform sampler2D tDepth;\n uniform sampler2D tAODepth;\n varying vec2 vUv;\n\n void main() {\n vec4 texel = texture2D( tDiffuse, vUv );\n float d = textureLod(tDepth, vUv.xy, 0.0).x;\n float d2 = textureLod(tAODepth, vUv.xy, 0.0).x;\n\n float depth = 2.0 * 1.0 * 500.0 / (500.0 + 1.0 - (2.0 * d - 1.0) * (500.0 - 1.0));\n gl_FragColor = vec4(mix(vec3(1.), texel.rgb, d2 > d ? 0.0 : intensity), texel.a);\n }\n ",l.output=R.OUTPUT.Default,l.enabled=!1,this.aoPass=l,!1!==this.options.ao?.enabled&&this.composer.addPass(l),this.renderer.info.autoReset=!1;const d=new c(this.renderer);d.renderToScreen=!1,d.addPass(o),d.addPass(h),this.bloomComposer=d,U||(d.renderTarget2.texture.type=s.HalfFloatType,this.composer.renderTarget1.texture.type=s.HalfFloatType);const x=new f(new s.ShaderMaterial({uniforms:{baseTexture:{value:null},bloomTexture:{value:d.renderTarget2.texture}},vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }",fragmentShader:"\n uniform sampler2D baseTexture;\n uniform sampler2D bloomTexture;\n varying vec2 vUv;\n void main() {\n gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n }",defines:{}}),"baseTexture");if(x.needsSwap=!0,this.composer.addPass(x),this.outlinePass=new O(new s.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new f(m);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e)}new f(p).clear=!1,this.fixStatsStyle();const b=new y;this.composer.addPass(b)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setCamera(e){this.camera=e,this.composer.passes.forEach((t=>{t instanceof u?t.camera=e:t instanceof O?t.renderCamera=e:(t instanceof L||t instanceof R)&&(t.camera=e)})),null==this.csm?(this.csm=new M({maxFar:500,lightFar:250,lightMargin:20,cascades:4,shadowMapSize:2048,lightDirection:new s.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene}),l.lights_fragment_begin=x.lights_fragment_begin):(this.csm.camera=this.camera,this.camera instanceof h&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t){var i=!!e.extensions.get("WEBGL_depth_texture");const r=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio());return r.texture.minFilter=s.NearestFilter,r.texture.magFilter=s.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===i&&(r.depthTexture=new s.DepthTexture(128,128),r.depthTexture.type=s.UnsignedShortType,r.depthTexture.minFilter=s.NearestFilter,r.depthTexture.magFilter=s.NearestFilter),r}static createAOMaskDepthRenderTarget(e,t){const i=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:s.HalfFloatType});return i.texture.minFilter=s.NearestFilter,i.texture.magFilter=s.NearestFilter,i.texture.generateMipmaps=!1,i.stencilBuffer=!1,i.depthTexture=new s.DepthTexture(128,128),i.depthTexture.type=s.UnsignedInt248Type,i.depthTexture.minFilter=s.NearestFilter,i.depthTexture.magFilter=s.NearestFilter,i}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){null!=this.scene.environment&&e instanceof b&&(null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1}),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment)}loop(e,t=!1){const i=this.stats,r=i.addPanel(new C.Panel("Calls","#83f","#002")),h=i.addPanel(new C.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new k(this.renderer.getContext()),i.addPanel(l)),this.showStats=t;let d=10,c=1e3;const m=()=>{const e=this.renderer.info.render.calls;e>d&&(d=e,setTimeout((()=>d=10),5e3)),r.update(e,d);const t=this.renderer.info.render.triangles;t>c&&(c=t,setTimeout((()=>c=1e3),5e3)),h.update(t,c)};performance.now();s.Ray.prototype.intersectTriangle;const p=[],u=[];let f=0;const g=new a,v=new a,x=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return void setTimeout((()=>x(t)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,i.begin();let a=(t*=.001)-f;if(f=t,g.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(V),t-=V;e(t)}else e(a);this.onLoopCallbacks.forEach((e=>e(a))),this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),v.equals(g)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender(),p.length=0,u.length=0;const h=_;if(this.camera.updateMatrixWorld(),N.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(N),this.scene.traverseVisible((e=>{if(null!=this.scene.environment&&(e instanceof o||e instanceof s.Sprite)&&function(e,t){if(Array.isArray(e.material))for(const i of e.material)t(i);else null!=e.material&&t(e.material)}(e,(e=>this.applyEnvMap(e))),(e instanceof o||e instanceof s.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[S])&&isObjectInFrustum(e,h)?(e.visible=!1,p.push(e),this.initDepthUniform(e.material),e.renderOrder=100):e instanceof T?(e.visible=!1,u.push(e)):(e instanceof o||e instanceof s.Sprite)&&function(e){if(e.material instanceof n)return e.material.transparent||e.material.alphaTest>0;if(Array.isArray(e.material))for(const t of e.material)if(t.transparent||t.alphaTest>0)return!0}(e)&&(e.visible=!1,e.layers.enable(5),u.push(e)),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[A])e.material.uniforms[A].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const i of e.material)i.uniforms&&null!=i.uniforms[A]&&(i.uniforms[A].value=t)})),p.length>0){if(this.scene.overrideMaterial=B,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}if(p.forEach((e=>e.visible=!0)),u.forEach((e=>e.visible=!0)),this.aoPass.enabled){if(this.scene.overrideMaterial=B,this.camera.layers.set(5),this.renderer.setRenderTarget(this.aoMaskDepthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.camera.layers.enableAll(),this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}try{!this.paused&&this.running&&(this.showStats&&l?.startQuery(),this.render(a),this.showStats&&l?.endQuery(),this.showStats&&m(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}i.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(x)}),1e3/this.fpsCap):requestAnimationFrame(x))};!0===this.options.enableXR?this.renderer.setAnimationLoop(x):requestAnimationFrame(x)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let s=0;s<e.length;s++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*s+this.insetMargin*s,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[s])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;const t=this.hasBloom();if(t||this.hadBloom){const e=this.scene.fog;this.scene.fog=null;const t=this.renderer.getClearColor(this.prevClearColor);this.renderer.setClearColor(0),this.scene.traverseVisible((e=>this.darkenNonBloomed(e))),this.bloomComposer.render(),this.scene.traverse((e=>this.restoreMaterial(e))),this.bloomHidden.forEach((e=>e.visible=!0)),this.bloomHidden.length=0,this.renderer.setClearColor(t),this.scene.fog=e}this.hadBloom=t,this.composer.render(e)}hasBloom(){return null!=j(this.scene,(e=>e instanceof o&&!0===e.material?.userData?.hasBloom))}darkenNonBloomed(e){(e instanceof o||e instanceof s.Sprite||e instanceof s.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)?(this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=E:e.visible=!1):"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof d&&(e.uniforms[S].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[W]&&e.uniforms[W].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof h&&(null!=e.uniforms[F]&&(e.uniforms[F].value=this.camera.near),null!=e.uniforms[D]&&(e.uniforms[D].value=this.camera.far)))}};z=e=t([P(),i("design:paramtypes",[HTMLElement,Object])],z);export{z as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const V=.05;R.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse((function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls)&&(e.visible=!1),null!=e.material){let t=!1;if(Array.isArray(e.material)){for(const i of e.material)if(null!=i.alphaTest&&i.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0&&(t=!0);t&&(e.visible=!1)}}))};const _=new s.Frustum,I=new s.Box3,N=new s.Matrix4;export function isObjectInFrustum(e,t){const i=I.setFromObject(e);return t.intersectsBox(i)}/*
|
1
|
+
var e;import{__decorate as t,__metadata as i}from"tslib";import*as r from"three";import{Color as s,Material as n,Matrix4 as a,Mesh as o,PerspectiveCamera as h,ShaderChunk as l,ShaderMaterial as d}from"three";import{EffectComposer as c,FXAAShader as m,GammaCorrectionShader as u,RenderPass as p,ShaderPass as f,UnrealBloomPass as g,VRButton as v}from"three-stdlib";import{CSMShader as x,CSMUtil as w}from"./csm.js";import{NodeShaderMaterial as b}from"three-shader-graph";import{Reflector as T}from"three-stdlib";import{OutputPass as y}from"three/examples/jsm/Addons.js";import{CSM as R}from"three/examples/jsm/csm/CSM.js";import C from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as M}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as S}from"typedi";import{depthUniformName as P,farUniformName as D,nearUniformName as F,resolutionUniformName as W,supportsDepthTextureExtension as H}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as A}from"./shader-nodes/time.js";import{sceneMapUniformName as L}from"./shader-nodes/scene-sample.js";import{DepthPass as j}from"./utils/three/depth-pass.js";import{GPUStatsPanel as E}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as O}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as k}from"./utils/three/traverse.js";(new r.Layers).set(9);const B=new r.MeshBasicMaterial({color:"black"}),U=new r.MeshDepthMaterial;U.depthPacking=r.RGBADepthPacking,U.blending=r.NoBlending,U.side=r.DoubleSide;const z=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let V=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||0!==this.container.clientWidth&&0!==this.container.clientHeight&&(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof h&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.bloomComposer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.aoMaskDepthRenderTarget.dispose(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.aoPass.blendMaterial.uniforms.tDepth.value=this.aoMaskDepthRenderTarget.depthTexture,this.depthRenderTarget.dispose(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget.dispose(),this.sceneColorRenderTarget=e.createSceneColorRenderTarget(this.renderer,this.container))}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=z?.5:1,this.maxPixelRatio=z?1:window.devicePixelRatio,this.onResize=()=>{this.resizeRender(),this.paused||this.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=new C,this._showStats=!0,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new s,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],null!=i.maxPixelRatio&&(this.maxPixelRatio=i.maxPixelRatio),window.renderer=this.renderer=new r.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new r.Scene,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(v.createButton(this.renderer)),this.composer=new c(this.renderer);var n=(t.clientWidth||1)/(t.clientHeight||1);const a=new r.PerspectiveCamera(45,n,.5,800);a.layers.enable(19),this.setCamera(a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=r.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=i.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=r.SRGBColorSpace,this.renderer.toneMapping=r.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,w.renderingView=this,w.patchThreeAdd(),this.isDepthTextureExtensionSupported=H(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget=e.createSceneColorRenderTarget(this.renderer,this.container);const o=new p(this.scene,this.camera);this.composer.addPass(o);const h=new g(new r.Vector2(t.clientWidth,t.clientHeight),1.5,.4,.85);h.threshold=1,h.strength=.9,h.radius=.5,this.bloomPass=h;const l=new M(this.scene,this.camera,t.clientWidth,t.clientWidth);l.blendMaterial.uniforms.tDepth={value:this.aoMaskDepthRenderTarget.depthTexture},l.blendMaterial.uniforms.tAODepth={value:l.depthTexture},l.blendMaterial.fragmentShader="\n uniform float intensity;\n uniform sampler2D tDiffuse;\n uniform sampler2D tDepth;\n uniform sampler2D tAODepth;\n varying vec2 vUv;\n\n void main() {\n vec4 texel = texture2D( tDiffuse, vUv );\n float d = textureLod(tDepth, vUv.xy, 0.0).x;\n float d2 = textureLod(tAODepth, vUv.xy, 0.0).x;\n\n float depth = 2.0 * 1.0 * 500.0 / (500.0 + 1.0 - (2.0 * d - 1.0) * (500.0 - 1.0));\n gl_FragColor = vec4(mix(vec3(1.), texel.rgb, d2 > d ? 0.0 : intensity), texel.a);\n }\n ",l.output=M.OUTPUT.Default,l.enabled=!1,this.aoPass=l,!1!==this.options.ao?.enabled&&this.composer.addPass(l),this.renderer.info.autoReset=!1;const d=new c(this.renderer);d.renderToScreen=!1,d.addPass(o),d.addPass(h),this.bloomComposer=d,z||(d.renderTarget2.texture.type=r.HalfFloatType,this.composer.renderTarget1.texture.type=r.HalfFloatType);const x=new f(new r.ShaderMaterial({uniforms:{baseTexture:{value:null},bloomTexture:{value:d.renderTarget2.texture}},vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }",fragmentShader:"\n uniform sampler2D baseTexture;\n uniform sampler2D bloomTexture;\n varying vec2 vUv;\n void main() {\n gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n }",defines:{}}),"baseTexture");if(x.needsSwap=!0,this.composer.addPass(x),this.outlinePass=new O(new r.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new f(m);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e)}new f(u).clear=!1,this.fixStatsStyle();const b=new y;this.composer.addPass(b)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setCamera(e){this.camera=e,this.composer.passes.forEach((t=>{t instanceof p?t.camera=e:t instanceof O?t.renderCamera=e:(t instanceof j||t instanceof M)&&(t.camera=e)})),null==this.csm?(this.csm=new R({maxFar:500,lightFar:250,lightMargin:20,cascades:4,shadowMapSize:2048,lightDirection:new r.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene}),l.lights_fragment_begin=x.lights_fragment_begin):(this.csm.camera=this.camera,this.camera instanceof h&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t){var i=!!e.extensions.get("WEBGL_depth_texture");const s=new r.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio());return s.texture.minFilter=r.NearestFilter,s.texture.magFilter=r.NearestFilter,s.texture.generateMipmaps=!1,s.stencilBuffer=!1,!0===i&&(s.depthTexture=new r.DepthTexture(128,128),s.depthTexture.type=r.UnsignedShortType,s.depthTexture.minFilter=r.NearestFilter,s.depthTexture.magFilter=r.NearestFilter),s}static createAOMaskDepthRenderTarget(e,t){const i=new r.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:r.HalfFloatType});return i.texture.minFilter=r.NearestFilter,i.texture.magFilter=r.NearestFilter,i.texture.generateMipmaps=!1,i.stencilBuffer=!1,i.depthTexture=new r.DepthTexture(128,128),i.depthTexture.type=r.UnsignedInt248Type,i.depthTexture.minFilter=r.NearestFilter,i.depthTexture.magFilter=r.NearestFilter,i}static createSceneColorRenderTarget(e,t){const i=new r.WebGLRenderTarget(t.clientWidth*e.getPixelRatio()*.5,t.clientHeight*e.getPixelRatio()*.5,{format:r.RGBAFormat,colorSpace:r.SRGBColorSpace,stencilBuffer:!1});return i.texture.minFilter=r.LinearFilter,i.texture.magFilter=r.LinearFilter,i.texture.generateMipmaps=!1,i}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){null!=this.scene.environment&&e instanceof b&&(null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1}),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment)}loop(e,t=!1){const i=this.stats,s=i.addPanel(new C.Panel("Calls","#83f","#002")),h=i.addPanel(new C.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new E(this.renderer.getContext()),i.addPanel(l)),this.showStats=t;let d=10,c=1e3;const m=()=>{const e=this.renderer.info.render.calls;e>d&&(d=e,setTimeout((()=>d=10),5e3)),s.update(e,d);const t=this.renderer.info.render.triangles;t>c&&(c=t,setTimeout((()=>c=1e3),5e3)),h.update(t,c)};performance.now();r.Ray.prototype.intersectTriangle;const u=[],p=[],f=[];let g=0;const v=new a,x=new a,w=t=>{const s=this.renderer.getContext();if(this.paused&&this.running&&s.drawingBufferHeight>1)return void setTimeout((()=>w(t)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,i.begin();let a=(t*=.001)-g;if(g=t,v.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(_),t-=_;e(t)}else e(a);this.onLoopCallbacks.forEach((e=>e(a))),this.camera?.updateMatrixWorld(),x.copy(this.camera.matrixWorld),x.equals(v)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender(),u.length=0,p.length=0,f.length=0;const h=I;if(this.camera.updateMatrixWorld(),G.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(G),this.scene.traverseVisible((e=>{if(null!=this.scene.environment&&(e instanceof o||e instanceof r.Sprite)&&function(e,t){if(Array.isArray(e.material))for(const i of e.material)t(i);else null!=e.material&&t(e.material)}(e,(e=>this.applyEnvMap(e))),(e instanceof o||e instanceof r.Sprite)&&this.initResolutionUniform(e.material),(e instanceof o||e instanceof r.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[P])&&isObjectInFrustum(e,h)?(e.visible=!1,u.push(e),this.initDepthUniform(e.material),e.renderOrder=100):e instanceof T?(e.visible=!1,p.push(e)):(e instanceof o||e instanceof r.Sprite)&&e.visible&&e.material?.uniforms&&null!=e.material?.uniforms[L]&&isObjectInFrustum(e,h)?(e.visible=!1,f.push(e),e.material.uniforms[L].value=this.sceneColorRenderTarget.texture):(e instanceof o||e instanceof r.Sprite)&&function(e){if(e.material instanceof n)return e.material.transparent||e.material.alphaTest>0;if(Array.isArray(e.material))for(const t of e.material)if(t.transparent||t.alphaTest>0)return!0}(e)&&(e.visible=!1,e.layers.enable(5),p.push(e)),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[A])e.material.uniforms[A].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const i of e.material)i.uniforms&&null!=i.uniforms[A]&&(i.uniforms[A].value=t)})),u.length>0){if(this.scene.overrideMaterial=U,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}if(f.length>0){if(this.renderer.setRenderTarget(this.sceneColorRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(!0,!0,!1),this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Error rendering scene color:",e)}this.renderer.setRenderTarget(null)}if(u.forEach((e=>e.visible=!0)),p.forEach((e=>e.visible=!0)),f.forEach((e=>e.visible=!0)),this.aoPass.enabled){if(this.scene.overrideMaterial=U,this.camera.layers.set(5),this.renderer.setRenderTarget(this.aoMaskDepthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.camera.layers.enableAll(),this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}try{!this.paused&&this.running&&(this.showStats&&l?.startQuery(),this.render(a),this.showStats&&l?.endQuery(),this.showStats&&m(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}i.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(w)}),1e3/this.fpsCap):requestAnimationFrame(w))};!0===this.options.enableXR?this.renderer.setAnimationLoop(w):requestAnimationFrame(w)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let r=0;r<e.length;r++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*r+this.insetMargin*r,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[r])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;const t=this.hasBloom();if(t||this.hadBloom){const e=this.scene.fog;this.scene.fog=null;const t=this.renderer.getClearColor(this.prevClearColor);this.renderer.setClearColor(0),this.scene.traverseVisible((e=>this.darkenNonBloomed(e))),this.bloomComposer.render(),this.scene.traverse((e=>this.restoreMaterial(e))),this.bloomHidden.forEach((e=>e.visible=!0)),this.bloomHidden.length=0,this.renderer.setClearColor(t),this.scene.fog=e}this.hadBloom=t,this.composer.render(e)}hasBloom(){return null!=k(this.scene,(e=>e instanceof o&&!0===e.material?.userData?.hasBloom))}darkenNonBloomed(e){(e instanceof o||e instanceof r.Sprite||e instanceof r.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)?(this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=B:e.visible=!1):"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof d&&(e.uniforms[P].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,this.camera instanceof h&&(null!=e.uniforms[F]&&(e.uniforms[F].value=this.camera.near),null!=e.uniforms[D]&&(e.uniforms[D].value=this.camera.far)))}initResolutionUniform(e){e instanceof d&&null!=e.uniforms[W]&&e.uniforms[W].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio())}};V=e=t([S(),i("design:paramtypes",[HTMLElement,Object])],V);export{V as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const _=.05;M.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse((function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls)&&(e.visible=!1),null!=e.material){let t=!1;if(Array.isArray(e.material)){for(const i of e.material)if(null!=i.alphaTest&&i.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0&&(t=!0);t&&(e.visible=!1)}}))};const I=new r.Frustum,N=new r.Box3,G=new r.Matrix4;export function isObjectInFrustum(e,t){const i=N.setFromObject(e);return t.intersectsBox(i)}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"asset-resource-loader.d.ts","sourceRoot":"","sources":["../../src/scene/asset-resource-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6G,QAAQ,EAAE,OAAO,EAA+B,MAAM,OAAO,CAAC;AAIlL,OAAO,EAAE,KAAK,EAAY,MAAM,YAAY,CAAC;AAG7C,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;
|
1
|
+
{"version":3,"file":"asset-resource-loader.d.ts","sourceRoot":"","sources":["../../src/scene/asset-resource-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6G,QAAQ,EAAE,OAAO,EAA+B,MAAM,OAAO,CAAC;AAIlL,OAAO,EAAE,KAAK,EAAY,MAAM,YAAY,CAAC;AAG7C,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAW/D,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAQ;IACxB,OAAO,CAAC,KAAK,CAAgC;IAC7C,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,cAAc,CAAuB;IAC7C,OAAO,CAAC,SAAS,CAAmE;IACpF,OAAO,CAAC,SAAS,CAAsC;IACvD,OAAO,CAAC,SAAS,CAAsC;IACvD,OAAO,CAAC,aAAa,CAAyC;IAC9D,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,SAAS,CAA0C;IAC3D,OAAO,CAAC,UAAU,CAAsC;IACxD,OAAO,CAAC,cAAc,CAAmD;IACzE,OAAO,CAAC,WAAW,CAAuC;IAC1D,OAAO,CAAC,eAAe,CAAQ;IAE/B,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO;IAIhC,OAAO,CAAC,SAAS,CAAgB;IACjC,OAAO,CAAC,KAAK,CAAiC;;IAIvC,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,aAAa;IAMtC,UAAU,CAAC,IAAI,EAAE,MAAM;IAK9B,OAAO,CAAC,MAAM;IAKD,UAAU,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC;IAmCvD,OAAO,CAAC,iBAAiB;IAYlB,UAAU,CAAC,KAAK,EAAE,KAAK;IAU9B,OAAO,CAAC,gBAAgB,CAAyC;IACpD,OAAO,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,UAAU,CAAC;IAuDpE,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,WAAW,CAAC;IAMzD,OAAO,CAAC,mBAAmB,CAAsC;IACjE,OAAO,CAAC,sBAAsB;YAShB,QAAQ;IAyBtB,OAAO,CAAC,eAAe,CAAoB;IAC3C,OAAO,CAAC,kBAAkB;YAyEZ,WAAW;CAiC1B;AAgBD,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,iBAAiB,CAAC;IACzB,UAAU,EAAE,KAAK,CAAC,aAAa,EAAE,CAAA;CAClC;AAED,qBAAa,iBAAkB,SAAQ,QAAQ;IAC7C,eAAe,CAAC,EAAE,cAAc,EAAE,CAAA;IAClC,OAAO,CAAC,EAAE,0BAA0B,CAAA;CACrC;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAInD;AAiFD,MAAM,MAAM,cAAc,GAAG;IAC3B;;;;OAIG;IACH,cAAc,EAAE,OAAO,CAAA;CACxB,CAAA"}
|
@@ -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
|
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,DRACOLoader as l}from"three-stdlib";import{FBXLoader as d}from"three-stdlib";import{cloneMesh as m}from"../utils/mesh.js";import{pathJoin as p}from"../utils/files.js";import{Subject as u,firstValueFrom as f}from"rxjs";import{importCollisionShapes as g,isCollisionMesh as w}from"./collision/collision-shape-import.js";import*as y from"three";import{iterateMaterials as x}from"../utils/materials.js";import{BufferGeometryUtils as L,EXRLoader as M,KTX2Loader as b,TGALoader as A,UltraHDRLoader as C}from"three/examples/jsm/Addons.js";const S=new l;S.setDecoderConfig({type:"js"}),S.setDecoderPath("/assets/draco/");const v=["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).setDRACOLoader(S),this.fbxLoader=new d(this.loadingManager),this.objLoader=new c(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new A(this.loadingManager),this.exrLoader=new M(this.loadingManager),this.hdrLoader=new C(this.loadingManager),this.ktx2Loader=new b(this.loadingManager),this._textureLoader=new y.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this.makeReady=new u,this.ready=f(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=p(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){return p(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=R(e.texture?.wrapS),t.wrapT=R(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0,this.textureCache.set(e.id,t),t))),this.textureCache.get(e.id))}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:this.textureLoader}clearCache(e){"mesh"===e.type&&Array.from(this.cache.keys()).forEach((t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)}))}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!v.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=m(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,d=e.castShadow??!1;return o.traverse((e=>{e.castShadow=d,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.traverse((e=>{w(e)&&(e.visible=!1)})),e.scene=function(e,t){let s=!1;if(t.traverseVisible((e=>{k.test(e.name)&&(s=!0)})),!s)return t;const a=new y.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(k);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&&!w(e)){a++;const t=Object.keys(e.geometry.attributes).length;t!==r&&0!==r&&(s=!1),r=t}else(e instanceof y.SkinnedMesh||e instanceof y.Bone)&&(s=!1)})),a>1&&s){const s=[],a=[],r=[];e.updateWorldMatrix(!0,!0),e.traverse((e=>{e instanceof i&&e.geometry instanceof t&&!w(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=L.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&&L.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=>(j(e),e))).then((e=>({scene:e,animations:e.animations})))}}}function j(e){if(e instanceof i)for(const t of x(e.material))t instanceof y.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(j)}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 R(e){switch(e){case"clamp":return y.ClampToEdgeWrapping;case"repeat":return y.RepeatWrapping;case"mirror":return y.MirroredRepeatWrapping}return y.RepeatWrapping}new y.Matrix4;const k=/_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,
|
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,EAAqG,MAAM,sBAAsB,CAAC;AAE5K,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAK7C,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,GAAG,cAAc,EAAE,CAyDrF;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,QAAQ,WAK/C"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{Box3 as e,Mesh as t,Quaternion as n,Vector3 as s}from"three";import{BoxCollisionShape as i,
|
1
|
+
import{Box3 as e,Mesh as t,Quaternion as n,Vector3 as s}from"three";import{BoxCollisionShape as i,CollisionShapeSource as o,ConvexPolyhedronCollisionShape as r,SphereCollisionShape as a,TrimeshCollisionShape as m}from"./collision-shape.js";new n;export function importCollisionShapes(n,l){let c=l.mesh?.collisions?.shapeType;if(null==c){let e=!1;n.traverse((n=>{(n instanceof t||n.isMesh)&&isCollisionMesh(n)&&(e=!0)})),c=e?"imported":"convex"}const u=[];return n.traverse((n=>{if(n instanceof t||n.isMesh){let t;"imported"===c?t=function(t){if(t.name.startsWith(h.convex))return new r(t);if(t.name.startsWith(h.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(h.sphere)){t.geometry.computeBoundingSphere();const e=t.geometry.boundingSphere.radius*Math.max(t.scale.x,t.scale.y,t.scale.z);return new a(e)}if(t.name.startsWith(h.trimesh))return new m(t.geometry)}(n):"convex"===c?t=new r(n):"mesh"===c&&(t=new m(n.geometry)),null!=t&&(t.source="imported"!==c?o.rendered:o.custom,t.offset=n.getWorldPosition(new s),u.push(t),isCollisionMesh(n)&&(n.visible=!1))}})),u}export function isCollisionMesh(e){return e.name.startsWith(h.convex)||e.name.startsWith(h.box)||e.name.startsWith(h.sphere)||e.name.startsWith(h.trimesh)}var h;!function(e){e.convex="UCX_",e.box="UBX_",e.sphere="USP_",e.trimesh="UTM_"}(h||(h={}));new e;/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,5 +1,18 @@
|
|
1
1
|
import { SceneObjectPhysicsSettings } from "../../scene/materializer.js";
|
2
2
|
import { BufferGeometry, Euler, Material, Mesh, Vector3 } from "three";
|
3
|
+
export declare enum CollisionShapeSource {
|
4
|
+
/**
|
5
|
+
* The shape is distinct from the rendered mesh
|
6
|
+
* so the offset and rotation should be used even for
|
7
|
+
* instanced meshes in physics system
|
8
|
+
*/
|
9
|
+
custom = 0,
|
10
|
+
/** It is based on the geometry of the rendered mesh
|
11
|
+
* In this case, we will ignore the position and rotation
|
12
|
+
* for instanced meshes
|
13
|
+
*/
|
14
|
+
rendered = 1
|
15
|
+
}
|
3
16
|
export declare class CollisionShape {
|
4
17
|
offset: Vector3;
|
5
18
|
rotation: Euler;
|
@@ -8,6 +21,7 @@ export declare class CollisionShape {
|
|
8
21
|
friction?: number;
|
9
22
|
restitution?: number;
|
10
23
|
collisionGroup?: number;
|
24
|
+
source?: CollisionShapeSource;
|
11
25
|
withRestitution(restitution: number): this;
|
12
26
|
withOffset(vector: Vector3): this;
|
13
27
|
withRotation(rotation: Euler): this;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"collision-shape.d.ts","sourceRoot":"","sources":["../../../src/scene/collision/collision-shape.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAA;AACxE,OAAO,EAAe,cAAc,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,OAAO,CAAA;
|
1
|
+
{"version":3,"file":"collision-shape.d.ts","sourceRoot":"","sources":["../../../src/scene/collision/collision-shape.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAA;AACxE,OAAO,EAAe,cAAc,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,OAAO,CAAA;AAGnF,oBAAY,oBAAoB;IAC9B;;;;MAIE;IACF,MAAM,IAAA;IACN;;;OAGG;IACH,QAAQ,IAAA;CACT;AACD,qBAAa,cAAc;IAClB,MAAM,EAAE,OAAO,CAAgB;IAC/B,QAAQ,EAAE,KAAK,CAAc;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,cAAc,CAAC,EAAE,MAAM,CAAA;IAGvB,MAAM,CAAC,EAAE,oBAAoB,CAAA;IAEpC,eAAe,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI;IAK1C,UAAU,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI;IAKjC,YAAY,CAAC,QAAQ,EAAE,KAAK;IAK5B,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAKlC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAK5B,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAKpC,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,OAAO;IAI9B,MAAM,CAAC,KAAK,CACV,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM;IAKhB,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM;IAI5B,MAAM,CAAC,QAAQ,CACb,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,KAAK;IAKpB,MAAM,CAAC,IAAI,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAIhD,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE,IAAI,GAAG,cAAc;IAInD,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,cAAc;IAIvC,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,cAAc;IAIpC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAI9C;AAED,qBAAa,iBAAkB,SAAQ,cAAc;aAEjC,UAAU,EAAE,OAAO;gBAAnB,UAAU,EAAE,OAAO;CAItC;AAED,qBAAa,mBAAoB,SAAQ,cAAc;aAEnC,KAAK,EAAE,MAAM;aACb,MAAM,EAAE,MAAM;gBADd,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM;CAIjC;AAED,qBAAa,oBAAqB,SAAQ,cAAc;aAEpC,MAAM,EAAE,MAAM;gBAAd,MAAM,EAAE,MAAM;CAIjC;AAED,qBAAa,sBAAuB,SAAQ,cAAc;aAEtC,SAAS,EAAE,MAAM;aACjB,YAAY,EAAE,MAAM;aACpB,MAAM,EAAE,MAAM;aACd,QAAQ,EAAE,MAAM;aAChB,UAAU,EAAE,KAAK;gBAJjB,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,KAAK;CAIpC;AAED,qBAAa,kBAAmB,SAAQ,cAAc;aAElC,YAAY,EAAE,MAAM;aACpB,MAAM,EAAE,MAAM;gBADd,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM;CAIjC;AAED,qBAAa,8BAA+B,SAAQ,cAAc;aAE9C,IAAI,EAAE,IAAI,GAAC,cAAc;gBAAzB,IAAI,EAAE,IAAI,GAAC,cAAc;CAI5C;AAED,qBAAa,qBAAsB,SAAQ,cAAc;aAErC,QAAQ,EAAE,cAAc;gBAAxB,QAAQ,EAAE,cAAc;CAK3C;AAED,qBAAa,kBAAmB,SAAQ,cAAc;aAElC,QAAQ,EAAE,cAAc;gBAAxB,QAAQ,EAAE,cAAc;CAI3C;AAGD,qBAAa,qBAAsB,SAAQ,cAAc;IAE9C,MAAM,EAAE,MAAM;IACd,MAAM,EAAE,MAAM;gBADd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;CAIxB;AAGD,qBAAa,iBAAkB,SAAQ,IAAI;IAKhC,cAAc,EAAE,cAAc;IAC9B,OAAO,CAAC,EAAE,0BAA0B;IAL7C,mBAAmB,UAAO;gBAExB,QAAQ,EAAE,cAAc,EACxB,QAAQ,EAAE,QAAQ,EACX,cAAc,EAAE,cAAc,EAC9B,OAAO,CAAC,EAAE,0BAA0B;CAI9C"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{Euler as s,Mesh as e,Vector3 as t}from"three";export class CollisionShape{constructor(){this.offset=new t,this.rotation=new s}withRestitution(s){return this.restitution=s,this}withOffset(s){return this.offset.copy(s),this}withRotation(s){return this.rotation.copy(s),this}withDensity(s){return this.density=s,this}withMass(s){return this.mass=s,this}withFriction(s){return this.friction=s,this}static box(s){return new BoxCollisionShape(s)}static plane(s,e){return new PlaneCollisionShape(s,e)}static sphere(s){return new SphereCollisionShape(s)}static cylinder(s,e,t,i,o){return new CylinderCollisionShape(s,e,t,i,o)}static cone(s,e){return new ConeCollisionShape(s,e)}static convexPolyhedron(s){return new ConvexPolyhedronCollisionShape(s)}static trimesh(s){return new TrimeshCollisionShape(s)}static mesh(s){return new MeshCollisionShape(s)}static capsule(s,e){return new CapsuleCollisionShape(s,e)}}export class BoxCollisionShape extends CollisionShape{constructor(s){super(),this.dimensions=s}}export class PlaneCollisionShape extends CollisionShape{constructor(s,e){super(),this.width=s,this.height=e}}export class SphereCollisionShape extends CollisionShape{constructor(s){super(),this.radius=s}}export class CylinderCollisionShape extends CollisionShape{constructor(s,e,t,i,o){super(),this.radiusTop=s,this.radiusBottom=e,this.height=t,this.segments=i,this.orentation=o}}export class ConeCollisionShape extends CollisionShape{constructor(s,e){super(),this.radiusBottom=s,this.height=e}}export class ConvexPolyhedronCollisionShape extends CollisionShape{constructor(s){super(),this.mesh=s}}export class TrimeshCollisionShape extends CollisionShape{constructor(s){super(),this.geometry=s}}export class MeshCollisionShape extends CollisionShape{constructor(s){super(),this.geometry=s}}export class CapsuleCollisionShape extends CollisionShape{constructor(s,e){super(),this.length=s,this.radius=e}}export class PhysicalShapeMesh extends e{constructor(s,e,t,i){super(s,e),this.collisionShape=t,this.physics=i,this.isPhysicalShapeMesh=!0}}/*
|
1
|
+
import{Euler as s,Mesh as e,Vector3 as t}from"three";export var CollisionShapeSource;!function(s){s[s.custom=0]="custom",s[s.rendered=1]="rendered"}(CollisionShapeSource||(CollisionShapeSource={}));export class CollisionShape{constructor(){this.offset=new t,this.rotation=new s}withRestitution(s){return this.restitution=s,this}withOffset(s){return this.offset.copy(s),this}withRotation(s){return this.rotation.copy(s),this}withDensity(s){return this.density=s,this}withMass(s){return this.mass=s,this}withFriction(s){return this.friction=s,this}static box(s){return new BoxCollisionShape(s)}static plane(s,e){return new PlaneCollisionShape(s,e)}static sphere(s){return new SphereCollisionShape(s)}static cylinder(s,e,t,i,o){return new CylinderCollisionShape(s,e,t,i,o)}static cone(s,e){return new ConeCollisionShape(s,e)}static convexPolyhedron(s){return new ConvexPolyhedronCollisionShape(s)}static trimesh(s){return new TrimeshCollisionShape(s)}static mesh(s){return new MeshCollisionShape(s)}static capsule(s,e){return new CapsuleCollisionShape(s,e)}}export class BoxCollisionShape extends CollisionShape{constructor(s){super(),this.dimensions=s}}export class PlaneCollisionShape extends CollisionShape{constructor(s,e){super(),this.width=s,this.height=e}}export class SphereCollisionShape extends CollisionShape{constructor(s){super(),this.radius=s}}export class CylinderCollisionShape extends CollisionShape{constructor(s,e,t,i,o){super(),this.radiusTop=s,this.radiusBottom=e,this.height=t,this.segments=i,this.orentation=o}}export class ConeCollisionShape extends CollisionShape{constructor(s,e){super(),this.radiusBottom=s,this.height=e}}export class ConvexPolyhedronCollisionShape extends CollisionShape{constructor(s){super(),this.mesh=s}}export class TrimeshCollisionShape extends CollisionShape{constructor(s){super(),this.geometry=s}}export class MeshCollisionShape extends CollisionShape{constructor(s){super(),this.geometry=s}}export class CapsuleCollisionShape extends CollisionShape{constructor(s,e){super(),this.length=s,this.radius=e}}export class PhysicalShapeMesh extends e{constructor(s,e,t,i){super(s,e),this.collisionShape=t,this.physics=i,this.isPhysicalShapeMesh=!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{Subject as e,debounceTime as t}from"rxjs";import{Box3 as s,BufferAttribute as n,InstancedMesh as o,MathUtils as i,Matrix4 as a,Mesh as r,MeshStandardMaterial as c,PerspectiveCamera as l,PlaneGeometry as h,ShaderMaterial as u,Triangle as f,Vector2 as p,Vector3 as m}from"three";import{materialFromAsset as d}from"../../scene/materializer.js";import{getMaterialAttribute as w}from"../../scene/materials/utils/material-painting";import{whenIdle as g}from"../../utils/async.js";import{indexBy as y}from"../../utils/collections.js";import{meanVectors3withWeight as M}from"../../utils/math.js";import{LandscapeMesh as x,defaultLandscapeMaterial as b}from"./landscape.js";import{smoothNormalsCrossMeshes as S}from"./utils.js";export const grassGeometryTriangleLimit=400;new m,new m;const v=new m,A=new m,z=new m;export class LandscapeManager{constructor(s,n,o,i,r,c,l){this.view=n,this.landscape=o,this.assetManagerService=i,this.assetService=r,this.shaders=c,this.applyMaterial=l,this.scatterMeshes=new Map,this.loadedScatterSquares=new Set,this.refreshRequests=new e,this.defaultLandscapeMaterial=b.clone(),this.scatterMeshPool=[],this.onLoopHandler=()=>this.update(),this.sectionCache=new Map,this._matrix=new a,this.scatterGeometryCache=new Map,this._lastUpdatePosition=new m,this._cameraPosition=new m,this.source=JSON.parse(JSON.stringify(s)),this.view.onLoop(this.onLoopHandler),this.defaultLandscapeMaterial.name=b.name,this.defaultLandscapeMaterial.color=b.color,this.refreshRequests.pipe(t(500)).subscribe((e=>this.refreshScatter(e.origin,e.force,e.predicate)))}updateSource(e){this.source=JSON.parse(JSON.stringify(e))}updateShaders(e){this.shaders=e}async loadGrass(){const e=await this.assetService.getAsset("6ij937n72g");await this.assetManagerService.getMesh(e);this.grassGeometry=new h(2,2,3,3);const t=this.grassGeometry.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.needsUpdate=!0,this.grassMaterial=new c({color:3765785})}refreshGeometry(){const e=this.source.landscape.options,t=(new m,new m);this.view.camera.getWorldPosition(t);const s=[];z.fromArray(this.source.position);const n=this.view.camera instanceof l?Math.min(this.view.camera.far,1e3):1e3,o=1.1*n,i=e.sections.y*e.sectionSize/-2,a=e.sections.x*e.sectionSize/-2;for(let r=0;r<e.sections.x;r++)if(v.x=a+r*e.sectionSize,!(Math.abs(t.x-v.x)>o))for(let c=0;c<e.sections.y;c++){v.z=i+c*e.sectionSize,A.copy(z).add(v);const l=A.distanceTo(t),h=`${r},${c}`,u=this.landscape.sections.find((e=>e.x===r&&e.y===c));if(l<=n){if(null==u){this.sectionCache.has(h)||this.sectionCache.set(h,this.createLandscapeMesh(this.source,e,a,i,r,c));const t=this.sectionCache.get(h);this.applyMaterial(t),this.landscape.add(t),s.push(t)}}else l>o&&this.landscape.remove(u)}S(s)}applyHeightMap(e,t,s,n=1){const o=Math.pow(s+1,2),i=e.getAttribute("position");if(1===n)for(const e of t.points)i.setY(e.i,e.y);else{const e=y(t.points??[],(e=>e.i));for(let t=0;t<i.count;t++){const s=P(t,i.count,o);let n=0;n=s%1==0?e.get(s)?.y??0:Math.floor(e.get(s)?.y),i.setY(t,n)}}i.needsUpdate=!0,e.computeVertexNormals()}deleteOldScatterMeshes(){const e=new Set;for(const[t,s]of this.source.grass?.layers.entries()??[])for(const[n,o]of s.meshes.entries()){const s=`${t}-${n}`;e.add(s)}for(const t of this.scatterMeshes.keys())if(!e.has(t)){this.scatterMeshes.get(t).forEach((e=>{e.parent?.remove(e),e.dispose()})),this.scatterMeshes.delete(t)}}queueRefreshScatter(e,t=!1,s=()=>!0){this.refreshRequests.next({origin:e,force:t,predicate:s})}async refreshScatter(e,t=!1,s=()=>!0){t&&this.scatterGeometryCache.clear(),this.deleteOldScatterMeshes();for(const[n,a]of this.source.grass?.layers.entries()??[])for(const[c,l]of a.meshes.entries()){const a=`${n}-${c}`;this.scatterMeshes.has(a)||this.scatterMeshes.set(a,new Map);const h=this.scatterMeshes.get(a),u=await this.assetService.getAsset(l.assetId);if(null==u){console.error(`Can not find asset with id ${l.assetId}`);continue}let p;try{p=await this.assetManagerService.getMesh(u)}catch(e){console.error(`Failed to load mesh in landscape manager for asset with name ${u.name}`,e);continue}const w=[];if(p.scene.traverse((e=>{e instanceof r&&w.push(e)})),1!==w.length){console.log(p),console.warn("Dynamic grass only works for meshes with a single geometry.");continue}if(!(w[0]instanceof r)){console.warn("Only meshes can be used for dynamic grass. Found:",p.scene);continue}const x=w[0];let b=x.geometry;if(this.scatterGeometryCache.has(x.geometry.uuid))b=this.scatterGeometryCache.get(x.geometry.uuid);else if(b=x.geometry.clone(),!0===l.normalsUp&&F(b),null==b.userData.updatedMatrix){p.scene.updateMatrixWorld(),b.applyMatrix4(x.matrixWorld),b.userData.updatedMatrix=!0;const e=u.mesh?.rescale??1;1!==e&&b.scale(e,e,e)}const S=b.getIndex()??b.getAttribute("position"),v=null!=S?S.count/3:0;if(v>400){console.warn(`The triangle count of ${u.name} is too big ${v}. Keep it below 400`);continue}const A=null!=u.materialAssignments&&u.materialAssignments.length>0?u.materialAssignments[0].materialId:null,z=null!=A&&"null"!==A?await d(await this.assetService.getAsset(A),null,this.assetService,this.assetManagerService,this.shaders,!1):null;let P=null!=z?z:x.material;const L=i.degToRad(l.maxSlope??90),_=Math.cos(L),T=this.landscape.sections,q=T.filter(j(e,l.viewDistance)),I=q.filter((e=>!h.has(e.uuid)||t)).filter((e=>s(e)));T.filter($(e,2*l.viewDistance)).forEach((e=>{const t=h.get(e.uuid);null!=t&&(t.visible=!1)}));for(const e of q){const t=h.get(e.uuid);null!=t&&(t.visible=!0)}performance.now();const R=this.source.landscape.options,k=R.sectionSize,D=l.density??1??1,H=R.density,X=k/H,Y=D,E=X/Math.sqrt(Y),J=Math.pow(H,2),Z=E/X,K=Math.floor(J*Y),V=[0,0,0];for(const e of I)await g((async()=>{e.updateWorldMatrix(!0,!1);const s=this._matrix,i=new m,a=e.geometry.getAttribute("position"),r=e.geometry.getAttribute("normal"),c=(this.source.vertexMaterials??[]).filter((t=>t.m===e.name)),u=y(c,(e=>e.i));let p=h.get(e.uuid);if(null==p||p.count==K&&!t||(p.parent?.remove(p),this.scatterMeshPool.push(p),h.delete(e.uuid),p=null),null==p){const e=this.scatterMeshPool.findIndex((e=>e.count>=K));e>-1?(p=this.scatterMeshPool[e],p.geometry=b,p.material=P,this.scatterMeshPool.splice(e,1)):p=new o(b,P,K),p.raycast=()=>{},p.receiveShadow=!0}p.visible=!0;const d=new f(new m,new m,new m);let[w,g,x,S]=[new m,new m,new m,new m],[v,A,z]=[[],[],[]],[L,$,j]=[new m,new m,new m,new m];const T=new m,q=new m,I=new m,R=new m,k=new f(new m,new m,new m),D=new f(new m,new m,new m),F=new f(new m,new m,new m),X=new f(new m,new m,new m);let E=0;e:for(let t=0;t<J;t++){const o=Math.floor(t/H);w.fromBufferAttribute(a,t+o),R.copy(w).applyMatrix4(e.matrixWorld),k.a.copy(w),k.b.fromBufferAttribute(a,t+1+o),k.c.fromBufferAttribute(a,t+H+1+o),D.a.copy(k.b),D.b.copy(k.c),D.c.fromBufferAttribute(a,t+H+2+o),F.a.fromBufferAttribute(r,t+o),F.b.fromBufferAttribute(r,t+1+o),F.c.fromBufferAttribute(r,t+H+1+o),X.a.copy(F.b),X.b.copy(F.c),X.c.fromBufferAttribute(r,t+H+2+o);const c=[];c[0]=u.get(t+o)?.w,c[1]=u.get(t+1+o)?.w,c[2]=u.get(t+H+1+o)?.w,c[3]=u.get(t+H+2+o)?.w;let h=0;for(let e=0;e<=1+Z;e+=Z)for(let t=0;t<=1+Z;t+=Z){if(E>K)break e;if(h++,h>Y)continue e;1-e>t?(g=k.a,x=k.b,S=k.c,L=F.a,$=F.b,j=F.c,v=c[0],A=c[1],z=c[2]):(g=D.a,x=D.b,S=D.c,L=X.a,$=X.b,j=X.c,v=c[1],A=c[2],z=c[3]),d.a.copy(g),d.b.copy(x),d.c.copy(S),B(d),T.set(w.x,0,w.z),U(d,T),d.getBarycoord(T,i).toArray(V),C[0]=v,C[1]=A,C[2]=z;if(G(C,V,.2)!==n-1)continue;if(M([g,x,S],V,q),M([L,$,j],V,I),null!=l.maxSlope&&l.maxSlope<90&&I.y<_)continue;const o=q;o.y+=O(l.offsetMin,l.offsetMax);const a=O(l.scaleMin??1,l.scaleMax??1);s.makeScale(a,a,a);const r=s.elements;r[12]=o.x,r[13]=o.y,r[14]=o.z,!1!==l.randomRotation&&N(s,a),l.alignToNormal&&W(s,o,p.matrixWorld,I);const u=p.instanceMatrix.array,f=16*E;u[f]=r[0],u[f+1]=r[1],u[f+2]=r[2],u[f+3]=r[3],u[f+4]=r[4],u[f+5]=r[5],u[f+6]=r[6],u[f+7]=r[7],u[f+8]=r[8],u[f+9]=r[9],u[f+10]=r[10],u[f+11]=r[11],u[f+12]=r[12],u[f+13]=r[13],u[f+14]=r[14],u[f+15]=r[15],E++}}p.count=E,p.instanceMatrix.needsUpdate=!0,p.position.copy(e.position),p.updateMatrix(),h.has(e.uuid)||this.landscape?.add(p),h.set(e.uuid,p),p.userData.meshConfig=l}));performance.now()}}stop(){this.view.removeOnLoop(this.onLoopHandler)}update(){this.view.camera&&(this.view.camera.getWorldPosition(this._cameraPosition),this._cameraPosition.distanceTo(this._lastUpdatePosition)>10&&(this._lastUpdatePosition.copy(this._cameraPosition),this.refreshGeometry(),this.refreshScatter(this._cameraPosition)))}clear(){this.scatterMeshes.forEach((e=>e.forEach((e=>e.parent?.remove(e)))))}createLandscapeMesh(e,t,s,n,o,i){const a=new h(t.sectionSize,t.sectionSize,t.density,t.density);a.rotateX(Math.PI/-2);const r=this.defaultLandscapeMaterial,c=new x(a,r);c.position.x=s+o*t.sectionSize,c.position.z=n+i*t.sectionSize,c.receiveShadow=!0,c.castShadow=!1,c.userData.landscape={x:o,y:i},c.x=o,c.y=i,c.name=`${o},${i}`,w(c,0,!0),w(c,4,!0);const l=e.landscape.heightMaps.find((e=>e.x===o&&e.y===i));if(null!=l&&this.applyHeightMap(a,l,t.density,1),a.computeBoundsTree(),null!=e.landscape.holes&&e.landscape.holes.length>0){const t=getHoleAttribute(c,!0);for(const s of e.landscape.holes)s.m===c.name&&t.setX(s.i,s.w[0])}return c}}export function getHoleAttribute(e,t=!1){if(!e.geometry.hasAttribute("hole")||t){const t=new Float32Array(e.geometry.getAttribute("position").array.length);e.geometry.setAttribute("hole",new n(t,1))}return e.geometry.getAttribute("hole")}function P(e,t,s){const n=Math.sqrt(t),o=Math.floor(e/n)/(n-1),i=e%n/(n-1),a=Math.sqrt(s);return(s-1)*o-(a-1)*o+(a-1)*i}new Map,new p(0,0),new p(1,0),new p(0,1),new p(1,0),new p(0,1),new p(1,1),new m;const L=new s;function $(e,t){return function(s){return L.setFromObject(s).distanceToPoint(e)>t}}function j(e,t){return function(s){return L.setFromObject(s).distanceToPoint(e)<t}}function B(e){e.a.y=0,e.b.y=0,e.c.y=0}const C=[];function G(e,t,s=.5){const n=C;let o=-1,i=-1;for(let e=0;e<n.length;e++)if(null!=n[e])for(let a=0;a<n[e].length;a++){const r=n[e][a]*t[e];r>s&&r>i&&(i=r,o=a)}return o}function O(e,t){let s=t-e,n=q();return n*=s,n+=e,n}const _=[];let T=1e3;for(;T--;)_.push(Math.random());function q(){return++T>=_.length?_[T=0]:_[T]}const I=[];let R=20;for(;R--;)I.push((new a).makeRotationY(q()*Math.PI/2));function U(e,t){let s=q(),n=q();s+n>1&&(s=1-s,n=1-n);const o=e.a,i=e.b,a=e.c;t.x=o.x+s*(i.x-o.x)+n*(a.x-o.x),t.z=o.z+s*(i.z-o.z)+n*(a.z-o.z)}new m;new m;const k=new m,D=new m(0,1,0),H=(new a).makeRotationX(Math.PI/-2);function W(e,t,s,n){e.lookAt(k,n,D).multiply(H)}new a;function N(e,t=1){const s=(++R>=I.length?I[R=0]:I[R]).elements,n=e.elements;n[0]=s[0]*t,n[4]=s[4]*t,n[8]=s[8]*t,n[1]=s[1]*t,n[5]=s[5]*t,n[9]=s[9]*t,n[2]=s[2]*t,n[6]=s[6]*t,n[10]=s[10]*t}function F(e){const t=e.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.normalized=!0,t.needsUpdate=!0}/*
|
1
|
+
import{Subject as e,debounceTime as t}from"rxjs";import{Box3 as s,BufferAttribute as n,InstancedMesh as o,MathUtils as i,Matrix4 as a,Mesh as r,MeshStandardMaterial as c,PerspectiveCamera as l,PlaneGeometry as h,ShaderMaterial as u,Triangle as f,Vector2 as m,Vector3 as p}from"three";import{materialFromAsset as d}from"../../scene/materializer.js";import{getMaterialAttribute as w}from"../../scene/materials/utils/material-painting";import{whenIdle as g}from"../../utils/async.js";import{indexBy as y}from"../../utils/collections.js";import{meanVectors3withWeight as M}from"../../utils/math.js";import{LandscapeMesh as x,defaultLandscapeMaterial as b}from"./landscape.js";import{smoothNormalsCrossMeshes as S}from"./utils.js";export const grassGeometryTriangleLimit=400;new p,new p;const v=new p,A=new p,z=new p;export class LandscapeManager{constructor(s,n,o,i,r,c,l){this.view=n,this.landscape=o,this.assetManagerService=i,this.assetService=r,this.shaders=c,this.applyMaterial=l,this.scatterMeshes=new Map,this.loadedScatterSquares=new Set,this.refreshRequests=new e,this.defaultLandscapeMaterial=b.clone(),this.scatterMeshPool=[],this.onLoopHandler=()=>this.update(),this.sectionCache=new Map,this._matrix=new a,this.scatterGeometryCache=new Map,this._lastUpdatePosition=new p,this._cameraPosition=new p,this.source=JSON.parse(JSON.stringify(s)),this.view.onLoop(this.onLoopHandler),this.defaultLandscapeMaterial.name=b.name,this.defaultLandscapeMaterial.color=b.color,this.refreshRequests.pipe(t(500)).subscribe((e=>this.refreshScatter(e.origin,e.force,e.predicate)))}updateSource(e){this.source=JSON.parse(JSON.stringify(e))}updateShaders(e){this.shaders=e}async loadGrass(){const e=await this.assetService.getAsset("6ij937n72g");await this.assetManagerService.getMesh(e);this.grassGeometry=new h(2,2,3,3);const t=this.grassGeometry.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.needsUpdate=!0,this.grassMaterial=new c({color:3765785})}refreshGeometry(){const e=this.source.landscape.options,t=(new p,new p);this.view.camera.getWorldPosition(t);const s=[];z.fromArray(this.source.position);const n=this.view.camera instanceof l?Math.min(this.view.camera.far,1e3):1e3,o=1.1*n,i=e.sections.y*e.sectionSize/-2,a=e.sections.x*e.sectionSize/-2;for(let r=0;r<e.sections.x;r++)if(v.x=a+r*e.sectionSize,!(Math.abs(t.x-v.x)>o))for(let c=0;c<e.sections.y;c++){v.z=i+c*e.sectionSize,A.copy(z).add(v);const l=A.distanceTo(t),h=`${r},${c}`,u=this.landscape.sections.find((e=>e.x===r&&e.y===c));if(l<=n){if(null==u){this.sectionCache.has(h)||this.sectionCache.set(h,this.createLandscapeMesh(this.source,e,a,i,r,c));const t=this.sectionCache.get(h);this.applyMaterial(t),this.landscape.add(t),s.push(t)}}else l>o&&this.landscape.remove(u)}S(s)}applyHeightMap(e,t,s,n=1){const o=Math.pow(s+1,2),i=e.getAttribute("position");if(1===n)for(const e of t.points)i.setY(e.i,e.y);else{const e=y(t.points??[],(e=>e.i));for(let t=0;t<i.count;t++){const s=P(t,i.count,o);let n=0;n=s%1==0?e.get(s)?.y??0:Math.floor(e.get(s)?.y),i.setY(t,n)}}i.needsUpdate=!0,e.computeVertexNormals()}deleteOldScatterMeshes(){const e=new Set;for(const[t,s]of this.source.grass?.layers.entries()??[])for(const[n,o]of s.meshes.entries()){const s=`${t}-${n}`;e.add(s)}for(const t of this.scatterMeshes.keys())if(!e.has(t)){this.scatterMeshes.get(t).forEach((e=>{e.parent?.remove(e),e.dispose()})),this.scatterMeshes.delete(t)}}queueRefreshScatter(e,t=!1,s=()=>!0){this.refreshRequests.next({origin:e,force:t,predicate:s})}async refreshScatter(e,t=!1,s=()=>!0){t&&this.scatterGeometryCache.clear(),this.deleteOldScatterMeshes();for(const[n,a]of this.source.grass?.layers.entries()??[])for(const[c,l]of a.meshes.entries()){const a=`${n}-${c}`;this.scatterMeshes.has(a)||this.scatterMeshes.set(a,new Map);const h=this.scatterMeshes.get(a),u=await this.assetService.getAsset(l.assetId);if(null==u){console.error(`Can not find asset with id ${l.assetId}`);continue}let m;try{m=await this.assetManagerService.getMesh(u)}catch(e){console.error(`Failed to load mesh in landscape manager for asset with name ${u.name}`,e);continue}const w=[];if(m.scene.traverse((e=>{e instanceof r&&w.push(e)})),1!==w.length){console.log(m),console.warn("Dynamic grass only works for meshes with a single geometry.");continue}if(!(w[0]instanceof r)){console.warn("Only meshes can be used for dynamic grass. Found:",m.scene);continue}const x=w[0];let b=x.geometry;if(this.scatterGeometryCache.has(x.geometry.uuid))b=this.scatterGeometryCache.get(x.geometry.uuid);else if(b=x.geometry.clone(),!0===l.normalsUp&&F(b),this.scatterGeometryCache.set(x.geometry.uuid,b),null==b.userData.updatedMatrix){m.scene.updateMatrixWorld(),b.applyMatrix4(x.matrixWorld),b.userData.updatedMatrix=!0;const e=u.mesh?.rescale??1;1!==e&&b.scale(e,e,e)}const S=b.getIndex()??b.getAttribute("position"),v=null!=S?S.count/3:0;if(v>400){console.warn(`The triangle count of ${u.name} is too big ${v}. Keep it below 400`);continue}const A=null!=u.materialAssignments&&u.materialAssignments.length>0?u.materialAssignments[0].materialId:null,z=null!=A&&"null"!==A?await d(await this.assetService.getAsset(A),null,this.assetService,this.assetManagerService,this.shaders,!1):null;let P=null!=z?z:x.material;const L=i.degToRad(l.maxSlope??90),_=Math.cos(L),T=this.landscape.sections,q=T.filter(C(e,l.viewDistance)),I=q.filter((e=>!h.has(e.uuid)||t)).filter((e=>s(e)));T.filter($(e,2*l.viewDistance)).forEach((e=>{const t=h.get(e.uuid);null!=t&&(t.visible=!1)}));for(const e of q){const t=h.get(e.uuid);null!=t&&(t.visible=!0)}performance.now();const R=this.source.landscape.options,k=R.sectionSize,D=l.density??1??1,H=R.density,X=k/H,Y=D,E=X/Math.sqrt(Y),J=Math.pow(H,2),Z=E/X,K=Math.floor(J*Y),V=[0,0,0];for(const e of I)await g((async()=>{e.updateWorldMatrix(!0,!1);const s=this._matrix,i=new p,a=e.geometry.getAttribute("position"),r=e.geometry.getAttribute("normal"),c=(this.source.vertexMaterials??[]).filter((t=>t.m===e.name)),u=y(c,(e=>e.i));let m=h.get(e.uuid);if(null==m||m.count==K&&!t||(m.parent?.remove(m),this.scatterMeshPool.push(m),h.delete(e.uuid),m=null),null==m){const e=this.scatterMeshPool.findIndex((e=>e.count>=K));e>-1?(m=this.scatterMeshPool[e],m.geometry=b,m.material=P,this.scatterMeshPool.splice(e,1)):m=new o(b,P,K),m.raycast=()=>{},m.receiveShadow=!0}m.visible=!0;const d=new f(new p,new p,new p);let[w,g,x,S]=[new p,new p,new p,new p],[v,A,z]=[[],[],[]],[L,$,C]=[new p,new p,new p,new p];const T=new p,q=new p,I=new p,R=new p,k=new f(new p,new p,new p),D=new f(new p,new p,new p),F=new f(new p,new p,new p),X=new f(new p,new p,new p);let E=0;e:for(let t=0;t<J;t++){const o=Math.floor(t/H);w.fromBufferAttribute(a,t+o),R.copy(w).applyMatrix4(e.matrixWorld),k.a.copy(w),k.b.fromBufferAttribute(a,t+1+o),k.c.fromBufferAttribute(a,t+H+1+o),D.a.copy(k.b),D.b.copy(k.c),D.c.fromBufferAttribute(a,t+H+2+o),F.a.fromBufferAttribute(r,t+o),F.b.fromBufferAttribute(r,t+1+o),F.c.fromBufferAttribute(r,t+H+1+o),X.a.copy(F.b),X.b.copy(F.c),X.c.fromBufferAttribute(r,t+H+2+o);const c=[];c[0]=u.get(t+o)?.w,c[1]=u.get(t+1+o)?.w,c[2]=u.get(t+H+1+o)?.w,c[3]=u.get(t+H+2+o)?.w;let h=0;for(let e=0;e<=1+Z;e+=Z)for(let t=0;t<=1+Z;t+=Z){if(E>K)break e;if(h++,h>Y)continue e;1-e>t?(g=k.a,x=k.b,S=k.c,L=F.a,$=F.b,C=F.c,v=c[0],A=c[1],z=c[2]):(g=D.a,x=D.b,S=D.c,L=X.a,$=X.b,C=X.c,v=c[1],A=c[2],z=c[3]),d.a.copy(g),d.b.copy(x),d.c.copy(S),G(d),T.set(w.x,0,w.z),U(d,T),d.getBarycoord(T,i).toArray(V),j[0]=v,j[1]=A,j[2]=z;if(B(j,V,.2)!==n-1)continue;if(M([g,x,S],V,q),M([L,$,C],V,I),null!=l.maxSlope&&l.maxSlope<90&&I.y<_)continue;const o=q;o.y+=O(l.offsetMin,l.offsetMax);const a=O(l.scaleMin??1,l.scaleMax??1);s.makeScale(a,a,a);const r=s.elements;r[12]=o.x,r[13]=o.y,r[14]=o.z,!1!==l.randomRotation&&N(s,a),l.alignToNormal&&W(s,o,m.matrixWorld,I);const u=m.instanceMatrix.array,f=16*E;u[f]=r[0],u[f+1]=r[1],u[f+2]=r[2],u[f+3]=r[3],u[f+4]=r[4],u[f+5]=r[5],u[f+6]=r[6],u[f+7]=r[7],u[f+8]=r[8],u[f+9]=r[9],u[f+10]=r[10],u[f+11]=r[11],u[f+12]=r[12],u[f+13]=r[13],u[f+14]=r[14],u[f+15]=r[15],E++}}m.count=E,m.instanceMatrix.needsUpdate=!0,m.position.copy(e.position),m.updateMatrix(),h.has(e.uuid)||this.landscape?.add(m),h.set(e.uuid,m),m.userData.meshConfig=l}));performance.now()}}stop(){this.view.removeOnLoop(this.onLoopHandler)}update(){this.view.camera&&(this.view.camera.getWorldPosition(this._cameraPosition),this._cameraPosition.distanceTo(this._lastUpdatePosition)>10&&(this._lastUpdatePosition.copy(this._cameraPosition),this.refreshGeometry(),this.refreshScatter(this._cameraPosition)))}clear(){this.scatterMeshes.forEach((e=>e.forEach((e=>e.parent?.remove(e)))))}createLandscapeMesh(e,t,s,n,o,i){const a=new h(t.sectionSize,t.sectionSize,t.density,t.density);a.rotateX(Math.PI/-2);const r=this.defaultLandscapeMaterial,c=new x(a,r);c.position.x=s+o*t.sectionSize,c.position.z=n+i*t.sectionSize,c.receiveShadow=!0,c.castShadow=!1,c.userData.landscape={x:o,y:i},c.x=o,c.y=i,c.name=`${o},${i}`,w(c,0,!0),w(c,4,!0);const l=e.landscape.heightMaps.find((e=>e.x===o&&e.y===i));if(null!=l&&this.applyHeightMap(a,l,t.density,1),a.computeBoundsTree(),null!=e.landscape.holes&&e.landscape.holes.length>0){const t=getHoleAttribute(c,!0);for(const s of e.landscape.holes)s.m===c.name&&t.setX(s.i,s.w[0])}return c}}export function getHoleAttribute(e,t=!1){if(!e.geometry.hasAttribute("hole")||t){const t=new Float32Array(e.geometry.getAttribute("position").array.length);e.geometry.setAttribute("hole",new n(t,1))}return e.geometry.getAttribute("hole")}function P(e,t,s){const n=Math.sqrt(t),o=Math.floor(e/n)/(n-1),i=e%n/(n-1),a=Math.sqrt(s);return(s-1)*o-(a-1)*o+(a-1)*i}new Map,new m(0,0),new m(1,0),new m(0,1),new m(1,0),new m(0,1),new m(1,1),new p;const L=new s;function $(e,t){return function(s){return L.setFromObject(s).distanceToPoint(e)>t}}function C(e,t){return function(s){return L.setFromObject(s).distanceToPoint(e)<t}}function G(e){e.a.y=0,e.b.y=0,e.c.y=0}const j=[];function B(e,t,s=.5){const n=j;let o=-1,i=-1;for(let e=0;e<n.length;e++)if(null!=n[e])for(let a=0;a<n[e].length;a++){const r=n[e][a]*t[e];r>s&&r>i&&(i=r,o=a)}return o}function O(e,t){let s=t-e,n=q();return n*=s,n+=e,n}const _=[];let T=1e3;for(;T--;)_.push(Math.random());function q(){return++T>=_.length?_[T=0]:_[T]}const I=[];let R=20;for(;R--;)I.push((new a).makeRotationY(q()*Math.PI/2));function U(e,t){let s=q(),n=q();s+n>1&&(s=1-s,n=1-n);const o=e.a,i=e.b,a=e.c;t.x=o.x+s*(i.x-o.x)+n*(a.x-o.x),t.z=o.z+s*(i.z-o.z)+n*(a.z-o.z)}new p;new p;const k=new p,D=new p(0,1,0),H=(new a).makeRotationX(Math.PI/-2);function W(e,t,s,n){e.lookAt(k,n,D).multiply(H)}new a;function N(e,t=1){const s=(++R>=I.length?I[R=0]:I[R]).elements,n=e.elements;n[0]=s[0]*t,n[4]=s[4]*t,n[8]=s[8]*t,n[1]=s[1]*t,n[5]=s[5]*t,n[9]=s[9]*t,n[2]=s[2]*t,n[6]=s[6]*t,n[10]=s[10]*t}function F(e){const t=e.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.normalized=!0,t.needsUpdate=!0}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,7 +1,7 @@
|
|
1
1
|
import { Subject } from "rxjs";
|
2
2
|
import * as THREE from "three";
|
3
3
|
import { Euler, Material, Object3D, Scene, Vector3 } from "three";
|
4
|
-
import { ContainerInstance } from
|
4
|
+
import { ContainerInstance } from 'typedi';
|
5
5
|
import { GameComponent } from '../game-component/game-component.js';
|
6
6
|
import { BaseActor } from '../gameplay/actors/actor.js';
|
7
7
|
import { PhysicsBodyType } from '../gameplay/index.js';
|
@@ -228,6 +228,7 @@ export declare class SceneMaterializer {
|
|
228
228
|
private assets;
|
229
229
|
constructor(scene: Scene, dataProvider: SceneDataProvider, assetsService: AssetsProvider, assetManagerService: AssetResourceLoader, renderingView: RenderingView, shaders: ShaderImpl[], actorTypes: ActorImpl[], actorProvider: ActorProvider);
|
230
230
|
private refreshMaterial;
|
231
|
+
private getTopLevelActors;
|
231
232
|
get actorInstances(): BaseActor[];
|
232
233
|
/**
|
233
234
|
* Initializing textures uploads all textures in the project to the GPU.
|
@@ -249,6 +250,8 @@ export declare class SceneMaterializer {
|
|
249
250
|
* This should however be discouraged as it may not be initialised,
|
250
251
|
* especially if there is a circular dependency in which case that would
|
251
252
|
* be impossible to guarantee.
|
253
|
+
*
|
254
|
+
* Initiating top level actors by default as actors nested in prefabs are already initiated
|
252
255
|
*/
|
253
256
|
private initActorsPostInit;
|
254
257
|
private addVfxChildActors;
|
@@ -282,7 +285,7 @@ export declare class SceneMaterializer {
|
|
282
285
|
* @param anonymous If the object should be possible to select and edit
|
283
286
|
* @returns
|
284
287
|
*/
|
285
|
-
materialize(source: SceneObject, parent?: Object3D, anonymous?: boolean): Promise<Object3D>;
|
288
|
+
materialize(source: SceneObject, parent?: Object3D, anonymous?: boolean, context?: MaterializeContext): Promise<Object3D>;
|
286
289
|
private pmremGenerator?;
|
287
290
|
private pmremGeneratorResults;
|
288
291
|
private updateWorldEnv;
|
@@ -290,8 +293,18 @@ export declare class SceneMaterializer {
|
|
290
293
|
private updateSky;
|
291
294
|
private createComponent;
|
292
295
|
private createFromActor;
|
296
|
+
/**
|
297
|
+
* Each prefab instance is defined by a unique chain if ids.
|
298
|
+
* The first element in the chain is
|
299
|
+
*
|
300
|
+
* scene (initial materializer call) -> prefab scene object id -> prefab scene object id nested ...
|
301
|
+
* runtime prefab instance id -> prefab scene object id nested ...
|
302
|
+
*
|
303
|
+
* When resolving actor references, we have to prefix the current chain with the source id
|
304
|
+
*/
|
305
|
+
private prefabInstanceChain;
|
306
|
+
private getNestedActorId;
|
293
307
|
private createFromVfx;
|
294
|
-
cleanup(): void;
|
295
308
|
private createFromShape;
|
296
309
|
private createLandscape;
|
297
310
|
private applyHeightMaps;
|
@@ -299,7 +312,17 @@ export declare class SceneMaterializer {
|
|
299
312
|
private collisionShapeCache;
|
300
313
|
private createMeshByShape;
|
301
314
|
private createFromAsset;
|
302
|
-
private
|
315
|
+
private createFromPrefab;
|
316
|
+
/**
|
317
|
+
*
|
318
|
+
* @param asset
|
319
|
+
* @param instanceId A unique ID added to the stack of prefab ids
|
320
|
+
* @returns
|
321
|
+
*/
|
322
|
+
createFromPrefabAsset(asset: Asset, context: MaterializeContext): Promise<{
|
323
|
+
object: Object3D;
|
324
|
+
actors: BaseActor[];
|
325
|
+
}>;
|
303
326
|
private createParticleSystem;
|
304
327
|
private createLight;
|
305
328
|
private applyDirectionalAmbientLight;
|
@@ -328,5 +351,8 @@ export declare function prepareCustomParamsFromType<T>(type: Type<T>, previous:
|
|
328
351
|
export declare function serializeCustomParameter(type: ParameterType, value: unknown): unknown;
|
329
352
|
export declare const customParameterDefaultValueByType: Map<SerializedParamType, any>;
|
330
353
|
export declare function applyMaterial(object: Object3D, assignment: MaterialAssignment, materialProvider: (id: AssetId) => Promise<Material>, _originalMaterials?: Map<string | number, THREE.Material>): Promise<void[]>;
|
354
|
+
type MaterializeContext = {
|
355
|
+
sceneObjectChain: SceneObjectId[];
|
356
|
+
};
|
331
357
|
export {};
|
332
358
|
//# sourceMappingURL=materializer.d.ts.map
|