@hology/core 0.0.209 → 0.0.211

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.
Files changed (46) hide show
  1. package/dist/data/surface-definition.d.ts +3 -0
  2. package/dist/data/surface-definition.js +4 -0
  3. package/dist/effects/sequence/sequence-player.js +1 -1
  4. package/dist/effects/vfx/vfx-materializer.js +1 -1
  5. package/dist/gameplay/actors/builtin/components/character/character-movement.js +1 -1
  6. package/dist/gameplay/actors/builtin/navmesh-actor.js +1 -1
  7. package/dist/gameplay/services/physics/abstract-physics-system.d.ts +1 -1
  8. package/dist/gameplay/services/physics/physics-system.d.ts +2 -1
  9. package/dist/gameplay/services/physics/physics-system.js +1 -1
  10. package/dist/index.d.ts +2 -0
  11. package/dist/index.js +1 -1
  12. package/dist/rendering.js +1 -1
  13. package/dist/scene/batched-mesh-2.d.ts +2 -0
  14. package/dist/scene/batched-mesh-2.js +1 -1
  15. package/dist/scene/custom-param-runtime-types.js +1 -1
  16. package/dist/scene/landscape/landscape-manager.d.ts +2 -1
  17. package/dist/scene/landscape/landscape-manager.js +1 -1
  18. package/dist/scene/materializer.d.ts +48 -1
  19. package/dist/scene/materializer.js +1 -1
  20. package/dist/scene/model.d.ts +3 -0
  21. package/dist/scene/scatter/painted-scatter-manager.d.ts +45 -0
  22. package/dist/scene/scatter/painted-scatter-manager.js +4 -0
  23. package/dist/scene/scatter/scatter-limits.d.ts +2 -0
  24. package/dist/scene/scatter/scatter-limits.js +4 -0
  25. package/dist/scene/scatter/surface-scatter-manager.js +1 -1
  26. package/dist/scene/storage/storage.js +1 -1
  27. package/dist/scene/surface-query.d.ts +4 -0
  28. package/dist/scene/surface-query.js +4 -0
  29. package/dist/shader/builtin/landscape-composite-shader.d.ts +1 -0
  30. package/dist/shader/builtin/landscape-composite-shader.js +1 -1
  31. package/dist/shader/builtin/standard-shader.js +1 -1
  32. package/dist/shader/graph/compiler.d.ts +7 -4
  33. package/dist/shader/graph/compiler.js +1 -1
  34. package/dist/shader/graph/model.d.ts +1 -1
  35. package/dist/shader/graph/model.js +1 -1
  36. package/dist/shader/graph/parameters.js +1 -1
  37. package/dist/shader/sprite-shader.js +1 -1
  38. package/dist/test/material-assignment.test.js +1 -1
  39. package/dist/test/materializer-prefetch.test.js +1 -1
  40. package/dist/test/painted-scatter-manager.test.d.ts +2 -0
  41. package/dist/test/painted-scatter-manager.test.js +4 -0
  42. package/dist/test/runtime-param-type-inference.test.js +1 -1
  43. package/dist/test/sequence-post-process.test.js +1 -1
  44. package/dist/test/shader-graph.test.js +1 -1
  45. package/package.json +2 -2
  46. 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 l,takeUntil as c}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 b,Vector3 as B}from"three";import{Service as v}from"typedi";import{AssetMeshInstance as C}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as A,CapsuleCollisionShape as S,ConeCollisionShape as R,ConvexPolyhedronCollisionShape as D,CylinderCollisionShape as z,PhysicalShapeMesh as T,PlaneCollisionShape as E,SphereCollisionShape as M,toInstancedCollisionShape as P,TrimeshCollisionShape as F}from"../../../index.js";import{LandscapeGroup as I}from"../../../scene/landscape/landscape.js";import{ViewController as V}from"../render.js";import{World as _}from"../world.js";import*as k from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as j}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as N}from"./abstract-physics-system.js";import{ActorComponent as W,Component as L}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 class ShapeCastResult{constructor(){this.hasHit=!1,this.hitPoint=new B,this.normal=new B}reset(){this.actor=void 0,this.hasHit=!1,this.distance=0,this.hitPoint.set(0,0,0),this.normal.set(0,0,0)}}ShapeCastResult.shared=new ShapeCastResult;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={}));const G=new B,K=new B,U=new w,q=new w,H=(new w,[]);let Q=class extends N{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(){super(),this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.colliders=new Map,this.collisionEvents=new l,this.beforeStep=new l,this.afterStep=new l,this.shouldRenderDebug=!1,this.viewController=O(V),this.shapeCacheBox=new Map,this.shapeCacheBall=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()}getBallShape(t){let e=this.shapeCacheBall.get(t);return null==e&&(e=new i.Ball(t),this.shapeCacheBall.set(t,e)),e}getBoxShape(t,e,s){const o=t+1e6*e+1e12*s;let n=this.shapeCacheBox.get(o);return null==n&&(n=new i.Cuboid(t,e,s),this.shapeCacheBox.set(o,n)),n}hasBoxIntersection(t){const e=t.getCenter(G),i=t.getSize(K),s=this.getBoxShape(i.x/2,i.y/2,i.z/2);return null!=this.world.intersectionWithShape(e,U,s)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,U,e)}findActorsInRadius(t,e,i){const s=this.getBallShape(e),o=[];for(const[e,n]of this.bodyActors)if(n instanceof i||null==i)for(let i=0,r=e.numColliders();i<r;i++){e.collider(i).intersectsShape(s,t,U)&&o.push(n)}return o}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.handleCollisionEvents(),this.ready}handleCollisionEvents(){this.collisionSub=this.collisionEvents.subscribe(t=>{const e=this.colliders.get(t.handle1);if(null==e)return;const i=this.world.getCollider(t.handle2);if(null==i||null==i.parent())return;const s=this.bodyActors.get(i.parent());null!=s&&(t.started?e.onBeginOverlapActor.next({actor:s}):e.onEndOverlapActor.next({actor:s}))})}renderDebug(){if(null==this.scene)return;null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.scene?.add(this.debugMesh));const t=this.world.debugRender().vertices,e=this.debugMesh.geometry,i=e.getAttribute("position");null==i||(i.array.length,t.length);{const i=new u(t,3);i.setUsage(d.DynamicDrawUsage),e.setAttribute("position",i)}e.setDrawRange(0,t.length/3)}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await at(),this.eventQueue=new this.rapier.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;null!=e&&e.parent instanceof b&&(dt(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&ht(e.quaternion,t.rotation()),e.matrixWorldNeedsUpdate=!0)}),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(ot,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;lt(ft.origin,t),lt(ft.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(ft,r,!1,void 0,s?.collisionFilter,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=ft.pointAt(a.timeOfImpact);if(i._internal=a,dt(i.hitNormal,a.normal),dt(i.hitPoint,e),i.distance=yt.subVectors(i.hitPoint,t).length(),!1!==s?.resolveActor){const t=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!=t?this.bodyActors.get(t):null}}if(this.showDebug){let e;H.length>0?(e=H.pop(),e.setDirection(n),e.position.copy(t),e.setLength(r,.2,.1),e.setColor(s?.debugColor??255)):e=new h(n,t,r,s?.debugColor??255),this.scene?.add(e),setTimeout(()=>{this.scene?.remove(e),H.push(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 Z.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())ut(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 T&&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 C){const e=!1!==t.userData?.src?.collisionDetection;if(t.children[0]&&(t.children[0].instanceMatrix&&e||t.children[0].isBatchedMesh))this.createForInstancedMesh(t.children[0],t.collisionShapes);else if(e&&t.children.length>0){const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}}else t instanceof I?this.addLandscapeGroup(t):(t instanceof p||t instanceof b)&&t.children.forEach(t=>this.addRecursively(t))}createForInstancedMesh(t,e){const i=new m;if(t instanceof d.BatchedMesh){const e=t._instanceInfo??t._drawInfo,s=new Map;for(let o=0;o<e.length;o++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[o])continue;const e=t.userData.collisionShapes;let n=e?.[o];if(null==n&&null==e&&t.parent instanceof C&&(n=t.parent.collisionShapes),null==n)continue;let r=s.get(n);null==r&&(r=this.instancedShapeReset(n),s.set(n,r));const a=new f;a.matrix.identity(),t.getMatrixAt(o,i),a.applyMatrix4(i);this.createStaticBody(a,r)}}else{const s=this.instancedShapeReset(e);for(let e=0;e<t.count;e++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[e])continue;const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*e),o.applyMatrix4(i);this.createStaticBody(o,s)}}}instancedShapeReset(t){return t.filter(t=>null!=t).map(t=>P(t))}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,gt);const a=e.computedMovement();return dt(pt,a),pt}createCollider(t,e){const i=this.addShape(e?.body,t),s=new PhysicsCollider(i,this.world);return this.colliders.set(i.handle,s),s.disposed.subscribe(()=>{this.colliders.delete(i.handle)}),s}createBody(t=PhysicsBodyType.dynamic,e={}){const s=(()=>{switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyDesc.dynamic();case PhysicsBodyType.static:return i.RigidBodyDesc.fixed();case PhysicsBodyType.kinematic:return i.RigidBodyDesc.kinematicPositionBased();case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyDesc.kinematicVelocityBased();default:return i.RigidBodyDesc.dynamic()}})();e.position&&s.setTranslation(e.position.x,e.position.y,e.position.z),e.rotation&&s.setRotation({x:e.rotation.x,y:e.rotation.y,z:e.rotation.z,w:e.rotation.w}),"boolean"==typeof e.canSleep&&s.setCanSleep(e.canSleep),"boolean"==typeof e.ccdEnabled&&s.setCcdEnabled(e.ccdEnabled),"number"==typeof e.gravityScale&&s.setGravityScale(e.gravityScale),"number"==typeof e.mass&&s.setAdditionalMass(e.mass),void 0!==e.userData&&(s.userData=e.userData);const o=this.world.createRigidBody(s);return new PhysicsBody(o,this.world)}getCharacterComputedMovement(t,e,i,o=null){const n=t.collider;e.computeColliderMovement(n,i,s.EXCLUDE_SENSORS,o,gt);const r=e.computedMovement();return dt(pt,r),pt}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)}setNextKinematicPosition(t,e){this.actorBodies.get(t.id).setNextKinematicTranslation(e)}setNextKinematicRotation(t,e){this.actorBodies.get(t.id).setNextKinematicRotation(e)}setNextKinematicTransform(t){!function(t,e){const i=e.getWorldPosition($),s=e.getWorldQuaternion(X);t.setNextKinematicTranslation(nt(i)),t.setNextKinematicRotation(rt(s))}(this.actorBodies.get(t.id),t.object)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.setAngvel(et,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.setLinvel(et,!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)}getLienarDamping(t){const e=this.actorBodies.get(t.id);return e?.linearDamping()??0}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}getAngularDamping(t){const e=this.actorBodies.get(t.id);e?.angularDamping()}setPosition(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(nt(e),!1)}getPosition(t,e=new B){const i=this.actorBodies.get(t.id);i&&dt(e,i.translation())}setRotation(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(rt(e),!1)}getRotation(t,e=new w){const i=this.actorBodies.get(t.id);i&&ht(e,i.rotation())}lockTranslations(t,e){const i=this.actorBodies.get(t.id);i?.lockTranslations(e,!1)}lockRotations(t,e){const i=this.actorBodies.get(t.id);i?.lockRotations(e,!1)}setEnabledTranslations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledTranslations(e,i,s,!1)}setEnabledRotations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledRotations(e,i,s,!1)}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(),i=n.scale,s=n.geometry.getAttribute("hole"),r=new Float32Array(t.getAttribute("position").array);for(let t=0;t<r.length;t+=3)r[t]*=i.x,r[t+1]*=i.y,r[t+2]*=i.z;const a=t.index;for(let t=0;t<a.count;t+=3){const e=s.getX(a.getX(t)),i=s.getX(a.getY(t)),o=s.getX(a.getZ(t));(e>.5||i>.5||o>.5)&&(a.setX(t,0),a.setY(t,0),a.setZ(t,0))}const l=this.rapier.ColliderDesc.trimesh(r,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(this.rapier.RigidBodyDesc.fixed()),e=new this.rapier.Vector3(0,0,0);lt(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 l=s.find(t=>t.x===n.x&&t.y==n.y);if(null!=l)for(const e of l.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:l})}const c=e.landscape.options.density,d=a.flatMap(t=>t.reverse()),h=i.ColliderDesc.heightfield(c,c,new Float32Array(d),new i.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(this.rapier.RigidBodyDesc.fixed()),e=new this.rapier.Vector3(0,0,0);lt(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);return ut(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)}),Y(r,o),!0===s.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,r),this.bodyActors.set(r,t),new PhysicsBody(r,this.world)}applyTorque(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.addTorque(et,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.applyTorqueImpulse(et,!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);et.x=e.x,et.y=e.y,et.z=e.z,i?.addForce(et,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.applyImpulse(et,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);lt(et,e),null==i?s?.addForce(et,!0):(lt(it,i),s?.addForceAtPoint(et,it,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);lt(et,e),null==i?s.applyImpulse(et,!0):(lt(it,i),s.applyImpulseAtPoint(et,it,!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=st;dt(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);et.x=a.x,et.y=a.y,et.z=a.z,o.applyImpulse(et,!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){if(null==t)return;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 I){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(c(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(c(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(c(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&&Y(e,t.object)}setupWorld(){const t=new this.rapier.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,i,s,o=ShapeCastResult.shared,n){o.reset();const r=this.getBallShape(e);this.shapeCacheBall.get;const a={x:t.x,y:t.y,z:t.z},l={x:i.x,y:i.y,z:i.z},c=n?.excludeActor?this.actorBodies.get(n.excludeActor.id):null,d=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n?.collisionFilter??void 0,null,c,n?.excludeTriggers?t=>!t.isSensor():void 0);if(null!=d){dt(o.hitPoint,d.witness1),o.normal.set(d.normal1.x,d.normal1.y,d.normal1.z),o.distance=d.time_of_impact,o.hasHit=!0;const t=d.collider.parent();if(t){const e=this.bodyActors.get(t);e&&(o.actor=e)}}return o}castActorShape(t,e,i,s=ShapeCastResult.shared,o=void 0){s.reset();const n=this.actorBodies.get(t.id);if(n&&n.numColliders()>0){for(let t=0;t<n.numColliders();t++){const r=n.collider(t);let a=r.shape,l=r.translation(),c=r.rotation(),d=e,h=i;const u=this.world.castShape(l,c,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=u){u.collider;const t=r;return dt(s.hitPoint,u.witness1),xt(t.rotation(),u.normal1,s.normal,q),s.distance=u.time_of_impact,s.actor=this.bodyActors.get(u.collider.parent()),s.hasHit=!0,s}}return s}return console.warn("Actor is not added to the physics system"),s}stop(){this.world?.bodies.forEach(t=>this.world.removeRigidBody(t)),this.world?.free(),this.fixedupdateSub?.unsubscribe(),this.collisionSub?.unsubscribe(),H.length=0}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed();o.setSleeping(!0);const n=this.world.createRigidBody(o);let r=0;for(const i of e){if(r>128){console.warn("Too many collision shapes for object",t);break}if(r++,null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=o&&(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 Y(n,t),n.userData=t.uuid,n.sleep(),n}addShape(t=void 0,e,i){const s=i?.getWorldScale(mt)??tt,o=this.createShape(e,s);if(null==o)return void console.error("Failed to create physics shape. This can happen if the geometry is degenerate or zero-scaled.",{shapeInfo:e,object:i});this.applyShapeSettings(o,e);const n=e.offset.clone().multiply(s);lt(o.translation,n);const r=(new w).setFromEuler(e.rotation);ct(o.rotation,r),null!=t&&t.numColliders()>128&&console.warn(`Rigid body has many colliders (${t.numColliders()}). Consider using a Trimesh if this is static geometry.`,t);try{return this.world.createCollider(o,t)}catch(t){return void console.error("Failed to create collider",t)}}applyShapeSettings(t,e){null!=e.collisionGroup&&t.setCollisionGroups(e.collisionGroup),t.friction=e.friction??.1,null!=e.restitution&&(t.restitution=e.restitution),null!=e.density&&(t.density=e.density,t.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(t.mass=e.mass,t.massPropsMode=i.MassPropsMode.Mass)}createShape(t,e){if(t instanceof A)return this.rapier.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof S){return this.rapier.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof F){const i=null!=t.geometry.getIndex()?t.geometry:k.mergeVertices(t.geometry),s=extractFloat32Array(i.getAttribute("position"));for(let t=0;t<s.length;t+=3)s[t]*=e.x,s[t+1]*=e.y,s[t+2]*=e.z;const o=i.getIndex();return null==o?(console.error("Trimesh collision shape is missing an index buffer.",t),null):this.rapier.ColliderDesc.trimesh(s,new Uint32Array(o.array))}if(t instanceof D){let i,s;t.mesh instanceof d.Mesh?i=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?i=t.mesh:console.log("Unknownd shape",{shapeInfo:t}),t.mesh instanceof d.Mesh&&(s=j(t.mesh));const o=`${i.uuid}|${s?.x??1},${s?.y??1},${s?.z??1}|${e.x},${e.y},${e.z}`,n=J.get(o);if(void 0!==n)return n;const r=extractFloat32Array(i.getAttribute("position"));if(null!=s)for(let t=0;t<r.length;t+=3)r[t]*=s.x,r[t+1]*=s.y,r[t+2]*=s.z;for(let t=0;t<r.length;t+=3)r[t]*=e.x,r[t+1]*=e.y,r[t+2]*=e.z;const a=this.rapier.ColliderDesc.convexHull(r);return null==a&&console.error("Failed to compute convex hull. Points may be coplanar or too few.",{count:r.length/3}),J.set(o,a),a}if(t instanceof M){const i=2*e.x-e.y-e.z;return Math.abs(i)>.01?this.createShape(new D(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new B(1,1,1)):this.rapier.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof z?this.rapier.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof R?this.rapier.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof E?this.rapier.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),this.rapier.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new this.rapier.CharacterCollision}};Q=t([v(),e("design:paramtypes",[])],Q);export{Q as PhysicsSystem};const $=new B,X=new d.Quaternion;function Y(t,e){const i=e.getWorldPosition($),s=e.getWorldQuaternion(X);t.setTranslation(nt(i),!1),t.setRotation(rt(s),!1)}const Z=new B,J=new Map,tt=new B(1,1,1),et=new i.Vector3(0,0,0),it=new i.Vector3(0,0,0),st=new B,ot=new d.Vector2;function nt(t){return lt(et,t),et}function rt(t){return ct(q,t),q}const at=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function lt(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function ct(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function dt(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function ht(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function ut(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const yt=new B,pt=new B,gt=t=>!t.isSensor(),mt=new B;const ft=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));let wt=class extends W{constructor(){super(...arguments),this._active=!0,this.physics=O(Q),this.world=O(_)}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}};wt=t([L()],wt);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}function xt(t,e,i,s){return s.set(t.x,t.y,t.z,t.w),i.set(e.x,e.y,e.z),i.applyQuaternion(s),i}export class PhysicsCollider{constructor(t,e){this.collider=t,this.world=e,this.disposed=new l,this.onBeginOverlapActor=new l,this.onEndOverlapActor=new l}dispose(){this.world.removeCollider(this.collider,!1),this.disposed.next(!0),this.disposed.complete(),this.onBeginOverlapActor.complete(),this.onEndOverlapActor.complete()}set mass(t){this.collider.setMass(t)}get mass(){return this.collider.mass()}set friction(t){this.collider.setFriction(t)}get friction(){return this.collider.friction()}set restitution(t){this.collider.setRestitution(t)}get restitution(){return this.collider.restitution()}set density(t){this.collider.setDensity(t)}get density(){return this.collider.density()}set isTrigger(t){this.collider.setSensor(t)}get isTrigger(){return this.collider.isSensor()}set collisionGroups(t){this.collider.setCollisionGroups(t)}get collisionGroups(){return this.collider.collisionGroups()}set enabled(t){this.collider.setEnabled(t)}get enabled(){return this.collider.isEnabled()}}export class PhysicsBody{constructor(t,e){this.body=t,this.world=e}dispose(){this.world.removeRigidBody(this.body)}setEnabled(t){this.body.setEnabled(t)}isEnabled(){return this.body.isEnabled()}getPosition(t){const e=this.body.translation();return t.set(e.x,e.y,e.z),t}setPosition(t){this.body.setTranslation({x:t.x,y:t.y,z:t.z},!0)}getRotation(t){const e=this.body.rotation();return t.set(e.x,e.y,e.z,e.w),t}setRotation(t){this.body.setRotation({x:t.x,y:t.y,z:t.z,w:t.w},!0)}getLinearVelocity(t){const e=this.body.linvel();return t.set(e.x,e.y,e.z),t}setLinearVelocity(t){this.body.setLinvel({x:t.x,y:t.y,z:t.z},!0)}getAngularVelocity(t){const e=this.body.angvel();return t.set(e.x,e.y,e.z),t}setAngularVelocity(t){this.body.setAngvel({x:t.x,y:t.y,z:t.z},!0)}applyImpulse(t,e=!0){this.body.applyImpulse({x:t.x,y:t.y,z:t.z},e)}applyTorqueImpulse(t,e=!0){this.body.applyTorqueImpulse({x:t.x,y:t.y,z:t.z},e)}setNextKinematicPosition(t){this.body.setNextKinematicTranslation(t)}setNextKinematicRotation(t){this.body.setNextKinematicRotation(t)}setType(t){this.body.setBodyType(function(t){switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyType.Dynamic;case PhysicsBodyType.static:return i.RigidBodyType.Fixed;case PhysicsBodyType.kinematic:return i.RigidBodyType.KinematicPositionBased;case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyType.KinematicVelocityBased}}(t),t!==PhysicsBodyType.static)}setGravityScale(t){this.body.setGravityScale(t,!1)}getGravityScale(){return this.body.gravityScale()}isDynamic(){return this.body.isDynamic()}isKinematic(){return this.body.isKinematic()}isStatic(){return this.body.isFixed()}sleep(){this.body.sleep()}wakeUp(){this.body.wakeUp()}}/*
1
+ import{__decorate as t,__metadata as e}from"tslib";import*as i from"@dimforge/rapier3d-simd-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-simd-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as l,takeUntil as c}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 B,Vector3 as b}from"three";import{Service as v}from"typedi";import{AssetMeshInstance as C}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as S,CapsuleCollisionShape as A,ConeCollisionShape as R,ConvexPolyhedronCollisionShape as D,CylinderCollisionShape as z,PhysicalShapeMesh as T,PlaneCollisionShape as E,SphereCollisionShape as M,toInstancedCollisionShape as P,TrimeshCollisionShape as _}from"../../../index.js";import{LandscapeGroup as F}from"../../../scene/landscape/landscape.js";import{ViewController as I}from"../render.js";import{World as V}from"../world.js";import*as k from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as j}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as N}from"./abstract-physics-system.js";import{ActorComponent as W,Component as L}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 class ShapeCastResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.normal=new b}reset(){this.actor=void 0,this.hasHit=!1,this.distance=0,this.hitPoint.set(0,0,0),this.normal.set(0,0,0)}}ShapeCastResult.shared=new ShapeCastResult;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={}));const G=new b,K=new b,U=new w,q=new w,H=(new w,[]);let Q=class extends N{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(){super(),this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.colliders=new Map,this.collisionEvents=new l,this.beforeStep=new l,this.afterStep=new l,this.shouldRenderDebug=!1,this.viewController=O(I),this.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new x,this._reusableResult=new RayTestResult,this._raytestDiff=new b,this._raytestDirection=new b,this.controlledActors=new Set,this._isStopped=!1,this.ready=this.setup()}getBallShape(t){let e=this.shapeCacheBall.get(t);return null==e&&(e=new this.rapier.Ball(t),this.shapeCacheBall.set(t,e)),e}getBoxShape(t,e,i){const s=t+1e6*e+1e12*i;let o=this.shapeCacheBox.get(s);return null==o&&(o=new this.rapier.Cuboid(t,e,i),this.shapeCacheBox.set(s,o)),o}hasBoxIntersection(t){const e=t.getCenter(G),i=t.getSize(K),s=this.getBoxShape(i.x/2,i.y/2,i.z/2);return null!=this.world.intersectionWithShape(e,U,s)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,U,e)}findActorsInRadius(t,e,i){const s=this.getBallShape(e),o=[];for(const[e,n]of this.bodyActors)if(n instanceof i||null==i)for(let i=0,r=e.numColliders();i<r;i++){e.collider(i).intersectsShape(s,t,U)&&o.push(n)}return o}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.handleCollisionEvents(),this.ready}handleCollisionEvents(){this.collisionSub=this.collisionEvents.subscribe(t=>{const e=this.colliders.get(t.handle1);if(null==e)return;const i=this.world.getCollider(t.handle2);if(null==i||null==i.parent())return;const s=this.bodyActors.get(i.parent());null!=s&&(t.started?e.onBeginOverlapActor.next({actor:s}):e.onEndOverlapActor.next({actor:s}))})}renderDebug(){if(null==this.scene)return;null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.scene?.add(this.debugMesh));const t=this.world.debugRender().vertices,e=this.debugMesh.geometry,i=e.getAttribute("position");null==i||(i.array.length,t.length);{const i=new u(t,3);i.setUsage(d.DynamicDrawUsage),e.setAttribute("position",i)}e.setDrawRange(0,t.length/3)}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await lt(),this.eventQueue=new this.rapier.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe(t=>{this._isStopped||(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;null!=e&&e.parent instanceof B&&(ht(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&ut(e.quaternion,t.rotation()),e.matrixWorldNeedsUpdate=!0)}),this.afterStep.next(t))})}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this._isStopped||(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(ot,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;null==wt&&(wt=new this.rapier.Ray(new this.rapier.Vector3(0,0,0),new this.rapier.Vector3(0,1,0))),ct(wt.origin,t),ct(wt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(wt,r,!1,void 0,s?.collisionFilter,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=wt.pointAt(a.timeOfImpact);if(i._internal=a,ht(i.hitNormal,a.normal),ht(i.hitPoint,e),i.distance=pt.subVectors(i.hitPoint,t).length(),!1!==s?.resolveActor){const t=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!=t?this.bodyActors.get(t):null}}if(this.showDebug){let e;H.length>0?(e=H.pop(),e.setDirection(n),e.position.copy(t),e.setLength(r,.2,.1),e.setColor(s?.debugColor??255)):e=new h(n,t,r,s?.debugColor??255),this.scene?.add(e),setTimeout(()=>{this.scene?.remove(e),H.push(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 Z.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())yt(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 T&&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 C){const e=!1!==t.userData?.src?.collisionDetection;if(t.children[0]&&(t.children[0].instanceMatrix&&e||t.children[0].isBatchedMesh))this.createForInstancedMesh(t.children[0],t.collisionShapes);else if(e&&t.children.length>0){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 B)&&t.children.forEach(t=>this.addRecursively(t))}createForInstancedMesh(t,e){const i=new m;if(t instanceof d.BatchedMesh){const e=t._instanceInfo??t._drawInfo,s=new Map;for(let o=0;o<e.length;o++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[o])continue;const e=t.userData.collisionShapes;let n=e?.[o];if(null==n&&null==e&&t.parent instanceof C&&(n=t.parent.collisionShapes),null==n)continue;let r=s.get(n);null==r&&(r=this.instancedShapeReset(n),s.set(n,r));const a=new f;a.matrix.identity(),t.getMatrixAt(o,i),a.applyMatrix4(i);this.createStaticBody(a,r)}}else{const s=this.instancedShapeReset(e);for(let e=0;e<t.count;e++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[e])continue;const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*e),o.applyMatrix4(i);this.createStaticBody(o,s)}}}instancedShapeReset(t){return t.filter(t=>null!=t).map(t=>P(t))}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,mt);const a=e.computedMovement();return ht(gt,a),gt}createCollider(t,e){const i=this.addShape(e?.body,t),s=new PhysicsCollider(i,this.world);return this.colliders.set(i.handle,s),s.disposed.subscribe(()=>{this.colliders.delete(i.handle)}),s}createBody(t=PhysicsBodyType.dynamic,e={}){const i=(()=>{switch(t){case PhysicsBodyType.dynamic:return this.rapier.RigidBodyDesc.dynamic();case PhysicsBodyType.static:return this.rapier.RigidBodyDesc.fixed();case PhysicsBodyType.kinematic:return this.rapier.RigidBodyDesc.kinematicPositionBased();case PhysicsBodyType.kinematicVelocityBased:return this.rapier.RigidBodyDesc.kinematicVelocityBased();default:return this.rapier.RigidBodyDesc.dynamic()}})();e.position&&i.setTranslation(e.position.x,e.position.y,e.position.z),e.rotation&&i.setRotation({x:e.rotation.x,y:e.rotation.y,z:e.rotation.z,w:e.rotation.w}),"boolean"==typeof e.canSleep&&i.setCanSleep(e.canSleep),"boolean"==typeof e.ccdEnabled&&i.setCcdEnabled(e.ccdEnabled),"number"==typeof e.gravityScale&&i.setGravityScale(e.gravityScale),"number"==typeof e.mass&&i.setAdditionalMass(e.mass),void 0!==e.userData&&(i.userData=e.userData);const s=this.world.createRigidBody(i);return new PhysicsBody(s,this.world)}getCharacterComputedMovement(t,e,i,o=null){const n=t.collider;e.computeColliderMovement(n,i,s.EXCLUDE_SENSORS,o,mt);const r=e.computedMovement();return ht(gt,r),gt}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)}setNextKinematicPosition(t,e){this.actorBodies.get(t.id).setNextKinematicTranslation(e)}setNextKinematicRotation(t,e){this.actorBodies.get(t.id).setNextKinematicRotation(e)}setNextKinematicTransform(t){!function(t,e){const i=e.getWorldPosition($),s=e.getWorldQuaternion(X);t.setNextKinematicTranslation(nt(i)),t.setNextKinematicRotation(rt(s))}(this.actorBodies.get(t.id),t.object)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.setAngvel(et,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.setLinvel(et,!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)}getLienarDamping(t){const e=this.actorBodies.get(t.id);return e?.linearDamping()??0}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}getAngularDamping(t){const e=this.actorBodies.get(t.id);e?.angularDamping()}setPosition(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(nt(e),!1)}getPosition(t,e=new b){const i=this.actorBodies.get(t.id);i&&ht(e,i.translation())}setRotation(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(rt(e),!1)}getRotation(t,e=new w){const i=this.actorBodies.get(t.id);i&&ut(e,i.rotation())}lockTranslations(t,e){const i=this.actorBodies.get(t.id);i?.lockTranslations(e,!1)}lockRotations(t,e){const i=this.actorBodies.get(t.id);i?.lockRotations(e,!1)}setEnabledTranslations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledTranslations(e,i,s,!1)}setEnabledRotations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledRotations(e,i,s,!1)}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(),i=n.scale,s=n.geometry.getAttribute("hole"),r=new Float32Array(t.getAttribute("position").array);for(let t=0;t<r.length;t+=3)r[t]*=i.x,r[t+1]*=i.y,r[t+2]*=i.z;const a=t.index;for(let t=0;t<a.count;t+=3){const e=s.getX(a.getX(t)),i=s.getX(a.getY(t)),o=s.getX(a.getZ(t));(e>.5||i>.5||o>.5)&&(a.setX(t,0),a.setY(t,0),a.setZ(t,0))}const l=this.rapier.ColliderDesc.trimesh(r,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(this.rapier.RigidBodyDesc.fixed()),e=new this.rapier.Vector3(0,0,0);ct(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 l=s.find(t=>t.x===n.x&&t.y==n.y);if(null!=l)for(const e of l.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:l})}const c=e.landscape.options.density,d=a.flatMap(t=>t.reverse()),h=i.ColliderDesc.heightfield(c,c,new Float32Array(d),new this.rapier.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(this.rapier.RigidBodyDesc.fixed()),e=new this.rapier.Vector3(0,0,0);ct(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,i={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const s=t.object;let o;switch(i.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:o=this.rapier.RigidBodyDesc.dynamic(),o.mass=i.mass??1;break;case PhysicsBodyType.kinematic:o=this.rapier.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:o=this.rapier.RigidBodyDesc.kinematicVelocityBased();break;default:o=i.isTrigger?this.rapier.RigidBodyDesc.kinematicVelocityBased():this.rapier.RigidBodyDesc.fixed()}const n=this.world.createRigidBody(o);n.enableCcd(1==i.continousCollisionDetection);for(const t of e)this.addShape(n,t,s);return yt(n,t=>{null!=i.isTrigger&&(t.setSensor(i.isTrigger),t.setActiveCollisionTypes(this.rapier.ActiveCollisionTypes.ALL),t.setActiveEvents(this.rapier.ActiveEvents.COLLISION_EVENTS)),null!=i.friction&&t.setFriction(i.friction),null!=i.density&&t.setDensity(i.density),null!=i.mass&&t.setMass(i.mass),null!=i.restitution&&t.setRestitution(i.restitution)}),Y(n,s),!0===i.ignoreForNavMesh&&(n.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,n),this.bodyActors.set(n,t),new PhysicsBody(n,this.world)}applyTorque(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.addTorque(et,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.applyTorqueImpulse(et,!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);et.x=e.x,et.y=e.y,et.z=e.z,i?.addForce(et,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);et.x=e.x,et.y=e.y,et.z=e.z,i?.applyImpulse(et,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);ct(et,e),null==i?s?.addForce(et,!0):(ct(it,i),s?.addForceAtPoint(et,it,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);ct(et,e),null==i?s.applyImpulse(et,!0):(ct(it,i),s.applyImpulseAtPoint(et,it,!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=st;ht(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);et.x=a.x,et.y=a.y,et.z=a.z,o.applyImpulse(et,!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){if(null==t)return;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(c(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(c(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(c(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&&Y(e,t.object)}setupWorld(){const t=new this.rapier.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,i,s,o=ShapeCastResult.shared,n){o.reset();const r=this.getBallShape(e);this.shapeCacheBall.get;const a={x:t.x,y:t.y,z:t.z},l={x:i.x,y:i.y,z:i.z},c=n?.excludeActor?this.actorBodies.get(n.excludeActor.id):null,d=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n?.collisionFilter??void 0,null,c,n?.excludeTriggers?t=>!t.isSensor():void 0);if(null!=d){ht(o.hitPoint,d.witness1),o.normal.set(d.normal1.x,d.normal1.y,d.normal1.z),o.distance=d.time_of_impact,o.hasHit=!0;const t=d.collider.parent();if(t){const e=this.bodyActors.get(t);e&&(o.actor=e)}}return o}castActorShape(t,e,i,s=ShapeCastResult.shared,o=void 0){s.reset();const n=this.actorBodies.get(t.id);if(n&&n.numColliders()>0){for(let t=0;t<n.numColliders();t++){const r=n.collider(t);let a=r.shape,l=r.translation(),c=r.rotation(),d=e,h=i;const u=this.world.castShape(l,c,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=u){u.collider;const t=r;return ht(s.hitPoint,u.witness1),Bt(t.rotation(),u.normal1,s.normal,q),s.distance=u.time_of_impact,s.actor=this.bodyActors.get(u.collider.parent()),s.hasHit=!0,s}}return s}return console.warn("Actor is not added to the physics system"),s}stop(){if(!this._isStopped){this._isStopped=!0,this.bodyActors.clear(),this.actorBodies.clear(),this.staticBodies.clear(),this.staticMeshes.clear(),this.colliders.clear(),this.fixedupdateSub?.unsubscribe(),this.collisionSub?.unsubscribe(),this.world?.bodies.forEach(t=>this.world.removeRigidBody(t));try{this.world?.free(),this.world=void 0}catch(t){console.warn("Error while freeing physics world",t)}H.length=0}}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed();o.setSleeping(!0);const n=this.world.createRigidBody(o);let r=0;for(const i of e){if(r>128){console.warn("Too many collision shapes for object",t);break}if(r++,null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=o&&(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 Y(n,t),n.userData=t.uuid,n.sleep(),n}addShape(t=void 0,e,i){const s=i?.getWorldScale(ft)??tt,o=this.createShape(e,s);if(null==o)return void console.error("Failed to create physics shape. This can happen if the geometry is degenerate or zero-scaled.",{shapeInfo:e,object:i});this.applyShapeSettings(o,e);const n=e.offset.clone().multiply(s);ct(o.translation,n);const r=(new w).setFromEuler(e.rotation);dt(o.rotation,r),null!=t&&t.numColliders()>128&&console.warn(`Rigid body has many colliders (${t.numColliders()}). Consider using a Trimesh if this is static geometry.`,t);try{return this.world.createCollider(o,t)}catch(t){return void console.error("Failed to create collider",t)}}applyShapeSettings(t,e){null!=e.collisionGroup&&t.setCollisionGroups(e.collisionGroup),t.friction=e.friction??.1,null!=e.restitution&&(t.restitution=e.restitution),null!=e.density&&(t.density=e.density,t.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(t.mass=e.mass,t.massPropsMode=i.MassPropsMode.Mass)}createShape(t,e){if(t instanceof S)return this.rapier.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof A){return this.rapier.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof _){const i=null!=t.geometry.getIndex()?t.geometry:k.mergeVertices(t.geometry),s=extractFloat32Array(i.getAttribute("position"));for(let t=0;t<s.length;t+=3)s[t]*=e.x,s[t+1]*=e.y,s[t+2]*=e.z;const o=i.getIndex();return null==o?(console.error("Trimesh collision shape is missing an index buffer.",t),null):this.rapier.ColliderDesc.trimesh(s,new Uint32Array(o.array))}if(t instanceof D){let i,s;t.mesh instanceof d.Mesh?i=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?i=t.mesh:console.log("Unknownd shape",{shapeInfo:t}),t.mesh instanceof d.Mesh&&(s=j(t.mesh));const o=`${i.uuid}|${s?.x??1},${s?.y??1},${s?.z??1}|${e.x},${e.y},${e.z}`,n=J.get(o);if(void 0!==n)return n;const r=extractFloat32Array(i.getAttribute("position"));if(null!=s)for(let t=0;t<r.length;t+=3)r[t]*=s.x,r[t+1]*=s.y,r[t+2]*=s.z;for(let t=0;t<r.length;t+=3)r[t]*=e.x,r[t+1]*=e.y,r[t+2]*=e.z;const a=this.rapier.ColliderDesc.convexHull(r);return null==a&&console.error("Failed to compute convex hull. Points may be coplanar or too few.",{count:r.length/3}),J.set(o,a),a}if(t instanceof M){const i=2*e.x-e.y-e.z;return Math.abs(i)>.01?this.createShape(new D(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):this.rapier.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof z?this.rapier.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof R?this.rapier.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof E?this.rapier.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),this.rapier.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new this.rapier.CharacterCollision}};Q=t([v(),e("design:paramtypes",[])],Q);export{Q as PhysicsSystem};const $=new b,X=new d.Quaternion;function Y(t,e){const i=e.getWorldPosition($),s=e.getWorldQuaternion(X);t.setTranslation(nt(i),!1),t.setRotation(rt(s),!1)}const Z=new b,J=new Map,tt=new b(1,1,1),et=new i.Vector3(0,0,0),it=new i.Vector3(0,0,0),st=new b,ot=new d.Vector2;function nt(t){return ct(et,t),et}function rt(t){return dt(q,t),q}let at=null;const lt=async()=>(null==at&&(at=(async()=>{let t=await import("@dimforge/rapier3d-simd-compat");return await t.init(),t})()),at);function ct(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function dt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function ht(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function ut(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function yt(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const pt=new b,gt=new b,mt=t=>!t.isSensor(),ft=new b;let wt,xt=class extends W{constructor(){super(...arguments),this._active=!0,this.physics=O(Q),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}};xt=t([L()],xt);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}function Bt(t,e,i,s){return s.set(t.x,t.y,t.z,t.w),i.set(e.x,e.y,e.z),i.applyQuaternion(s),i}export class PhysicsCollider{constructor(t,e){this.collider=t,this.world=e,this.disposed=new l,this.onBeginOverlapActor=new l,this.onEndOverlapActor=new l}dispose(){this.world.removeCollider(this.collider,!1),this.disposed.next(!0),this.disposed.complete(),this.onBeginOverlapActor.complete(),this.onEndOverlapActor.complete()}set mass(t){this.collider.setMass(t)}get mass(){return this.collider.mass()}set friction(t){this.collider.setFriction(t)}get friction(){return this.collider.friction()}set restitution(t){this.collider.setRestitution(t)}get restitution(){return this.collider.restitution()}set density(t){this.collider.setDensity(t)}get density(){return this.collider.density()}set isTrigger(t){this.collider.setSensor(t)}get isTrigger(){return this.collider.isSensor()}set collisionGroups(t){this.collider.setCollisionGroups(t)}get collisionGroups(){return this.collider.collisionGroups()}set enabled(t){this.collider.setEnabled(t)}get enabled(){return this.collider.isEnabled()}}export class PhysicsBody{constructor(t,e){this.body=t,this.world=e}dispose(){this.world.removeRigidBody(this.body)}setEnabled(t){this.body.setEnabled(t)}isEnabled(){return this.body.isEnabled()}getPosition(t){const e=this.body.translation();return t.set(e.x,e.y,e.z),t}setPosition(t){this.body.setTranslation({x:t.x,y:t.y,z:t.z},!0)}getRotation(t){const e=this.body.rotation();return t.set(e.x,e.y,e.z,e.w),t}setRotation(t){this.body.setRotation({x:t.x,y:t.y,z:t.z,w:t.w},!0)}getLinearVelocity(t){const e=this.body.linvel();return t.set(e.x,e.y,e.z),t}setLinearVelocity(t){this.body.setLinvel({x:t.x,y:t.y,z:t.z},!0)}getAngularVelocity(t){const e=this.body.angvel();return t.set(e.x,e.y,e.z),t}setAngularVelocity(t){this.body.setAngvel({x:t.x,y:t.y,z:t.z},!0)}applyImpulse(t,e=!0){this.body.applyImpulse({x:t.x,y:t.y,z:t.z},e)}applyTorqueImpulse(t,e=!0){this.body.applyTorqueImpulse({x:t.x,y:t.y,z:t.z},e)}setNextKinematicPosition(t){this.body.setNextKinematicTranslation(t)}setNextKinematicRotation(t){this.body.setNextKinematicRotation(t)}setType(t){this.body.setBodyType(function(t){switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyType.Dynamic;case PhysicsBodyType.static:return i.RigidBodyType.Fixed;case PhysicsBodyType.kinematic:return i.RigidBodyType.KinematicPositionBased;case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyType.KinematicVelocityBased}}(t),t!==PhysicsBodyType.static)}setGravityScale(t){this.body.setGravityScale(t,!1)}getGravityScale(){return this.body.gravityScale()}isDynamic(){return this.body.isDynamic()}isKinematic(){return this.body.isKinematic()}isStatic(){return this.body.isFixed()}sleep(){this.body.sleep()}wakeUp(){this.body.wakeUp()}}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
package/dist/index.d.ts CHANGED
@@ -8,4 +8,6 @@ export * from './gameplay/actors/builtin/post-process-volume-actor.js';
8
8
  export * from './scene/objects/prefab.js';
9
9
  export * from './scene/objects/data-asset.js';
10
10
  export * from './effects/sequence';
11
+ export * from './data/surface-definition.js';
12
+ export * from './scene/surface-query.js';
11
13
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export{loadScene}from"./scene/bootstrap.js";export{BaseGameController}from"./controllers/base-game-controller.js";export*from"./scene/collision/collision-shape.js";export{AssetMeshInstance}from"./scene/asset-resource-loader.js";export{registerWorker,initWorker}from"./worker";export*from"./shader";export*from"./gameplay/actors/builtin/post-process-volume-actor.js";export*from"./scene/objects/prefab.js";export*from"./scene/objects/data-asset.js";export*from"./effects/sequence";/*
1
+ export{loadScene}from"./scene/bootstrap.js";export{BaseGameController}from"./controllers/base-game-controller.js";export*from"./scene/collision/collision-shape.js";export{AssetMeshInstance}from"./scene/asset-resource-loader.js";export{registerWorker,initWorker}from"./worker";export*from"./shader";export*from"./gameplay/actors/builtin/post-process-volume-actor.js";export*from"./scene/objects/prefab.js";export*from"./scene/objects/data-asset.js";export*from"./effects/sequence";export*from"./data/surface-definition.js";export*from"./scene/surface-query.js";/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
package/dist/rendering.js CHANGED
@@ -1,4 +1,4 @@
1
- var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as a,Material as n,Matrix4 as r,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as p,WebGLRenderTarget as c,Texture as u,Euler as d,MeshStandardMaterial as m}from"three";import{CopyShader as f,EffectComposer as g,FXAAShader as M,GammaCorrectionShader as v,LUTPass as P,RenderPass as y,ShaderPass as b,VRButton as w}from"three-stdlib";import{CSMShader as x,CSMUtil as T}from"./csm.js";import{colorToNormal as S,float as R,NodeShaderMaterial as C,standardMaterial as U,uniformFloat as E,uniformVec3 as A,toonMaterial as O,lambertMaterial as F,normalize as G,rgb as D,rgba as B,transformed as j,varying as I,varyingAttributes as V,varyingTransformed as L,vec4 as _,BooleanExpression as W,select as N,ifDefApply as H,uniformSampler2d as q,RgbaNode as k,mix as z,attributes as $,uniformVec2 as J}from"three-shader-graph";import{Reflector as X}from"three-stdlib";import{BokehPass as Y,OutputPass as K}from"three/examples/jsm/Addons.js";import{CSM as Q}from"three/examples/jsm/csm/CSM.js";import{RectAreaLightUniformsLib as Z}from"three/examples/jsm/lights/RectAreaLightUniformsLib.js";import ee from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as te}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as se}from"typedi";import{depthUniformName as ie,farUniformName as ae,nearUniformName as ne,resolutionUniformName as re,sceneNormalUniformName as oe,screenUV as le,supportsDepthTextureExtension as he}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as pe}from"./shader-nodes/time.js";import{aoMapUniformName as ce,sceneMapUniformName as ue}from"./shader-nodes/scene-sample.js";import{DepthPass as de}from"./utils/three/depth-pass.js";import{GPUStatsPanel as me}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as fe}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as ge,traverseVisibleStop as Me}from"./utils/three/traverse.js";import{clamp as ve}from"./utils/math.js";import{ColorPass as Pe}from"./rendering/color-pass.js";import{PostProcessEffectPass as ye,PostProcessEffectRegistration as be,postProcessEffectStages as we,sanitizePostProcessEffectPriority as xe,sanitizePostProcessEffectStage as Te}from"./rendering/post-process-effect.js";import{SSRPass as Se}from"./rendering/ssr/SSRPass.js";import{SSRShader as Re}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as Ce}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as Ue}from"./rendering/outline-effect.js";import{UnrealBloomPass as Ee}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as Ae}from"./shader-nodes/depth.js";import{packDepthToRGBA as Oe}from"three-shader-graph";import{FogVolumeObject as Fe}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Ge}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as De}from"./shader-nodes/pom.js";import{FullScreenQuad as Be}from"three-stdlib";import{edgeDepthEffect as je}from"./shader-nodes/effects";import{decalDiscard as Ie}from"./shader-nodes/decal.js";import{Pass as Ve}from"three/examples/jsm/Addons.js";import{BatchedMesh2 as Le}from"./scene/batched-mesh-2.js";import{applyUvTiling as _e}from"./shader/uv-nodes.js";import{getTemporalUpscalingJitter as We,getUpscalingMethod as Ne,UpscaleOutputPass as He}from"./rendering/upscaling-pass.js";T.patchSetupMaterial();const qe=document.createElement("div");qe.style.position="absolute",qe.style.left="50%",qe.style.top="50%",qe.style.color="black",qe.style.zIndex="999";(new i.Layers).set(9);const ke=new i.MeshBasicMaterial({color:"black"}),ze=new i.MeshDepthMaterial;var $e;ze.depthPacking=i.RGBADepthPacking,ze.blending=i.NoBlending,ze.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}($e||($e={}));const Je=(()=>{const e=new Uint8Array([255,255,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Xe=(()=>{const e=new Uint8Array([0,0,0,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ye=(()=>{const e=new Uint8Array([128,128,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ke=new C({color:R(0),position:_(R(0))});Ke.visible=!1;const Qe=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let Ze=0,et=null;const tt=new Map;function st(){return null==et&&(et=new IntersectionObserver(e=>{for(const t of e){const e=tt.get(t.target);e&&e(t.isIntersecting)}},{threshold:0})),et}let it=e=class{get fpsCap(){return this._fpsCap}set fpsCap(e){const t=null!=e&&Number.isFinite(e)&&e>0?e:null;t!==this._fpsCap&&(this._fpsCap=t,this.fpsCapRevision++)}setPaused(e){this.paused=e}get currentResolutionScale(){return this.getEffectiveResolutionScale()}get currentRenderPixelRatio(){return this.getRenderPixelRatio()}get currentPresentationPixelRatio(){return this.getPresentationPixelRatio()}getRenderSize(e=new i.Vector2){return e.set(Math.max(1,this.container.clientWidth*this.getRenderPixelRatio()),Math.max(1,this.container.clientHeight*this.getRenderPixelRatio()))}isUpscalingEnabled(){return!0===this.options.upscaling?.enabled&&!0!==this.options.enableXR}isTemporalUpscalingEnabled(){return this.isUpscalingEnabled()&&"temporal"===Ne(this.options.upscaling)}resetUpscalingHistory(){this.hasPreviousTemporalViewProjection=!1,this.upscaleOutputPass?.resetHistory()}prepareUpscalingFrame(){if(!this.isTemporalUpscalingEnabled()||null==this.upscaleOutputPass)return void this.upscaleOutputPass?.setFrameState(null);this.unjitteredProjectionMatrix.copy(this.camera.projectionMatrix),this.currentUnjitteredViewProjectionMatrix.multiplyMatrices(this.unjitteredProjectionMatrix,this.camera.matrixWorldInverse),this.hasPreviousTemporalViewProjection||(this.previousViewProjectionMatrix.copy(this.currentUnjitteredViewProjectionMatrix),this.upscaleOutputPass.resetHistory());const e=mt(this.options.upscaling?.temporal?.jitterScale,1);We(this.temporalUpscalingFrameIndex++,this.temporalJitter,e),this.temporalJitterUv.set(this.temporalJitter.x/Math.max(1,this.gRenderTarget.width),this.temporalJitter.y/Math.max(1,this.gRenderTarget.height));const t=2*this.temporalJitter.x/Math.max(1,this.gRenderTarget.width),s=2*this.temporalJitter.y/Math.max(1,this.gRenderTarget.height);this.camera instanceof l?(this.camera.projectionMatrix.elements[8]+=t,this.camera.projectionMatrix.elements[9]+=s):(this.camera.projectionMatrix.elements[12]+=t,this.camera.projectionMatrix.elements[13]+=s),this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(),this.projectionJitterApplied=!0,this.currentViewProjectionMatrix.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),this.currentViewProjectionMatrixInverse.copy(this.currentViewProjectionMatrix).invert(),this.temporalUpscalingFrameState.depthTexture=this.gRenderTarget.depthTexture,this.upscaleOutputPass.setFrameState(this.temporalUpscalingFrameState)}finishUpscalingFrame(){this.projectionJitterApplied&&(this.camera.projectionMatrix.copy(this.unjitteredProjectionMatrix),this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(),this.previousViewProjectionMatrix.copy(this.currentUnjitteredViewProjectionMatrix),this.hasPreviousTemporalViewProjection=!0,this.projectionJitterApplied=!1)}getBasePixelRatio(){const e=mt(this.maxPixelRatio,1),t=mt(window.devicePixelRatio,1);return Math.min(e,t)}getBaseResolutionScale(){return mt(this.resolutionScale,1)}getDynamicResolutionMinScale(){const e=this.getBaseResolutionScale(),t=mt(this.options.dynamicResolution?.minScale,.7);return Math.min(e,t)}getEffectiveResolutionScale(){const e=this.getBaseResolutionScale();return!0!==this.options.dynamicResolution?.enabled?e:ve(this.dynamicResolutionScale,this.getDynamicResolutionMinScale(),e)}getRenderPixelRatio(){return this.getBasePixelRatio()*this.getEffectiveResolutionScale()}getPresentationPixelRatio(){const e=this.getBasePixelRatio();return this.isUpscalingEnabled()?e:e*this.getEffectiveResolutionScale()}resetDynamicResolutionAverage(){this.dynamicResolutionFrameTimeAverage=null,this.dynamicResolutionFrameSamples=0}updateDynamicResolution(e,t){const s=this.options.dynamicResolution;if(!0!==s?.enabled)return;if(!Number.isFinite(e)||e<=0||e>.25)return void this.resetDynamicResolutionAverage();const i=this.getBaseResolutionScale(),a=this.getDynamicResolutionMinScale(),n=ve(this.dynamicResolutionScale,a,i);dt(n,this.dynamicResolutionScale)||(this.dynamicResolutionScale=n);const r=mt(s.targetFps,60),o=1e3/(null!=this.fpsCap?Math.min(r,this.fpsCap):r),l=1e3*e;this.dynamicResolutionFrameTimeAverage=null==this.dynamicResolutionFrameTimeAverage?l:.9*this.dynamicResolutionFrameTimeAverage+.1*l,this.dynamicResolutionFrameSamples++;const h=Math.max(1,Math.floor(mt(s.sampleFrames,20)));if(this.dynamicResolutionFrameSamples<h)return;const p=mt(s.decreaseCooldown,500),c=mt(s.increaseCooldown,2e3),u=mt(s.decreaseStep,.05),d=mt(s.increaseStep,.025),m=this.dynamicResolutionFrameTimeAverage;let f=n;m>1.12*o&&n>a&&t-this.dynamicResolutionLastAdjustmentAt>=p?f=Math.max(a,n-u):m<.85*o&&n<i&&t-this.dynamicResolutionLastAdjustmentAt>=c&&(f=Math.min(i,n+d)),dt(f,n)||(this.dynamicResolutionScale=f,this.dynamicResolutionLastAdjustmentAt=t,this.resetDynamicResolutionAverage(),this.resizeRender(!0))}resizeRender(e=!1){if(!this.running)return;const t=this.container.clientWidth,s=this.container.clientHeight,i=this.getRenderPixelRatio(),a=this.getPresentationPixelRatio();if(!e&&this.previousClientWith===t&&this.previousClientHeight===s&&this.previousRenderPixelRatio===i&&this.previousPresentationPixelRatio===a)return;if(0===t||0===s)return;this.previousClientWith=t,this.previousClientHeight=s,this.previousRenderPixelRatio=i,this.previousPresentationPixelRatio=a,this.camera instanceof l&&(this.camera.aspect=t/s,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(a),this.renderer.setSize(t,s),this.composer.setPixelRatio(i),this.composer.setSize(t,s);const n=t*i,r=s*i;this.dofPass.setSize(n,r),this.fxaaPass.setSize(n,r),this.fxaaPass.uniforms.resolution.value.set(1/n,1/r),this.createGRenderTarget(),this.phasedRenderPass.gRenderTarget=this.gRenderTarget,this.bloomPass.emissiveTexture=this.gRenderTarget.textures[1],this.ssrPass.setSize(this.gRenderTarget.width,this.gRenderTarget.height),this.ssrPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.aoPass.setSize(this.gRenderTarget.width,this.gRenderTarget.height),this.aoPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.sceneColorRenderTarget.dispose(),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container),this.copyPass.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass.material.uniformsNeedUpdate=!0,this.resetDynamicResolutionAverage(),this.resetUpscalingHistory()}addPostProcessVolume(e){if(0===this.postProcessVolumes.length)this.postProcessVolumes.push(e);else{let t=!1;for(let s=0;s<this.postProcessVolumes.length;s++)if(e.priority<this.postProcessVolumes[s].priority){this.postProcessVolumes.splice(s,0,e),t=!0;break}t||this.postProcessVolumes.push(e)}}removePostProcessVolume(e){const t=this.postProcessVolumes.indexOf(e);t>-1&&this.postProcessVolumes.splice(t,1)}addPostProcessEffect(e,t={}){const s={id:++this.postProcessEffectId,pass:new ye(e),priority:xe(t.priority),stage:Te(t.stage)};return s.pass.enabled=t.enabled??!0,this.postProcessEffects.push(s),this.refreshPostProcessEffectPassOrder(),new be(this,s)}removePostProcessEffectEntry(e){const t=e,s=this.postProcessEffects.indexOf(t);-1!==s&&(this.postProcessEffects.splice(s,1),this.composer.removePass(t.pass),t.pass.dispose())}refreshPostProcessEffectPassOrder(){for(const e of this.postProcessEffects)this.composer.removePass(e.pass);for(const e of we){const t=this.getPostProcessEffectStageAnchorPass(e),s=null!=t?this.composer.passes.indexOf(t):this.composer.passes.length,i=this.postProcessEffects.filter(t=>t.stage===e).sort(rt);for(let e=0;e<i.length;e++)this.composer.insertPass(i[e].pass,s+e)}}getPostProcessEffectStageAnchorPass(e){switch(e){case"beforeFog":return this.volumetricFogPass;case"beforeDepthOfField":return this.dofPass;case"beforeColorAdjustment":return this.colorPass;case"beforeOutline":return this.outlinePass;case"beforeAntiAliasing":return this.fxaaPass;case"beforeLut":return this.lutPass;case"beforeOutput":return this.outputPass}}constructor(t,s={}){this.container=t,this.options=s,this.isIntersecting=!1,this.windowVisible=!0,this.running=!0,this.paused=!1,this._fpsCap=null,this.fpsCapRevision=0,this.postProcessVolumes=[],this.postProcessSettings={},this.baseToneMapping=i.NoToneMapping,this.baseToneMappingExposure=1,this.csmUpdateInvervals=this.options.shadows?.cascadeUpdateIntervals,this._id=Ze++,this.postProcessEffectId=0,this.postProcessEffects=[],this.postProcessEffectResolution=new i.Vector2(1,1),this.postProcessEffectUniformState={aoEnabled:!1,aoTexture:null,cameraFar:void 0,cameraNear:void 0,depthTexture:new u,normalTexture:new u,resolution:this.postProcessEffectResolution,simulationTime:0},this.fquadCopy=new Be(new p(f)),this.fquadCopyOpaque=new Be(new C({outputs:[q("tSceneColor",new u).sample(V.uv),_(q("tDepthTexture",new i.DepthTexture(1,1)).sample(V.uv).r)]})),this.simulationTime=0,this.simulationTimeScale=1,this.lightProbeIntensity=2,this.fquadBlendAO=(()=>{const e=_(1),t=new C({outputs:[q("tAO",new u).sample(le),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Be(t)})(),this.resolutionScale=1,this.maxPixelRatio=Qe?1:window.devicePixelRatio,this.dynamicResolutionScale=1,this.dynamicResolutionFrameTimeAverage=null,this.dynamicResolutionFrameSamples=0,this.dynamicResolutionLastAdjustmentAt=0,this.upscaleOutputPass=null,this.unjitteredProjectionMatrix=new r,this.temporalJitter=new i.Vector2,this.temporalJitterUv=new i.Vector2,this.currentUnjitteredViewProjectionMatrix=new r,this.currentViewProjectionMatrix=new r,this.currentViewProjectionMatrixInverse=new r,this.previousViewProjectionMatrix=new r,this.temporalUpscalingFrameState={depthTexture:null,currentJitterUv:this.temporalJitterUv,currentViewProjectionInverse:this.currentViewProjectionMatrixInverse,previousViewProjection:this.previousViewProjectionMatrix},this.temporalUpscalingFrameIndex=0,this.hasPreviousTemporalViewProjection=!1,this.projectionJitterApplied=!1,this.onResize=()=>{if(this.resizeRender(),!this.paused)try{this.render()}catch(e){}},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!0,this.onLoopCallbacks=[],this.stats=new ee,this._showStats=!1,this.gbufferMaterialCache=new Map,this.gbufferDepthPrepassMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.depthPrepassMaterialCache=new WeakMap,this.depthPrepassCachedMaterials=new Map,this.depthPrepassCachedVisibility=[],this.gBufferCachedMaterials=new Map,this.gBufferCachedVisibility=[],this._initiatedMaterialTextures=new Set,this._initiatedTextures=new Set,this.compileInProgress=!1,this.pmremGeneratorResults=new WeakMap,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 a,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,this.dynamicResolutionScale=this.getBaseResolutionScale(),this.fpsCap=s.fpsCap,e.activeView=this,Z.init(),window.renderer=this.renderer=window.renderer??new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}.bind(this.scene),this.renderer.setPixelRatio(this.getPresentationPixelRatio()),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(w.createButton(this.renderer));const n=new Ue(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=n,this.createGRenderTarget(),this.composer=new g(this.renderer,function(e,t){const s=new i.WebGLRenderTarget(Math.max(1,e),Math.max(1,t),{minFilter:i.LinearFilter,magFilter:i.LinearFilter,format:i.RGBAFormat,type:i.HalfFloatType});return s.texture.name="EffectComposer.rt1",s.texture.generateMipmaps=!1,s}(t.clientWidth,t.clientHeight)),this.composer.setPixelRatio(this.getRenderPixelRatio()),this.composer.setSize(t.clientWidth,t.clientHeight);var o=(t.clientWidth||1)/(t.clientHeight||1);const l=new i.PerspectiveCamera(45,o,.5,800);l.layers.enable(19),this.setCamera(l),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=i.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=s.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=i.SRGBColorSpace,this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1,this.baseToneMapping=this.renderer.toneMapping,this.baseToneMappingExposure=this.renderer.toneMappingExposure,this.renderer.gammaFactor=1.4,T.renderingView=this,this.isDepthTextureExtensionSupported=he(this.renderer),this.attachRendererDomElement(),this.setupEventListeners(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container,this.getRenderPixelRatio()),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container);const h=new i.Vector2(t.clientWidth,t.clientHeight),c=(new y(this.scene,this.camera),new b(f,"prevtexture"));c.enabled=!0,c.needsSwap=!0,c.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=c;const d=new Ee(h,1.5,.4,.85);d.threshold=1,d.strength=.9,d.radius=.2,this.bloomPass=d;const m=new te(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});m.normalRenderTarget?.dispose(),m.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),m.output=te.OUTPUT.Off,m.enabled=!1,this.aoPass=m,this.fquadBlendAO.material.uniforms.tAO.value=m.pdRenderTarget.texture,Re.fragmentShader=Re.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const x=new Se({renderer:this.renderer,scene:this.scene,camera:this.camera,width:this.gRenderTarget.width,height:this.gRenderTarget.height,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[2],depthTexture:this.gRenderTarget.depthTexture});x.output=Se.OUTPUT.Default,x.blur=!0,x.fresnel=!1,x.distanceAttenuation=!0,x.maxDistance=50,x.selective=!0,x.bouncing=!1,x.opacity=.4,x.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=x,!1!==this.options.ao?.enabled&&this.composer.addPass(m);const S=new Ct((e,t,s,i,a)=>{this.aoPass.enabled&&(this.initResolutionUniform(this.fquadBlendAO.material),this.renderer.setRenderTarget(this.gRenderTarget),this.fquadBlendAO.render(this.renderer),this.renderer.setRenderTarget(null))});this.composer.addPass(S);const R=new Ct((e,t,s,i,a)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene($e.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(R),this.composer.addPass(c),this.composer.addPass(x),this.phasedRenderPass=new Rt(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(d),d.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new Ce(h),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new Y(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const U=new Pe;this.composer.addPass(U),this.colorPass=U,U.vignetteEnabled=!1,this.outlinePass=new fe(new i.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const E=new b(M);E.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(E),this.fxaaPass=E,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new b(v).clear=!1,this.fixStatsStyle(),this.lutPass=new P({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const A=new b(f,"prevtexture");A.enabled=!0,A.needsSwap=!1,A.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],A.renderToScreen=!0;const O=this.isUpscalingEnabled()?new He(this.options.upscaling):new K;!function(e){const t=e.material;if(t.dithering=!0,t.fragmentShader.includes("<dithering_fragment>"))return;const s="#include <colorspace_pars_fragment>";if(!t.fragmentShader.includes(s))return;t.fragmentShader=t.fragmentShader.replace(s,`${s}\n #include <common>\n #include <dithering_pars_fragment>`);const i=t.fragmentShader.lastIndexOf("}");i<0||(t.fragmentShader=`${t.fragmentShader.slice(0,i)}\n #include <dithering_fragment>\n${t.fragmentShader.slice(i)}`,t.needsUpdate=!0)}(O),this.outputPass=O,this.upscaleOutputPass=O instanceof He?O:null,this.composer.addPass(O)}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"}setEnableOutlines(e){this.outlinePass.enabled=e,this.fxaaPass.enabled=e}setCamera(e){if(this.camera=e,this.resetUpscalingHistory(),this.composer.passes.forEach(t=>{t instanceof y?t.camera=e:t instanceof fe?t.renderCamera=e:(t instanceof de||t instanceof te)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),this.phasedRenderPass&&(this.phasedRenderPass.camera=e),null==this.csm){if(this.csm=new Q({maxFar:80,lightFar:250,lightMargin:20,cascades:Qe?2:3,shadowMapSize:2048*(Qe?.5:1),lightDirection:new i.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"}),null!=this.csmUpdateInvervals){this.csmCascadeLastUpdate=new Array(this.csm.lights.length).fill(0);for(const e of this.csm.lights)e.shadow.autoUpdate=!1}this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,h.lights_fragment_begin=x.lights_fragment_begin}else this.csm.camera=this.camera,this.camera;this.csm.updateFrustums()}setSelectedObjects(e){if(null==this.outlinePass)return;const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t,s){const a=Math.max(1,Math.floor(t.clientWidth*s)),n=Math.max(1,Math.floor(t.clientHeight*s)),r=new i.WebGLRenderTarget(a,n);return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new i.DepthTexture(a,n),r.depthTexture.type=i.UnsignedShortType,r.depthTexture.minFilter=i.NearestFilter,r.depthTexture.magFilter=i.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t,s=e.getPixelRatio()){const a=Math.max(1,t.clientWidth*s),n=Math.max(1,t.clientHeight*s),r=new i.DepthTexture(a,n);r.type=i.UnsignedInt248Type,r.minFilter=i.NearestFilter,r.magFilter=i.NearestFilter;const o=new i.WebGLRenderTarget(a,n,{type:i.HalfFloatType,depthTexture:r});return o.texture.minFilter=i.NearestFilter,o.texture.magFilter=i.NearestFilter,o.texture.generateMipmaps=!1,o.stencilBuffer=!1,o}createSceneColorRenderTarget(e,t){const s=this.gRenderTarget.width,a=this.gRenderTarget.height,n=new i.WebGLRenderTarget(s,a,{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return n.texture.minFilter=i.LinearFilter,n.texture.magFilter=i.LinearFilter,n.texture.generateMipmaps=!1,n.textures[1].minFilter=i.NearestFilter,n.textures[1].magFilter=i.NearestFilter,n}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose();const t=this.getRenderPixelRatio(),s=Math.max(1,e.clientWidth*t),a=Math.max(1,e.clientHeight*t),n=new i.DepthTexture(s,a);n.type=i.UnsignedIntType,n.minFilter=i.NearestFilter,n.magFilter=i.NearestFilter,this.gRenderTarget=new c(s,a,{count:3,samples:this.options?.msaa??(Qe?void 0:2),minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat,depthTexture:n}),this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(e=!0){this.running=!1,this.lightVolume?.shTexture.dispose(),window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],e&&this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose();for(const e of this.postProcessEffects)this.composer.removePass(e.pass),e.pass.dispose();this.postProcessEffects.length=0,this.detachOwnedDomElements();st().unobserve(this.container),tt.delete(this.container),this.volumetricFogPass.dispose(),T.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.findIndex(t=>t===e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&this.stats.dom.parentElement!==this.container?this.container.appendChild(this.stats.dom):this._showStats||this.stats.dom.parentElement!==this.container||this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}attachRendererDomElement(){const e=this.renderer.domElement;e.parentElement===this.container&&e===this.container.firstChild||this.container.insertBefore(e,this.container.firstChild),this._showStats&&this.stats.dom.parentElement!==this.container&&this.container.appendChild(this.stats.dom)}detachOwnedDomElements(){this.renderer.domElement.parentElement===this.container&&this.container.removeChild(this.renderer.domElement),this.stats.dom.parentElement===this.container&&this.container.removeChild(this.stats.dom)}applyEnvMap(e){if(null!=this.scene.environment&&(e instanceof C&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0,e.uniforms.envMapRotation={value:bt(this.scene.environmentRotation,this.scene.environment,new i.Matrix3)}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment),e instanceof C||e instanceof i.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateMaterialProperties(e,t){(e instanceof i.MeshBasicMaterial||e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(null!=t.uniforms.color&&t.uniforms.color.value.setFromColor(e.color),null!=t.uniforms.opacity&&(t.uniforms.opacity.value=e.opacity),null!=t.uniforms.map&&(t.uniforms.map.value=e.map),null!=t.uniforms.alphaMap&&(t.uniforms.alphaMap.value=e.alphaMap),null!=t.uniforms.lightMap&&(t.uniforms.lightMap.value=e.lightMap,t.uniforms.lightMapIntensity.value=e.lightMapIntensity),null!=t.uniforms.aoMap&&(t.uniforms.aoMap.value=e.aoMap,t.uniforms.aoMapIntensity.value=e.aoMapIntensity),null!=t.uniforms.alphaTest&&(t.uniforms.alphaTest.value=e.alphaTest)),(e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(t.uniforms.normalMap&&(t.uniforms.normalMap.value=e.normalMap,t.uniforms.normalScale.value=e.normalScale.x),t.uniforms.emissiveMap&&(t.uniforms.emissiveMap.value=e.emissiveMap,t.uniforms.emissive.value.setFromColor(e.emissive),t.uniforms.emissiveIntensity.value=e.emissiveIntensity)),e instanceof m&&(null!=t.uniforms.roughnessMap&&(t.uniforms.roughnessMap.value=e.roughnessMap),null!=t.uniforms.metalnessMap&&(t.uniforms.metalnessMap.value=e.metalnessMap),null!=t.uniforms.roughness&&(t.uniforms.roughness.value=e.roughness),null!=t.uniforms.metalness&&(t.uniforms.metalness.value=e.metalness)),e instanceof i.MeshPhysicalMaterial&&(t.uniforms.sheenColor&&t.uniforms.sheenColor.value.setFromColor(e.sheenColor).multiplyScalar(e.sheen),t.uniforms.sheenColorMap&&(t.uniforms.sheenColorMap.value=e.sheenColorMap),t.uniforms.sheenRoughness&&(t.uniforms.sheenRoughness.value=e.sheenRoughness),t.uniforms.sheenRoughnessMap&&(t.uniforms.sheenRoughnessMap.value=e.sheenRoughnessMap)),e instanceof Ge&&(t.uniforms.heightMap.value=e.heightMap,t.uniforms.heightScale.value=e.heightScale),this.updateMaterialCommonProperties(e,t)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],a=s[e].value;null!=t&&t.value!==a&&"receiveShadow"!==e&&!1===Ut.includes(e)&&(t.value=a)}this.updateMaterialCommonProperties(e,t)}inheritCustomUniformBindings(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s)null==i[e]&&("receiveShadow"===e||Ut.includes(e)||Et.includes(e)||(i[e]={value:s[e].value}))}updateMaterialCommonProperties(e,t){t.alphaTest=e.alphaTest,t.side=e.side,t.depthTest=e.depthTest,t.blending=e.blending,t.colorWrite=e.colorWrite,t.premultipliedAlpha=e.premultipliedAlpha,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.visible=e.visible}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of Ut){const t=i[e],a=s[e];null!=a&&null!=t&&(t.value=a.value)}}createGBufferMaterial(e,t,s=!1){const a=t===$e.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let n=a.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==n){let s=V.uv;if(e instanceof Ge&&null!=e.heightMap){const t=E("heightScale",e.heightScale??1);s=De(s,q("heightMap",e.heightMap),t)}let o=L.normal;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.normalMap??Ye,i=E("useNormalMap",null!=e.normalMap?1:0),a=E("normalScale",e.normalScale?.x??1),n=S(q("normalMap",t).sample(_e(s,e.normalMap)),a);o=z(L.normal,n,i)}else e instanceof C&&null!=e.outputNormal&&(o=e.outputNormal);!0!==e.userData.disableAO&&(o=H("DOUBLE_SIDED",o,e=>N(new W("gl_FrontFacing"),e,e.multiplyScalar(-1))));let l=e.userData?.reflective?R(0):R(1);if(e instanceof i.MeshStandardMaterial){const t=E("roughness",e.roughness??1),i=e.roughnessMap??Je,a=E("useRoughnessMap",null!=e.roughnessMap?1:0),n=q("roughnessMap",i).sample(_e(s,e.roughnessMap)).g.multiply(t);l=z(t,n,a)}else e instanceof C&&null!=e.outputRoughness&&(l=e.outputRoughness);let h=null;if((e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial)&&null!=e.lightMap){const t=e.lightMap,i=E("useLightMap",null!=e.lightMap?1:0),a=E("lightMapIntensity",e.lightMapIntensity??1),n=q("lightMap",t).sample(s).rgb.multiplyScalar(a);h=z(D(0),n,i)}let c=R(0);if(e instanceof i.MeshStandardMaterial){const t=E("metalness",e.metalness??0),i=e.metalnessMap??Xe,a=E("useMetalnessMap",null!=e.metalnessMap?1:0),n=q("metalnessMap",i).sample(_e(s,e.metalnessMap)).b.multiply(t);c=z(t,n,a)}else e instanceof C&&e.outputRoughness;let u=null,d=R(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){const t=e.aoMap??Je,i=E("useAoMap",null!=e.aoMap?1:0);d=E("aoMapIntensity",e.aoMapIntensity??1);const a=q("aoMap",t).sample(_e(s,e.aoMap)).r;u=z(R(1),a,i)}else e instanceof C&&e.outputRoughness;const f=E("opacity",e.opacity??1);let g=R(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){if(null!=e.alphaMap){const t=e.alphaMap;g=q("alphaMap",t).sample(_e(s,e.alphaMap)).r}g=g.multiply(f)}else e instanceof C&&null!=e.outputOpacity&&(g=e.outputOpacity);let M=B(0,1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){let t=A("color",(new i.Vector3).setFromColor(e.color));const a=e.map??Je,n=E("useAlbedoMap",null!=e.map?1:0),r=q("map",a).sample(_e(s,e.map)),o=r.multiply(B(t,1)),l=B(t,1);M=z(l,o,n),e.vertexColors&&(M=M.multiply(_(I($.color.rgb),1)));const h=z(R(1),r.w,n);g=g.multiply(h)}const v=!0===e.userData.hasBloom;let P=D(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=A("emissive",(new i.Vector3).setFromColor(e.emissive)),a=E("emissiveIntensity",e.emissiveIntensity),n=e.emissiveMap??Xe,r=E("useEmissiveMap",null!=e.emissiveMap?1:0),o=q("emissiveMap",n).sample(_e(s,e.emissiveMap)).rgb.multiply(t);P=z(t,o,r),P=P.multiplyScalar(a)}else e instanceof C&&null!=e.outputEmissive&&(P=e.outputEmissive);let y=null;if(e instanceof i.MeshPhysicalMaterial&&e.sheen>0&&(y=A("sheenColor",(new i.Vector3).setFromColor(e.sheenColor).multiplyScalar(e.sheen)),e.sheen>0&&null!=e.sheenColorMap)){const t=q("sheenColorMap",e.sheenColorMap).sample(s).rgb;y=y.multiply(t)}let b=null;if(e instanceof i.MeshPhysicalMaterial&&e.sheen>0&&(b=E("sheenRoughness",e.sheenRoughness),e.sheen>0&&null!=e.sheenRoughnessMap)){const t=q("sheenRoughnessMap",e.sheenRoughnessMap).sample(s).r;b=b.multiply(t)}let w=null;if(e instanceof i.MeshPhysicalMaterial&&e.anisotropy>0&&(w=E("anisotropy",e.anisotropy),e.anisotropy>0&&null!=e.anisotropyMap)){const t=q("anisotropyMap",e.anisotropyMap).sample(s).r;w=w.multiply(t)}let x=null;if(e instanceof i.MeshPhysicalMaterial&&e.anisotropy>0){const t=e.anisotropyRotation??0;x=J("anisotropyDirection",new i.Vector2(Math.cos(t),Math.sin(t)))}const T=this.usesShaderUniform(e,ie),j=this.usesShaderUniform(e,ue),k=this.usesShaderUniform(e,ce),X=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,Y=E("alphaTest",e.alphaTest);let K,Q=e.alphaTest>0?g.lt(Y):X&&t===$e.opaque?g.lt(.8):null;!0===e.userData.isDecal&&(Q=Q?Q.or(Ie):Ie),K=X?_(0,0,0,0):(r=o,G(r).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?l:1);const Z=e instanceof C?e.outputPosition:void 0,ee=e instanceof C?e.outputTransform:void 0;let te,se=B("black",1);if(e instanceof C&&null!=e.outputColor)se=e.outputColor;else if(e instanceof i.MeshStandardMaterial)se=U({color:M,metalness:c,roughness:l,emissive:P.rgb,normal:o,ambientOcclusion:u,ambientOcclusionIntensity:d,bakedLight:h,sheenColor:y,sheenRoughness:b,anisotropy:w,anisotropyDirection:x});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)se=F({color:M.rgb,ambientOcclusion:u,ambientOcclusionIntensity:d});else if(e instanceof i.MeshBasicMaterial){let e=M.rgb,t=h??D("black");null!=u&&(t=t.multiplyScalar(u.subtract(1).multiply(d).add(1))),e=e.add(t),se=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(se=O({color:M,emissive:P.rgb,normal:o,ambientOcclusion:u,ambientOcclusionIntensity:d,bakedLight:h}));(e instanceof C||e instanceof i.MeshStandardMaterial)&&(te=e.envMap);let ae=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(ae=e.fog);let ne=B(se.rgb,g);ae&&(ne=new FogNode(ne));let re=!0;if(t===$e.opaque?(re&&(re=!T&&!j&&!k),re&&(re=!X)):t===$e.transparent&&re&&(re=X||T||j||k),!re)return n=Ke,a.set(e,n),n;n=new C({transform:ee,position:null==ee?Z:void 0,outputs:[ne,P.rgba(t===$e.opaque?Y:v?1:0),K],opacity:g,outputEncoding:!1,fog:ae,transparent:e.transparent,lights:!0,envMap:te,alphaTest:e.alphaTest,uniformNodes:e.uniformNodes??{},discard:Q}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=n.uniforms.envMapIntensity&&(n.uniforms.envMapIntensity.value=e.envMapIntensity),"alphaMap"in e&&null!=e.alphaMap&&(n.alphaMap=e.alphaMap),(e instanceof C||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(n),e instanceof C&&(Object.assign(n.defines,e.defines),null!=n.uniforms[ce]&&(n.uniforms[ce].value=this.aoPass.pdRenderTarget.texture,n.defines.USE_SSAO_MAP="")),n.userData.mrtOutputs=3,n.forceSinglePass=e.forceSinglePass,n.side=e.side,n.blending=e.blending,X?(n.depthWrite=!e.transparent,n.depthTest=e.depthTest,n.colorWrite=t===$e.transparent):(n.depthWrite=e.depthWrite,n.depthTest=e.depthTest),n.visible=e.visible,n.alphaTest=e.alphaTest,n.alphaHash=e.alphaHash,n.vertexColors=e.vertexColors,n.premultipliedAlpha=e.premultipliedAlpha,n.toneMapped=e.toneMapped,n.blendAlpha=e.blendAlpha,n.blendColor=e.blendColor,n.polygonOffset=e.polygonOffset,n.polygonOffsetFactor=e.polygonOffsetFactor,n.polygonOffsetUnits=e.polygonOffsetUnits,n.blending=e.blending,n.wireframe=e.wireframe??!1,n.userData.isGBufferMaterial=!0,n.visible=re,Object.assign(n.userData,e.userData),n.visible&&(this.csm.setupMaterial(n),e instanceof p&&this.inheritCustomUniformBindings(e,n)),a.set(e,n)}var r;return n.visible&&(e instanceof p?this.updateUniformValues(e,n):this.updateMaterialProperties(e,n)),this.usesShaderUniform(n,ue)&&this.initSceneColorUniform(n),this.initLightVolumeUniform(n),n}isDepthPrepassEnabled(){return!0===this.options.depthPrepass?.enabled}usesSceneFeedbackUniforms(e){return e instanceof p&&(this.usesShaderUniform(e,ie)||this.usesShaderUniform(e,ue)||this.usesShaderUniform(e,ce))}usesShaderUniform(e,t){return e instanceof p&&null!=e.uniforms[t]}isDepthPrepassEligibleMaterial(e){return null!=e&&(!1!==e.visible&&!1!==e.depthTest&&!1!==e.depthWrite&&(!e.transparent&&e.blending!==i.AdditiveBlending&&(!this.usesSceneFeedbackUniforms(e)&&(e instanceof C||e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshBasicMaterial))))}isDepthPrepassEligibleMesh(e){return!!this.isDepthPrepassEnabled()&&((e instanceof i.InstancedMesh||e instanceof Le)&&(!Array.isArray(e.material)&&this.isDepthPrepassEligibleMaterial(e.material)))}createDepthPrepassMaterial(e){if(!this.isDepthPrepassEligibleMaterial(e))return null;let t=this.depthPrepassMaterialCache.get(e);if(null==t){let s,a=R(1);e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(a=E("opacity",e.opacity??1),null!=e.map&&(a=a.multiply(q("map",e.map).sample(V.uv).a)),null!=e.alphaMap&&(a=a.multiply(q("alphaMap",e.alphaMap).sample(V.uv).r))):e instanceof C&&(a=e.outputOpacity??R(1)),null!=e.alphaTest&&e.alphaTest>0&&(s=a.lt(e.alphaTest));const n=e instanceof C?e.outputPosition:void 0,r=e instanceof C?e.outputTransform:void 0;t=new C({outputs:[B(0,0),B(0,0),B(0,0)],opacity:a,transform:r,position:null==r?n:void 0,discard:s,lights:!1,fog:!1,outputEncoding:!1,transparent:!1,alphaTest:e.alphaTest}),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=i.NoBlending,t.lights=!1,t.fog=!1,t.toneMapped=!1,t.side=e.side,t.alphaTest=e.alphaTest,t.visible=e.visible,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.onBeforeCompile=()=>{},t.customProgramCacheKey=()=>`depth-prepass:${e.id}:${e.version}:${e.alphaTest}:${e.side}`;for(const e of Ut)delete t.uniforms[e];for(const e of Et)delete t.uniforms[e];delete t.uniforms.receiveShadow,this.depthPrepassMaterialCache.set(e,t)}return e instanceof C?this.updateUniformValues(e,t):this.updateMaterialProperties(e,t),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=i.NoBlending,t.visible=e.visible,t.alphaTest=e.alphaTest,t.side=e.side,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t}applyDepthPrepassMaterials(){const e=this.depthPrepassCachedMaterials,t=this.depthPrepassCachedVisibility;e.clear(),t.length=0,Me(this.scene,s=>{if(Tt(s))return t.push(s),s.visible=!1,!1;if(!(s instanceof o))return;if(e.set(s,s.material),!this.isDepthPrepassEligibleMesh(s))return t.push(s),void(s.visible=!1);const i=this.createDepthPrepassMaterial(s.material);if(null==i)return t.push(s),void(s.visible=!1);s.material=i,s.visible=!0})}unapplyDepthPrepassMaterials(){this.depthPrepassCachedMaterials.forEach((e,t)=>{t.material=e}),this.depthPrepassCachedVisibility.forEach(e=>{e.visible=!0})}renderDepthPrepass(){if(!this.isDepthPrepassEnabled())return;this.applyDepthPrepassMaterials();const e=this.scene.matrixWorldAutoUpdate,t=this.scene.matrixAutoUpdate,s=this.renderer.shadowMap.autoUpdate;this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clearDepth();try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Depth prepass render failed",e)}this.unapplyDepthPrepassMaterials(),this.renderer.shadowMap.autoUpdate=s,this.scene.matrixWorldAutoUpdate=e,this.scene.matrixAutoUpdate=t}updateCsm(){const e=this.csmUpdateInvervals;if(this.renderer.shadowMap.autoUpdate&&null!=this.csmCascadeLastUpdate&&Array.isArray(e)){const t=performance.now();for(let s=0;s<this.csm.lights.length;++s){const i=e[s]??e[e.length-1]??16;(t-this.csmCascadeLastUpdate[s]>=i||0===s)&&this.csm.lights[s].shadow&&(this.csm.lights[s].shadow.needsUpdate=!0,this.csmCascadeLastUpdate[s]=t)}}this.csm.update()}loop(t,s=!1){const a=this.stats,n=a.addPanel(new ee.Panel("Calls","#83f","#002")),l=a.addPanel(new ee.Panel("Triangles","#c32","#002"));let h;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(h=new me(this.renderer.getContext()),a.addPanel(h)),this.showStats=s;let p=10,c=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>p&&(p=e,setTimeout(()=>p=10,5e3)),n.update(e,p);const t=this.renderer.info.render.triangles;t>c&&(c=t,setTimeout(()=>c=1e3,5e3)),l.update(t,c)};performance.now();i.Ray.prototype.intersectTriangle;this.resizeRender();const d=[],m=[],f=[];let g=0;const M=new r,v=new r;let P=0;let y=this.paused,b=!1,w=0,x=null,T=this.fpsCapRevision;const S=()=>{this.running&&!0!==this.options.enableXR&&requestAnimationFrame(E)},R=()=>{e.activeView=this,b&&(b=!1,requestAnimationFrame(()=>E(w)))},U=st();tt.set(this.container,e=>{this.isIntersecting=e,e&&R()}),U.observe(this.container),this.container.addEventListener("pointerdown",()=>{R()},{capture:!0});const E=s=>{b=!1;const n=this.renderer.getContext();if(!this.running||null===this.container.offsetParent||this.paused&&n.drawingBufferHeight>1)return b=!0,w=s,setTimeout(()=>{b&&E(s)},500),void(this.paused&&(y=!0));if(this.renderer.domElement.parentElement!==this.container){if(e.activeView!==this&&null!==e.activeView)return b=!0,void(w=s);this.attachRendererDomElement(),this.resizeRender()}if(!0!==this.options.enableXR){T!==this.fpsCapRevision&&(T=this.fpsCapRevision,x=null);const e=this.fpsCap;if(null!=e){const t=1e3/e;if(null!=x){const e=s-x;if(e<t)return void S();x=s-e%t}else x=s}else x=s}let r=(s*=.001)-g;if(g=s,y?(r=.016,y=!1,this.resetUpscalingHistory()):r>.25&&this.resetUpscalingHistory(),this.updateDynamicResolution(r,1e3*s),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),a.begin(),this.showStats&&h?.startQuery(),this.ssrPass.gpuPanel=h,M.copy(this.camera.matrixWorld),r>1){let e=r;for(;e>.05;)t(at),e-=at;t(e)}else t(r);this.onLoopCallbacks.forEach(e=>e(r)),this.paused||(this.simulationTime+=r*this.simulationTimeScale);const l=this.simulationTime;this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),s-P>.08&&!v.equals(M)&&(this.renderer.shadowMap.needsUpdate=!0,P=s),this.updateCsm();let p=!1;d.length=0,m.length=0,f.length=0;const c=lt;pt.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),c.setFromProjectionMatrix(pt);let R=!1,U=!1,A=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Fe&&(R=!0),e instanceof o&&this.initCustomDepthMaterial(e),(e instanceof o||e instanceof i.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),this.initShadowUniform(e,e.material),this.initLightVolumeUniform(e.material),null!=this.scene.environment&&ot(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(p=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[ie])&&isObjectInFrustum(e,c)?(this.initDepthUniform(e.material),U=!0):e instanceof X&&(e.visible=!1,m.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[ce]&&isObjectInFrustum(e,c)&&e.material instanceof C&&this.initAoUniform(e.material),e instanceof o||e instanceof i.Sprite){let t=!1;ot(e,e=>{this.usesShaderUniform(e,ue)&&(this.initSceneColorUniform(e),t=!0)}),t&&(f.push(e),A=!0)}if(e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[pe])e.material.uniforms[pe].value=l;else if(e instanceof o&&Array.isArray(e.material))for(const t of e.material)t.uniforms&&null!=t.uniforms[pe]&&(t.uniforms[pe].value=l)}),this.bloomPass.enabled=p,this.prepareUpscalingFrame(),this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderDepthPrepass(),this.renderScene($e.opaque),this.aoPass.output=te.OUTPUT.Off,(U||A)&&(this.fquadCopyOpaque.material.uniforms.tSceneColor.value=this.gRenderTarget.textures[0],this.fquadCopyOpaque.material.uniforms.tDepthTexture.value=this.gRenderTarget.depthTexture,this.initResolutionUniform(this.fquadCopyOpaque.material),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.clear(),this.fquadCopyOpaque.render(this.renderer),this.renderer.setRenderTarget(this.gRenderTarget)),f.length,d.forEach(e=>e.visible=!0),m.forEach(e=>e.visible=!0),f.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=s),this.volumetricFogPass&&R?(this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene),this.volumetricFogPass.enabled=!0):this.volumetricFogPass&&(this.volumetricFogPass.enabled=!1),this.updatePostProcessEffectUniforms(l);try{!this.paused&&this.running&&(this.render(r),this.finishUpscalingFrame(),this.showStats&&h?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}finally{this.finishUpscalingFrame()}a.end(),this.csm?.update(),S()};!0===this.options.enableXR?this.renderer.setAnimationLoop(E):requestAnimationFrame(E)}applyGBufferMaterials(e){const t=this.gBufferCachedMaterials,s=this.gBufferCachedVisibility;t.clear(),s.length=0;Me(this.scene,i=>{if(Tt(i))return s.push(i),i.visible=!1,!1;if(i instanceof o){t.set(i,i.material);let a=!1;if(Array.isArray(i.material)){i.material=i.material.slice();for(let t=0;t<i.material.length;t++)i.material[t]=this.createGBufferMaterial(i.material[t],e,e===$e.opaque&&this.isDepthPrepassEligibleMesh(i)),a||(a=i.material[t].visible),this.initShadowUniform(i,i.material[t])}else i.material=this.createGBufferMaterial(i.material,e,e===$e.opaque&&this.isDepthPrepassEligibleMesh(i)),a||(a=i.material.visible),this.initShadowUniform(i,i.material);a?i.visible=!0:null!=i.children&&0!=i.children.length||(s.push(i),i.visible=!1)}})}unapplyGBufferMaterials(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e}),this.gBufferCachedVisibility.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)})}initTextures(e=this.scene){e.traverse(e=>{if(e instanceof o)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++)this._initMaterialTextures(e.material[t]);else this._initMaterialTextures(e.material)})}_initMaterialTextures(e){if(!this._initiatedMaterialTextures.has(e))if(this._initiatedMaterialTextures.add(e),e instanceof p){for(const[t,s]of Object.entries(e.uniforms))if(s.value instanceof u){if(this._initiatedTextures.has(s.value))continue;this.renderer.initTexture(s.value),this._initiatedTextures.add(s.value)}}else for(const[t,s]of Object.entries(e))if(s instanceof u){if(this._initiatedTextures.has(s))continue;this.renderer.initTexture(s),this._initiatedTextures.add(s)}}async compileAsync(e=this.scene){if(this.compileInProgress)return;this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0,this.applyGBufferMaterials($e.opaque),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials($e.transparent),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.isDepthPrepassEnabled()&&(this.renderer.setRenderTarget(this.gRenderTarget),this.applyDepthPrepassMaterials(),await this.renderer.compileAsync(e,this.camera),this.unapplyDepthPrepassMaterials()),e===this.scene&&(this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.compileAsync(this.fquadBlendAO.mesh,this.fquadBlendAO.camera),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.compileAsync(this.fquadCopyOpaque.mesh,this.fquadCopyOpaque.camera));const t=this.csm.lights[0]?.shadow.camera;null!=t&&(this.applyDepthMaterial(),await this.renderer.compileAsync(e,t),this.unapplyDepthMaterial()),this.compileInProgress=!1,this.renderer.setRenderTarget(null)}applyDepthMaterial(){const e=this.gBufferCachedMaterials;e.clear(),this.scene.traverse(t=>{(t.isMesh||t.isPoints||t.isLine||t.isSprite)&&(this.initCustomDepthMaterial(t),e.set(t,t.material),t.castShadow?null!=t.customDepthMaterial?t.material=t.customDepthMaterial:t.material=Ot:t.material=null)})}unapplyDepthMaterial(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e})}renderScene(e){if(!this.running||this.paused)return;if(this.compileInProgress)return void console.error("Compile in progress, skipping render");this.applyGBufferMaterials(e);const t=this.scene.matrixWorldAutoUpdate,s=this.scene.matrixAutoUpdate,i=this.renderer.shadowMap.autoUpdate;e!==$e.opaque&&(this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1);try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Render failed",e)}e===$e.opaque&&this.gBufferCachedMaterials.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof p&&this.updateLightUniformValues(t.material,e)}),this.unapplyGBufferMaterials(),this.renderer.shadowMap.autoUpdate=i,this.scene.matrixWorldAutoUpdate=t,this.scene.matrixAutoUpdate=s}getEnvTexture(e){null==this.pmremGenerator&&(this.pmremGenerator=new i.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader());let t=this.pmremGeneratorResults.get(e);return null==t&&(t=this.pmremGenerator.fromEquirectangular(e).texture,this.pmremGeneratorResults.set(e,t)),t.colorSpace=i.SRGBColorSpace,t}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure);!function(e,t=i.NoToneMapping,s=1){e.tonemapMapping=t,e.tonemapExposure=s,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=e.colorTint??new i.Color("white"),e.colorTint.set("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.globalSaturation=ct(e.globalSaturation,1,1,1),e.globalContrast=ct(e.globalContrast,1,1,1),e.globalGamma=ct(e.globalGamma,1,1,1),e.globalGain=ct(e.globalGain,1,1,1),e.globalOffset=ct(e.globalOffset,0,0,0),e.shadowsSaturation=ct(e.shadowsSaturation,1,1,1),e.shadowsContrast=ct(e.shadowsContrast,1,1,1),e.shadowsGamma=ct(e.shadowsGamma,1,1,1),e.shadowsGain=ct(e.shadowsGain,1,1,1),e.shadowsOffset=ct(e.shadowsOffset,0,0,0),e.shadowsMax=.09,e.midtonesSaturation=ct(e.midtonesSaturation,1,1,1),e.midtonesContrast=ct(e.midtonesContrast,1,1,1),e.midtonesGamma=ct(e.midtonesGamma,1,1,1),e.midtonesGain=ct(e.midtonesGain,1,1,1),e.midtonesOffset=ct(e.midtonesOffset,0,0,0),e.highlightsSaturation=ct(e.highlightsSaturation,1,1,1),e.highlightsContrast=ct(e.highlightsContrast,1,1,1),e.highlightsGamma=ct(e.highlightsGamma,1,1,1),e.highlightsGain=ct(e.highlightsGain,1,1,1),e.highlightsOffset=ct(e.highlightsOffset,0,0,0),e.highlightsMin=.5,e.lut=void 0,e.lutIntensity=0}(this.postProcessSettings,this.baseToneMapping,this.baseToneMappingExposure);const e=this.postProcessSettings;let t,s=!1;if(null==this.camera)return;const a=this.camera.getWorldPosition(gt);let n=[];for(const r of this.postProcessVolumes){if(!nt(r.object))continue;let o=r.blendWeight??1;const l=r.distanceToPoint(a);l>r.blendRadius||(r.blendRadius>0&&(o*=ve(1-l/r.blendRadius,0,1)),o>1&&(o=1),o>0&&(n.push(r),void 0!==r.settings.tonemapMapping&&(e.tonemapMapping=r.settings.tonemapMapping),void 0!==r.settings.tonemapExposure&&(e.tonemapExposure=i.MathUtils.lerp(e.tonemapExposure,r.settings.tonemapExposure,o)),void 0!==r.settings.envTexture&&(e.envTexture=r.settings.envTexture),void 0!==r.settings.envIntensity&&(e.envIntensity=i.MathUtils.lerp(e.envIntensity,r.settings.envIntensity,o)),void 0!==r.settings.vignetteIntensity&&(e.vignetteIntensity=i.MathUtils.lerp(e.vignetteIntensity,r.settings.vignetteIntensity,o)),void 0!==r.settings.colorTint&&void 0!==r.settings.colorTintIntensity&&r.settings.colorTintIntensity>0&&(e.colorTint=e.colorTint.lerp(r.settings.colorTint,o)),void 0!==r.settings.colorTintIntensity&&(e.colorTintIntensity=i.MathUtils.lerp(e.colorTintIntensity,r.settings.colorTintIntensity,o)),void 0!==r.settings.depthFocus&&(s=!0,e.depthFocus=void 0!==e.depthFocus?i.MathUtils.lerp(e.depthFocus,r.settings.depthFocus,o):r.settings.depthFocus),void 0!==r.settings.depthAperture&&(s=!0,e.depthAperture=void 0!==e.depthAperture?i.MathUtils.lerp(e.depthAperture,r.settings.depthAperture,o):r.settings.depthAperture),void 0!==r.settings.depthMaxBlur&&(s=!0,e.depthMaxBlur=void 0!==e.depthMaxBlur?i.MathUtils.lerp(e.depthMaxBlur,r.settings.depthMaxBlur,o):r.settings.depthMaxBlur),void 0!==r.settings.temperature&&(e.temperature=i.MathUtils.lerp(e.temperature,r.settings.temperature,o)),void 0!==r.settings.temperatureTint&&(e.temperatureTint=i.MathUtils.lerp(e.temperatureTint,r.settings.temperatureTint,o)),void 0!==r.settings.globalSaturation&&e.globalSaturation.lerp(r.settings.globalSaturation,o),void 0!==r.settings.globalContrast&&e.globalContrast.lerp(r.settings.globalContrast,o),void 0!==r.settings.globalGamma&&e.globalGamma.lerp(r.settings.globalGamma,o),void 0!==r.settings.globalGain&&e.globalGain.lerp(r.settings.globalGain,o),void 0!==r.settings.globalOffset&&e.globalOffset.lerp(r.settings.globalOffset,o),void 0!==r.settings.shadowsSaturation&&e.shadowsSaturation.lerp(r.settings.shadowsSaturation,o),void 0!==r.settings.shadowsContrast&&e.shadowsContrast.lerp(r.settings.shadowsContrast,o),void 0!==r.settings.shadowsGamma&&e.shadowsGamma.lerp(r.settings.shadowsGamma,o),void 0!==r.settings.shadowsGain&&e.shadowsGain.lerp(r.settings.shadowsGain,o),void 0!==r.settings.shadowsOffset&&e.shadowsOffset.lerp(r.settings.shadowsOffset,o),void 0!==r.settings.shadowsMax&&(e.shadowsMax=i.MathUtils.lerp(e.shadowsMax,r.settings.shadowsMax,o)),void 0!==r.settings.midtonesSaturation&&e.midtonesSaturation.lerp(r.settings.midtonesSaturation,o),void 0!==r.settings.midtonesContrast&&e.midtonesContrast.lerp(r.settings.midtonesContrast,o),void 0!==r.settings.midtonesGamma&&e.midtonesGamma.lerp(r.settings.midtonesGamma,o),void 0!==r.settings.midtonesGain&&e.midtonesGain.lerp(r.settings.midtonesGain,o),void 0!==r.settings.midtonesOffset&&e.midtonesOffset.lerp(r.settings.midtonesOffset,o),void 0!==r.settings.highlightsSaturation&&e.highlightsSaturation.lerp(r.settings.highlightsSaturation,o),void 0!==r.settings.highlightsContrast&&e.highlightsContrast.lerp(r.settings.highlightsContrast,o),void 0!==r.settings.highlightsGamma&&e.highlightsGamma.lerp(r.settings.highlightsGamma,o),void 0!==r.settings.highlightsGain&&e.highlightsGain.lerp(r.settings.highlightsGain,o),void 0!==r.settings.highlightsOffset&&e.highlightsOffset.lerp(r.settings.highlightsOffset,o),void 0!==r.settings.highlightsMin&&(e.highlightsMin=i.MathUtils.lerp(e.highlightsMin,r.settings.highlightsMin,o)),void 0!==r.settings.lut&&(t=r.settings.lut),void 0!==r.settings.lutIntensity&&(e.lutIntensity=i.MathUtils.lerp(e.lutIntensity,r.settings.lutIntensity,o))))}if(0===n.length)return this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure);const r=e.vignetteIntensity>ft,o=(h=e.temperature,p=e.temperatureTint,!dt(h,6500)||!dt(p,0));var h,p;const c=(u=e.colorTint,e.colorTintIntensity>ft&&(!dt(u.r,1)||!dt(u.g,1)||!dt(u.b,1)));var u;const d=!(ut((m=e).globalSaturation,1,1,1)&&ut(m.globalContrast,1,1,1)&&ut(m.globalGamma,1,1,1)&&ut(m.globalGain,1,1,1)&&ut(m.globalOffset,0,0,0)&&ut(m.shadowsSaturation,1,1,1)&&ut(m.shadowsContrast,1,1,1)&&ut(m.shadowsGamma,1,1,1)&&ut(m.shadowsGain,1,1,1)&&ut(m.shadowsOffset,0,0,0)&&ut(m.midtonesSaturation,1,1,1)&&ut(m.midtonesContrast,1,1,1)&&ut(m.midtonesGamma,1,1,1)&&ut(m.midtonesGain,1,1,1)&&ut(m.midtonesOffset,0,0,0)&&ut(m.highlightsSaturation,1,1,1)&&ut(m.highlightsContrast,1,1,1)&&ut(m.highlightsGamma,1,1,1)&&ut(m.highlightsGain,1,1,1)&&ut(m.highlightsOffset,0,0,0));var m;const f=o||c||d||r,g=f&&e.tonemapMapping!==i.NoToneMapping,M=null!=t&&e.lutIntensity>ft;f?(this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1):(this.renderer.toneMapping=e.tonemapMapping,this.renderer.toneMappingExposure=e.tonemapExposure),null!=e.envTexture&&(this.scene.environment=this.getEnvTexture(e.envTexture)),this.scene.environmentIntensity=e.envIntensity,f?(this.colorPass.whiteBalanceEnabled=o,this.colorPass.whiteBalanceScale=o?function(e,t,s){const i=function(e){const t=ve(e,1e3,4e4)/100,s=t<=66?1:ve(1.292936186062745*Math.pow(t-60,-.1332047592),0,1),i=ve(t<=66?.3900815787690196*Math.log(t)-.6318414437886275:1.129890860895294*Math.pow(t-60,-.0755148492),0,1),a=t>=66?1:t<=19?0:ve(.5432067891101962*Math.log(t-10)-1.19625408914,0,1);return vt.set(s,i,a)}(t),a=1+.2*ve(s,-1,1),n=i.x,r=i.y*a,o=i.z,l=Math.max(r,1e-4);return e.set(1/Math.max(n/l,1e-4),1/Math.max(r/l,1e-4),1/Math.max(o/l,1e-4)),e}(Mt,e.temperature,e.temperatureTint):Mt.set(1,1,1),this.colorPass.vignetteIntensity=e.vignetteIntensity,this.colorPass.vignetteEnabled=r,this.colorPass.colorTintEnabled=c,this.colorPass.colorTint=e.colorTint,this.colorPass.colorTintIntensity=e.colorTintIntensity,this.colorPass.colorGradingEnabled=d,this.colorPass.toneMapping=e.tonemapMapping,this.colorPass.toneMappingEnabled=g,this.colorPass.toneMappingExposure=e.tonemapExposure,this.colorPass.globalSaturation=e.globalSaturation,this.colorPass.globalContrast=e.globalContrast,this.colorPass.globalGamma=e.globalGamma,this.colorPass.globalGain=e.globalGain,this.colorPass.globalOffset=e.globalOffset,this.colorPass.shadowsSaturation=e.shadowsSaturation,this.colorPass.shadowsContrast=e.shadowsContrast,this.colorPass.shadowsGamma=e.shadowsGamma,this.colorPass.shadowsGain=e.shadowsGain,this.colorPass.shadowsOffset=e.shadowsOffset,this.colorPass.shadowsMax=e.shadowsMax,this.colorPass.midtonesSaturation=e.midtonesSaturation,this.colorPass.midtonesContrast=e.midtonesContrast,this.colorPass.midtonesGamma=e.midtonesGamma,this.colorPass.midtonesGain=e.midtonesGain,this.colorPass.midtonesOffset=e.midtonesOffset,this.colorPass.highlightsSaturation=e.highlightsSaturation,this.colorPass.highlightsContrast=e.highlightsContrast,this.colorPass.highlightsGamma=e.highlightsGamma,this.colorPass.highlightsGain=e.highlightsGain,this.colorPass.highlightsOffset=e.highlightsOffset,this.colorPass.highlightsMin=e.highlightsMin,this.colorPass.enabled=!0):this.colorPass.enabled=!1,s&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==e.depthFocus&&(this.dofPass.uniforms.focus.value=e.depthFocus),void 0!==e.depthAperture&&(this.dofPass.uniforms.aperture.value=e.depthAperture),void 0!==e.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=e.depthMaxBlur)):this.dofPass.enabled=!1,this.lutPass.enabled=M,M&&(null!=t&&(t.flipY=!0,t.generateMipmaps=!1),this.lutPass.lut=t,this.lutPass.intensity=e.lutIntensity)}updatePostProcessEffectUniforms(e){if(0===this.postProcessEffects.length)return;const t=this.postProcessEffectUniformState;t.aoEnabled=this.aoPass.enabled,t.aoTexture=this.aoPass.enabled?this.aoPass.pdRenderTarget.texture:null,this.camera instanceof l?(t.cameraNear=this.camera.near,t.cameraFar=this.camera.far):(t.cameraNear=void 0,t.cameraFar=void 0),t.depthTexture=this.sceneColorRenderTarget.textures[1],t.normalTexture=this.gRenderTarget.textures[2],t.resolution.set(this.gRenderTarget.width,this.gRenderTarget.height),t.simulationTime=e;for(const e of this.postProcessEffects)e.pass.updateUniformState(t)}renderOverlay(){if(!this.running)return;if(0===this.overlayCameras.size)return;const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.previousClientWith/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}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;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof o&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,lt)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.options.bloom,this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=ge(this.scene,e=>e instanceof o&&!0===e.material?.userData?.hasBloom)}darkenNonBloomed(e){if((e instanceof o||e instanceof i.Sprite||e instanceof i.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)){if(e.material?.id===ke.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=ke:(e.visible=!1,this.bloomHidden.push(e))}else"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)}initSceneColorUniform(e){if(e instanceof p)return null==e.uniforms[ue]?(e.uniforms[ue]={value:this.sceneColorRenderTarget.texture},void(e.uniformsNeedUpdate=!0)):void(e.uniforms[ue].value!==this.sceneColorRenderTarget.texture&&(e.uniforms[ue].value=this.sceneColorRenderTarget.texture,e.uniformsNeedUpdate=!0))}initDepthUniform(e){e instanceof p&&(e.uniforms[ie].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[ne]&&(e.uniforms[ne].value=this.camera.near),null!=e.uniforms[ae]&&(e.uniforms[ae].value=this.camera.far)))}initNormalUniform(e){e instanceof p&&null!=e.uniforms[oe]&&(e.uniforms[oe].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof C&&(t.uniforms.receiveShadow?t.uniforms.receiveShadow.value=e.receiveShadow:t.uniforms.receiveShadow={value:e.receiveShadow})}initLightVolumeUniform(e){e instanceof C&&(null!=this.lightVolume?null==e.uniforms.uSH?(e.defines.USE_LIGHT_PROBE_VOLUME="",e.uniforms.gridOrigin={value:this.lightVolume.gridOrigin},e.uniforms.gridSize={value:this.lightVolume.gridSize},e.uniforms.gridRes={value:this.lightVolume.gridResolution},e.uniforms.giIntensity={value:this.lightProbeIntensity},e.uniforms.uSH={value:this.lightVolume.shTexture},e.uniformsNeedUpdate=!0,e.needsUpdate=!0):e.uniforms.giIntensity.value=this.lightProbeIntensity:null!=e.uniforms.uSH&&(delete e.defines.USE_LIGHT_PROBE_VOLUME,delete e.uniforms.gridOrigin,delete e.uniforms.gridSize,delete e.uniforms.gridRes,delete e.uniforms.giIntensity,delete e.uniforms.uSH,e.uniformsNeedUpdate=!0,e.needsUpdate=!0))}initResolutionUniform(e){e instanceof p&&null!=e.uniforms[re]&&e.uniforms[re].value.set(this.gRenderTarget.width,this.gRenderTarget.height)}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[ce].value=this.aoPass.pdRenderTarget.texture,null==e.defines.USE_SSAO_MAP&&(e.defines.USE_SSAO_MAP="",e.needsUpdate=!0),e.defines.USE_SSAO_MAP="";const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}else if(null!=e.defines.USE_SSAO_MAP){delete e.defines.USE_SSAO_MAP,e.needsUpdate=!0;const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}}initCustomDepthMaterial(e){if(null!=e.customDepthMaterial||!e.castShadow)return;const t=e.material;if(!(t instanceof C&&t.depthWrite&&t.alphaTest>0))return;let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Oe(Ae);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new C({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}};it.activeView=null,it=e=t([se(),s("design:paramtypes",[HTMLElement,Object])],it);export{it as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const at=.05;function nt(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}function rt(e,t){return e.priority!==t.priority?e.priority-t.priority:e.id-t.id}function ot(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}te.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.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};const lt=new i.Frustum,ht=new i.Box3,pt=new i.Matrix4;export function isObjectInFrustum(e,t){const s=ht.setFromObject(e);return t.intersectsBox(s)}function ct(e,t,s,a){return null==e?new i.Vector3(t,s,a):e.set(t,s,a)}function ut(e,t,s,i){return null!=e&&dt(e.x,t)&&dt(e.y,s)&&dt(e.z,i)}function dt(e,t,s=ft){return Math.abs(e-t)<=s}function mt(e,t){return null!=e&&Number.isFinite(e)&&e>0?e:t}const ft=1e-4,gt=new i.Vector3,Mt=new i.Vector3(1,1,1),vt=new i.Vector3(1,1,1);const Pt=new r,yt=new d;function bt(e,t,s=new i.Matrix3){return yt.copy(e),yt.x*=-1,yt.y*=-1,yt.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(yt.y*=-1,yt.z*=-1),s.setFromMatrix4(Pt.makeRotationFromEuler(yt))}const wt=new C({outputs:[_(0,0,0,0),_(0,0,0,0),B(D("white"),je(4))],transparent:!0}),xt=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});wt.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),xt);function Tt(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isLineSegments2||e.isTransformControls||e.isTransformControlsGizmo||e instanceof o&&St(e,e.material)}function St(e,t){return null==t||(Array.isArray(t)?t.some(t=>St(e,t)):t instanceof i.RawShaderMaterial||t instanceof i.ShaderMaterial&&!(t instanceof C))}class Rt extends Ve{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.cachedVisibility=[],this.toRender=[],this.needsSwap=!1}render(e,t,s,i,a){const n=e.autoClear;e.autoClear=!1;const r=this.scene.matrixWorldAutoUpdate,l=this.scene.matrixAutoUpdate,h=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const p=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),this.cachedVisibility.length=0;let c=0,u=this.toRender;if(u.length=0,this.scene.traverseVisible(e=>{const t=Tt(e);e instanceof o&&!t?(this.cachedVisibility.push(e),e.visible=!1):t&&(c++,u.push(e))}),c>0)for(const t of u)e.render(t,this.camera);this.cachedVisibility.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=n,s.depthTexture=p,this.scene.matrixWorldAutoUpdate=r,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class Ct extends Ve{constructor(e){super(),this.fn=e}render(e,t,s,i,a){this.fn(e,t,s,i,a)}}const Ut=["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"],Et=["directionalShadowMap","directionalShadowMatrix","pointLightShadows","pointShadowMap","pointShadowMatrix","spotLightShadows","spotShadowMap"],At=A("fogColor");export class FogNode extends k{constructor(e,t=At){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),a=e.get(this.fogColor),n=e.get(E("fogFar")),r=e.get(E("fogNear")),o=e.get(E("fogDensity")),l=e.get(I(j.mvPosition.z));return{pars:"\n ",chunk:`\n #ifdef FOG_EXP2\n float fogFactor_${t} = 1.0 - exp( - ${o} * ${o} * ${l} * ${l} );\n #else\n float fogFactor_${t} = smoothstep( ${r}, ${n}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${a}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}const Ot=new i.MeshDepthMaterial({depthPacking:i.RGBADepthPacking});/*
1
+ var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as a,Material as n,Matrix4 as r,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as p,WebGLRenderTarget as c,Texture as u,Euler as d,MeshStandardMaterial as m}from"three";import{CopyShader as f,EffectComposer as g,FXAAShader as M,GammaCorrectionShader as v,LUTPass as P,RenderPass as y,ShaderPass as b,VRButton as w}from"three-stdlib";import{CSMShader as x,CSMUtil as T}from"./csm.js";import{colorToNormal as S,float as R,NodeShaderMaterial as C,standardMaterial as U,uniformFloat as E,uniformVec3 as A,toonMaterial as O,lambertMaterial as F,normalize as G,rgb as D,rgba as B,transformed as j,varying as I,varyingAttributes as V,varyingTransformed as L,vec4 as _,BooleanExpression as W,select as N,ifDefApply as H,uniformSampler2d as q,RgbaNode as k,mix as z,attributes as $,uniformVec2 as J}from"three-shader-graph";import{Reflector as X}from"three-stdlib";import{BokehPass as Y,OutputPass as K}from"three/examples/jsm/Addons.js";import{CSM as Q}from"three/examples/jsm/csm/CSM.js";import{RectAreaLightUniformsLib as Z}from"three/examples/jsm/lights/RectAreaLightUniformsLib.js";import ee from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as te}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as se}from"typedi";import{depthUniformName as ie,farUniformName as ae,nearUniformName as ne,resolutionUniformName as re,sceneNormalUniformName as oe,screenUV as le,supportsDepthTextureExtension as he}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as pe}from"./shader-nodes/time.js";import{aoMapUniformName as ce,sceneMapUniformName as ue}from"./shader-nodes/scene-sample.js";import{DepthPass as de}from"./utils/three/depth-pass.js";import{GPUStatsPanel as me}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as fe}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as ge,traverseVisibleStop as Me}from"./utils/three/traverse.js";import{clamp as ve}from"./utils/math.js";import{ColorPass as Pe}from"./rendering/color-pass.js";import{PostProcessEffectPass as ye,PostProcessEffectRegistration as be,postProcessEffectStages as we,sanitizePostProcessEffectPriority as xe,sanitizePostProcessEffectStage as Te}from"./rendering/post-process-effect.js";import{SSRPass as Se}from"./rendering/ssr/SSRPass.js";import{SSRShader as Re}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as Ce}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as Ue}from"./rendering/outline-effect.js";import{UnrealBloomPass as Ee}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as Ae}from"./shader-nodes/depth.js";import{packDepthToRGBA as Oe}from"three-shader-graph";import{FogVolumeObject as Fe}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Ge}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as De}from"./shader-nodes/pom.js";import{FullScreenQuad as Be}from"three-stdlib";import{edgeDepthEffect as je}from"./shader-nodes/effects";import{decalDiscard as Ie}from"./shader-nodes/decal.js";import{Pass as Ve}from"three/examples/jsm/Addons.js";import{BatchedMesh2 as Le}from"./scene/batched-mesh-2.js";import{applyUvTiling as _e}from"./shader/uv-nodes.js";import{getTemporalUpscalingJitter as We,getUpscalingMethod as Ne,UpscaleOutputPass as He}from"./rendering/upscaling-pass.js";T.patchSetupMaterial();const qe=document.createElement("div");qe.style.position="absolute",qe.style.left="50%",qe.style.top="50%",qe.style.color="black",qe.style.zIndex="999";(new i.Layers).set(9);const ke=new i.MeshBasicMaterial({color:"black"}),ze=new i.MeshDepthMaterial;var $e;ze.depthPacking=i.RGBADepthPacking,ze.blending=i.NoBlending,ze.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}($e||($e={}));const Je=(()=>{const e=new Uint8Array([255,255,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Xe=(()=>{const e=new Uint8Array([0,0,0,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ye=(()=>{const e=new Uint8Array([128,128,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ke=new C({color:R(0),position:_(R(0))});Ke.visible=!1;const Qe=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let Ze=0,et=null;const tt=new Map;function st(){return null==et&&(et=new IntersectionObserver(e=>{for(const t of e){const e=tt.get(t.target);e&&e(t.isIntersecting)}},{threshold:0})),et}let it=e=class{get fpsCap(){return this._fpsCap}set fpsCap(e){const t=null!=e&&Number.isFinite(e)&&e>0?e:null;t!==this._fpsCap&&(this._fpsCap=t,this.fpsCapRevision++)}setPaused(e){this.paused=e}get currentResolutionScale(){return this.getEffectiveResolutionScale()}get currentRenderPixelRatio(){return this.getRenderPixelRatio()}get currentPresentationPixelRatio(){return this.getPresentationPixelRatio()}getRenderSize(e=new i.Vector2){return e.set(Math.max(1,this.container.clientWidth*this.getRenderPixelRatio()),Math.max(1,this.container.clientHeight*this.getRenderPixelRatio()))}isUpscalingEnabled(){return!0===this.options.upscaling?.enabled&&!0!==this.options.enableXR}isTemporalUpscalingEnabled(){return this.isUpscalingEnabled()&&"temporal"===Ne(this.options.upscaling)}resetUpscalingHistory(){this.hasPreviousTemporalViewProjection=!1,this.upscaleOutputPass?.resetHistory()}prepareUpscalingFrame(){if(!this.isTemporalUpscalingEnabled()||null==this.upscaleOutputPass)return void this.upscaleOutputPass?.setFrameState(null);this.unjitteredProjectionMatrix.copy(this.camera.projectionMatrix),this.currentUnjitteredViewProjectionMatrix.multiplyMatrices(this.unjitteredProjectionMatrix,this.camera.matrixWorldInverse),this.hasPreviousTemporalViewProjection||(this.previousViewProjectionMatrix.copy(this.currentUnjitteredViewProjectionMatrix),this.upscaleOutputPass.resetHistory());const e=mt(this.options.upscaling?.temporal?.jitterScale,1);We(this.temporalUpscalingFrameIndex++,this.temporalJitter,e),this.temporalJitterUv.set(this.temporalJitter.x/Math.max(1,this.gRenderTarget.width),this.temporalJitter.y/Math.max(1,this.gRenderTarget.height));const t=2*this.temporalJitter.x/Math.max(1,this.gRenderTarget.width),s=2*this.temporalJitter.y/Math.max(1,this.gRenderTarget.height);this.camera instanceof l?(this.camera.projectionMatrix.elements[8]+=t,this.camera.projectionMatrix.elements[9]+=s):(this.camera.projectionMatrix.elements[12]+=t,this.camera.projectionMatrix.elements[13]+=s),this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(),this.projectionJitterApplied=!0,this.currentViewProjectionMatrix.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),this.currentViewProjectionMatrixInverse.copy(this.currentViewProjectionMatrix).invert(),this.temporalUpscalingFrameState.depthTexture=this.gRenderTarget.depthTexture,this.upscaleOutputPass.setFrameState(this.temporalUpscalingFrameState)}finishUpscalingFrame(){this.projectionJitterApplied&&(this.camera.projectionMatrix.copy(this.unjitteredProjectionMatrix),this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(),this.previousViewProjectionMatrix.copy(this.currentUnjitteredViewProjectionMatrix),this.hasPreviousTemporalViewProjection=!0,this.projectionJitterApplied=!1)}getBasePixelRatio(){const e=mt(this.maxPixelRatio,1),t=mt(window.devicePixelRatio,1);return Math.min(e,t)}getBaseResolutionScale(){return mt(this.resolutionScale,1)}getDynamicResolutionMinScale(){const e=this.getBaseResolutionScale(),t=mt(this.options.dynamicResolution?.minScale,.7);return Math.min(e,t)}getEffectiveResolutionScale(){const e=this.getBaseResolutionScale();return!0!==this.options.dynamicResolution?.enabled?e:ve(this.dynamicResolutionScale,this.getDynamicResolutionMinScale(),e)}getRenderPixelRatio(){return this.getBasePixelRatio()*this.getEffectiveResolutionScale()}getPresentationPixelRatio(){const e=this.getBasePixelRatio();return this.isUpscalingEnabled()?e:e*this.getEffectiveResolutionScale()}resetDynamicResolutionAverage(){this.dynamicResolutionFrameTimeAverage=null,this.dynamicResolutionFrameSamples=0}updateDynamicResolution(e,t){const s=this.options.dynamicResolution;if(!0!==s?.enabled)return;if(!Number.isFinite(e)||e<=0||e>.25)return void this.resetDynamicResolutionAverage();const i=this.getBaseResolutionScale(),a=this.getDynamicResolutionMinScale(),n=ve(this.dynamicResolutionScale,a,i);dt(n,this.dynamicResolutionScale)||(this.dynamicResolutionScale=n);const r=mt(s.targetFps,60),o=1e3/(null!=this.fpsCap?Math.min(r,this.fpsCap):r),l=1e3*e;this.dynamicResolutionFrameTimeAverage=null==this.dynamicResolutionFrameTimeAverage?l:.9*this.dynamicResolutionFrameTimeAverage+.1*l,this.dynamicResolutionFrameSamples++;const h=Math.max(1,Math.floor(mt(s.sampleFrames,20)));if(this.dynamicResolutionFrameSamples<h)return;const p=mt(s.decreaseCooldown,500),c=mt(s.increaseCooldown,2e3),u=mt(s.decreaseStep,.05),d=mt(s.increaseStep,.025),m=this.dynamicResolutionFrameTimeAverage;let f=n;m>1.12*o&&n>a&&t-this.dynamicResolutionLastAdjustmentAt>=p?f=Math.max(a,n-u):m<.85*o&&n<i&&t-this.dynamicResolutionLastAdjustmentAt>=c&&(f=Math.min(i,n+d)),dt(f,n)||(this.dynamicResolutionScale=f,this.dynamicResolutionLastAdjustmentAt=t,this.resetDynamicResolutionAverage(),this.resizeRender(!0))}resizeRender(e=!1){if(!this.running)return;const t=this.container.clientWidth,s=this.container.clientHeight,i=this.getRenderPixelRatio(),a=this.getPresentationPixelRatio();if(!e&&this.previousClientWith===t&&this.previousClientHeight===s&&this.previousRenderPixelRatio===i&&this.previousPresentationPixelRatio===a)return;if(0===t||0===s)return;this.previousClientWith=t,this.previousClientHeight=s,this.previousRenderPixelRatio=i,this.previousPresentationPixelRatio=a,this.camera instanceof l&&(this.camera.aspect=t/s,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(a),this.renderer.setSize(t,s),this.composer.setPixelRatio(i),this.composer.setSize(t,s);const n=t*i,r=s*i;this.dofPass.setSize(n,r),this.fxaaPass.setSize(n,r),this.fxaaPass.uniforms.resolution.value.set(1/n,1/r),this.createGRenderTarget(),this.phasedRenderPass.gRenderTarget=this.gRenderTarget,this.bloomPass.emissiveTexture=this.gRenderTarget.textures[1],this.ssrPass.setSize(this.gRenderTarget.width,this.gRenderTarget.height),this.ssrPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.aoPass.setSize(this.gRenderTarget.width,this.gRenderTarget.height),this.aoPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.sceneColorRenderTarget.dispose(),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container),this.copyPass.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass.material.uniformsNeedUpdate=!0,this.resetDynamicResolutionAverage(),this.resetUpscalingHistory()}addPostProcessVolume(e){if(0===this.postProcessVolumes.length)this.postProcessVolumes.push(e);else{let t=!1;for(let s=0;s<this.postProcessVolumes.length;s++)if(e.priority<this.postProcessVolumes[s].priority){this.postProcessVolumes.splice(s,0,e),t=!0;break}t||this.postProcessVolumes.push(e)}}removePostProcessVolume(e){const t=this.postProcessVolumes.indexOf(e);t>-1&&this.postProcessVolumes.splice(t,1)}addPostProcessEffect(e,t={}){const s={id:++this.postProcessEffectId,pass:new ye(e),priority:xe(t.priority),stage:Te(t.stage)};return s.pass.enabled=t.enabled??!0,this.postProcessEffects.push(s),this.refreshPostProcessEffectPassOrder(),new be(this,s)}removePostProcessEffectEntry(e){const t=e,s=this.postProcessEffects.indexOf(t);-1!==s&&(this.postProcessEffects.splice(s,1),this.composer.removePass(t.pass),t.pass.dispose())}refreshPostProcessEffectPassOrder(){for(const e of this.postProcessEffects)this.composer.removePass(e.pass);for(const e of we){const t=this.getPostProcessEffectStageAnchorPass(e),s=null!=t?this.composer.passes.indexOf(t):this.composer.passes.length,i=this.postProcessEffects.filter(t=>t.stage===e).sort(rt);for(let e=0;e<i.length;e++)this.composer.insertPass(i[e].pass,s+e)}}getPostProcessEffectStageAnchorPass(e){switch(e){case"beforeFog":return this.volumetricFogPass;case"beforeDepthOfField":return this.dofPass;case"beforeColorAdjustment":return this.colorPass;case"beforeOutline":return this.outlinePass;case"beforeAntiAliasing":return this.fxaaPass;case"beforeLut":return this.lutPass;case"beforeOutput":return this.outputPass}}constructor(t,s={}){this.container=t,this.options=s,this.isIntersecting=!1,this.windowVisible=!0,this.running=!0,this.paused=!1,this._fpsCap=null,this.fpsCapRevision=0,this.postProcessVolumes=[],this.postProcessSettings={},this.baseToneMapping=i.NoToneMapping,this.baseToneMappingExposure=1,this.csmUpdateInvervals=this.options.shadows?.cascadeUpdateIntervals,this._id=Ze++,this.postProcessEffectId=0,this.postProcessEffects=[],this.postProcessEffectResolution=new i.Vector2(1,1),this.postProcessEffectUniformState={aoEnabled:!1,aoTexture:null,cameraFar:void 0,cameraNear:void 0,depthTexture:new u,normalTexture:new u,resolution:this.postProcessEffectResolution,simulationTime:0},this.fquadCopy=new Be(new p(f)),this.fquadCopyOpaque=new Be(new C({outputs:[q("tSceneColor",new u).sample(V.uv),_(q("tDepthTexture",new i.DepthTexture(1,1)).sample(V.uv).r)]})),this.simulationTime=0,this.simulationTimeScale=1,this.lightProbeIntensity=2,this.fquadBlendAO=(()=>{const e=_(1),t=new C({outputs:[q("tAO",new u).sample(le),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Be(t)})(),this.resolutionScale=1,this.maxPixelRatio=Qe?1:window.devicePixelRatio,this.dynamicResolutionScale=1,this.dynamicResolutionFrameTimeAverage=null,this.dynamicResolutionFrameSamples=0,this.dynamicResolutionLastAdjustmentAt=0,this.upscaleOutputPass=null,this.unjitteredProjectionMatrix=new r,this.temporalJitter=new i.Vector2,this.temporalJitterUv=new i.Vector2,this.currentUnjitteredViewProjectionMatrix=new r,this.currentViewProjectionMatrix=new r,this.currentViewProjectionMatrixInverse=new r,this.previousViewProjectionMatrix=new r,this.temporalUpscalingFrameState={depthTexture:null,currentJitterUv:this.temporalJitterUv,currentViewProjectionInverse:this.currentViewProjectionMatrixInverse,previousViewProjection:this.previousViewProjectionMatrix},this.temporalUpscalingFrameIndex=0,this.hasPreviousTemporalViewProjection=!1,this.projectionJitterApplied=!1,this.onResize=()=>{if(this.resizeRender(),!this.paused)try{this.render()}catch(e){}},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!0,this.onLoopCallbacks=[],this.stats=new ee,this._showStats=!1,this.gbufferMaterialCache=new Map,this.gbufferDepthPrepassMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.depthPrepassMaterialCache=new WeakMap,this.depthPrepassCachedMaterials=new Map,this.depthPrepassCachedVisibility=[],this.gBufferCachedMaterials=new Map,this.gBufferCachedVisibility=[],this._initiatedMaterialTextures=new Set,this._initiatedTextures=new Set,this.compileInProgress=!1,this.pmremGeneratorResults=new WeakMap,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 a,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,this.dynamicResolutionScale=this.getBaseResolutionScale(),this.fpsCap=s.fpsCap,e.activeView=this,Z.init(),window.renderer=this.renderer=window.renderer??new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}.bind(this.scene),this.renderer.setPixelRatio(this.getPresentationPixelRatio()),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(w.createButton(this.renderer));const n=new Ue(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=n,this.createGRenderTarget(),this.composer=new g(this.renderer,function(e,t){const s=new i.WebGLRenderTarget(Math.max(1,e),Math.max(1,t),{minFilter:i.LinearFilter,magFilter:i.LinearFilter,format:i.RGBAFormat,type:i.HalfFloatType});return s.texture.name="EffectComposer.rt1",s.texture.generateMipmaps=!1,s}(t.clientWidth,t.clientHeight)),this.composer.setPixelRatio(this.getRenderPixelRatio()),this.composer.setSize(t.clientWidth,t.clientHeight);var o=(t.clientWidth||1)/(t.clientHeight||1);const l=new i.PerspectiveCamera(45,o,.5,800);l.layers.enable(19),this.setCamera(l),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=i.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=s.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=i.SRGBColorSpace,this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1,this.baseToneMapping=this.renderer.toneMapping,this.baseToneMappingExposure=this.renderer.toneMappingExposure,this.renderer.gammaFactor=1.4,T.renderingView=this,this.isDepthTextureExtensionSupported=he(this.renderer),this.attachRendererDomElement(),this.setupEventListeners(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container,this.getRenderPixelRatio()),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container);const h=new i.Vector2(t.clientWidth,t.clientHeight),c=(new y(this.scene,this.camera),new b(f,"prevtexture"));c.enabled=!0,c.needsSwap=!0,c.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=c;const d=new Ee(h,1.5,.4,.85);d.threshold=1,d.strength=.9,d.radius=.2,this.bloomPass=d;const m=new te(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});m.normalRenderTarget?.dispose(),m.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),m.output=te.OUTPUT.Off,m.enabled=!1,this.aoPass=m,this.fquadBlendAO.material.uniforms.tAO.value=m.pdRenderTarget.texture,Re.fragmentShader=Re.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const x=new Se({renderer:this.renderer,scene:this.scene,camera:this.camera,width:this.gRenderTarget.width,height:this.gRenderTarget.height,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[2],depthTexture:this.gRenderTarget.depthTexture});x.output=Se.OUTPUT.Default,x.blur=!0,x.fresnel=!1,x.distanceAttenuation=!0,x.maxDistance=50,x.selective=!0,x.bouncing=!1,x.opacity=.4,x.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=x,!1!==this.options.ao?.enabled&&this.composer.addPass(m);const S=new Ct((e,t,s,i,a)=>{this.aoPass.enabled&&(this.initResolutionUniform(this.fquadBlendAO.material),this.renderer.setRenderTarget(this.gRenderTarget),this.fquadBlendAO.render(this.renderer),this.renderer.setRenderTarget(null))});this.composer.addPass(S);const R=new Ct((e,t,s,i,a)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene($e.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(R),this.composer.addPass(c),this.composer.addPass(x),this.phasedRenderPass=new Rt(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(d),d.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new Ce(h),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new Y(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const U=new Pe;this.composer.addPass(U),this.colorPass=U,U.vignetteEnabled=!1,this.outlinePass=new fe(new i.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const E=new b(M);E.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(E),this.fxaaPass=E,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new b(v).clear=!1,this.fixStatsStyle(),this.lutPass=new P({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const A=new b(f,"prevtexture");A.enabled=!0,A.needsSwap=!1,A.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],A.renderToScreen=!0;const O=this.isUpscalingEnabled()?new He(this.options.upscaling):new K;!function(e){const t=e.material;if(t.dithering=!0,t.fragmentShader.includes("<dithering_fragment>"))return;const s="#include <colorspace_pars_fragment>";if(!t.fragmentShader.includes(s))return;t.fragmentShader=t.fragmentShader.replace(s,`${s}\n #include <common>\n #include <dithering_pars_fragment>`);const i=t.fragmentShader.lastIndexOf("}");i<0||(t.fragmentShader=`${t.fragmentShader.slice(0,i)}\n #include <dithering_fragment>\n${t.fragmentShader.slice(i)}`,t.needsUpdate=!0)}(O),this.outputPass=O,this.upscaleOutputPass=O instanceof He?O:null,this.composer.addPass(O)}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"}setEnableOutlines(e){this.outlinePass.enabled=e,this.fxaaPass.enabled=e}setCamera(e){if(this.camera=e,this.resetUpscalingHistory(),this.composer.passes.forEach(t=>{t instanceof y?t.camera=e:t instanceof fe?t.renderCamera=e:(t instanceof de||t instanceof te)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),this.phasedRenderPass&&(this.phasedRenderPass.camera=e),null==this.csm){if(this.csm=new Q({maxFar:80,lightFar:250,lightMargin:20,cascades:Qe?2:3,shadowMapSize:1024*(Qe?.5:1),lightDirection:new i.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"}),null!=this.csmUpdateInvervals){this.csmCascadeLastUpdate=new Array(this.csm.lights.length).fill(0);for(const e of this.csm.lights)e.shadow.autoUpdate=!1}this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,h.lights_fragment_begin=x.lights_fragment_begin}else this.csm.camera=this.camera,this.camera;this.csm.updateFrustums()}setSelectedObjects(e){if(null==this.outlinePass)return;const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t,s){const a=Math.max(1,Math.floor(t.clientWidth*s)),n=Math.max(1,Math.floor(t.clientHeight*s)),r=new i.WebGLRenderTarget(a,n);return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new i.DepthTexture(a,n),r.depthTexture.type=i.UnsignedShortType,r.depthTexture.minFilter=i.NearestFilter,r.depthTexture.magFilter=i.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t,s=e.getPixelRatio()){const a=Math.max(1,t.clientWidth*s),n=Math.max(1,t.clientHeight*s),r=new i.DepthTexture(a,n);r.type=i.UnsignedInt248Type,r.minFilter=i.NearestFilter,r.magFilter=i.NearestFilter;const o=new i.WebGLRenderTarget(a,n,{type:i.HalfFloatType,depthTexture:r});return o.texture.minFilter=i.NearestFilter,o.texture.magFilter=i.NearestFilter,o.texture.generateMipmaps=!1,o.stencilBuffer=!1,o}createSceneColorRenderTarget(e,t){const s=this.gRenderTarget.width,a=this.gRenderTarget.height,n=new i.WebGLRenderTarget(s,a,{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return n.texture.minFilter=i.LinearFilter,n.texture.magFilter=i.LinearFilter,n.texture.generateMipmaps=!1,n.textures[1].minFilter=i.NearestFilter,n.textures[1].magFilter=i.NearestFilter,n}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose();const t=this.getRenderPixelRatio(),s=Math.max(1,e.clientWidth*t),a=Math.max(1,e.clientHeight*t),n=new i.DepthTexture(s,a);n.type=i.UnsignedIntType,n.minFilter=i.NearestFilter,n.magFilter=i.NearestFilter,this.gRenderTarget=new c(s,a,{count:3,samples:this.options?.msaa??(Qe?void 0:2),minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat,depthTexture:n}),this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(e=!0){this.running=!1,this.lightVolume?.shTexture.dispose(),window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],e&&this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose();for(const e of this.postProcessEffects)this.composer.removePass(e.pass),e.pass.dispose();this.postProcessEffects.length=0,this.detachOwnedDomElements();st().unobserve(this.container),tt.delete(this.container),this.volumetricFogPass.dispose(),T.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.findIndex(t=>t===e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&this.stats.dom.parentElement!==this.container?this.container.appendChild(this.stats.dom):this._showStats||this.stats.dom.parentElement!==this.container||this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}attachRendererDomElement(){const e=this.renderer.domElement;e.parentElement===this.container&&e===this.container.firstChild||this.container.insertBefore(e,this.container.firstChild),this._showStats&&this.stats.dom.parentElement!==this.container&&this.container.appendChild(this.stats.dom)}detachOwnedDomElements(){this.renderer.domElement.parentElement===this.container&&this.container.removeChild(this.renderer.domElement),this.stats.dom.parentElement===this.container&&this.container.removeChild(this.stats.dom)}applyEnvMap(e){if(null!=this.scene.environment&&(e instanceof C&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0,e.uniforms.envMapRotation={value:bt(this.scene.environmentRotation,this.scene.environment,new i.Matrix3)}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment),e instanceof C||e instanceof i.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateMaterialProperties(e,t){(e instanceof i.MeshBasicMaterial||e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(null!=t.uniforms.color&&t.uniforms.color.value.setFromColor(e.color),null!=t.uniforms.opacity&&(t.uniforms.opacity.value=e.opacity),null!=t.uniforms.map&&(t.uniforms.map.value=e.map),null!=t.uniforms.alphaMap&&(t.uniforms.alphaMap.value=e.alphaMap),null!=t.uniforms.lightMap&&(t.uniforms.lightMap.value=e.lightMap,t.uniforms.lightMapIntensity.value=e.lightMapIntensity),null!=t.uniforms.aoMap&&(t.uniforms.aoMap.value=e.aoMap,t.uniforms.aoMapIntensity.value=e.aoMapIntensity),null!=t.uniforms.alphaTest&&(t.uniforms.alphaTest.value=e.alphaTest)),(e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(t.uniforms.normalMap&&(t.uniforms.normalMap.value=e.normalMap,t.uniforms.normalScale.value=e.normalScale.x),t.uniforms.emissiveMap&&(t.uniforms.emissiveMap.value=e.emissiveMap,t.uniforms.emissive.value.setFromColor(e.emissive),t.uniforms.emissiveIntensity.value=e.emissiveIntensity)),e instanceof m&&(null!=t.uniforms.roughnessMap&&(t.uniforms.roughnessMap.value=e.roughnessMap),null!=t.uniforms.metalnessMap&&(t.uniforms.metalnessMap.value=e.metalnessMap),null!=t.uniforms.roughness&&(t.uniforms.roughness.value=e.roughness),null!=t.uniforms.metalness&&(t.uniforms.metalness.value=e.metalness)),e instanceof i.MeshPhysicalMaterial&&(t.uniforms.sheenColor&&t.uniforms.sheenColor.value.setFromColor(e.sheenColor).multiplyScalar(e.sheen),t.uniforms.sheenColorMap&&(t.uniforms.sheenColorMap.value=e.sheenColorMap),t.uniforms.sheenRoughness&&(t.uniforms.sheenRoughness.value=e.sheenRoughness),t.uniforms.sheenRoughnessMap&&(t.uniforms.sheenRoughnessMap.value=e.sheenRoughnessMap)),e instanceof Ge&&(t.uniforms.heightMap.value=e.heightMap,t.uniforms.heightScale.value=e.heightScale),this.updateMaterialCommonProperties(e,t)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],a=s[e].value;null!=t&&t.value!==a&&"receiveShadow"!==e&&!1===Ut.includes(e)&&(t.value=a)}this.updateMaterialCommonProperties(e,t)}inheritCustomUniformBindings(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s)null==i[e]&&("receiveShadow"===e||Ut.includes(e)||Et.includes(e)||(i[e]={value:s[e].value}))}updateMaterialCommonProperties(e,t){t.alphaTest=e.alphaTest,t.side=e.side,t.depthTest=e.depthTest,t.blending=e.blending,t.colorWrite=e.colorWrite,t.premultipliedAlpha=e.premultipliedAlpha,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.visible=e.visible}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of Ut){const t=i[e],a=s[e];null!=a&&null!=t&&(t.value=a.value)}}createGBufferMaterial(e,t,s=!1){const a=t===$e.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let n=a.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==n){let s=V.uv;if(e instanceof Ge&&null!=e.heightMap){const t=E("heightScale",e.heightScale??1);s=De(s,q("heightMap",e.heightMap),t)}let o=L.normal;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.normalMap??Ye,i=E("useNormalMap",null!=e.normalMap?1:0),a=E("normalScale",e.normalScale?.x??1),n=S(q("normalMap",t).sample(_e(s,e.normalMap)),a);o=z(L.normal,n,i)}else e instanceof C&&null!=e.outputNormal&&(o=e.outputNormal);!0!==e.userData.disableAO&&(o=H("DOUBLE_SIDED",o,e=>N(new W("gl_FrontFacing"),e,e.multiplyScalar(-1))));let l=e.userData?.reflective?R(0):R(1);if(e instanceof i.MeshStandardMaterial){const t=E("roughness",e.roughness??1),i=e.roughnessMap??Je,a=E("useRoughnessMap",null!=e.roughnessMap?1:0),n=q("roughnessMap",i).sample(_e(s,e.roughnessMap)).g.multiply(t);l=z(t,n,a)}else e instanceof C&&null!=e.outputRoughness&&(l=e.outputRoughness);let h=null;if((e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial)&&null!=e.lightMap){const t=e.lightMap,i=E("useLightMap",null!=e.lightMap?1:0),a=E("lightMapIntensity",e.lightMapIntensity??1),n=q("lightMap",t).sample(s).rgb.multiplyScalar(a);h=z(D(0),n,i)}let c=R(0);if(e instanceof i.MeshStandardMaterial){const t=E("metalness",e.metalness??0),i=e.metalnessMap??Xe,a=E("useMetalnessMap",null!=e.metalnessMap?1:0),n=q("metalnessMap",i).sample(_e(s,e.metalnessMap)).b.multiply(t);c=z(t,n,a)}else e instanceof C&&e.outputRoughness;let u=null,d=R(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){const t=e.aoMap??Je,i=E("useAoMap",null!=e.aoMap?1:0);d=E("aoMapIntensity",e.aoMapIntensity??1);const a=q("aoMap",t).sample(_e(s,e.aoMap)).r;u=z(R(1),a,i)}else e instanceof C&&e.outputRoughness;const f=E("opacity",e.opacity??1);let g=R(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){if(null!=e.alphaMap){const t=e.alphaMap;g=q("alphaMap",t).sample(_e(s,e.alphaMap)).r}g=g.multiply(f)}else e instanceof C&&null!=e.outputOpacity&&(g=e.outputOpacity);let M=B(0,1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){let t=A("color",(new i.Vector3).setFromColor(e.color));const a=e.map??Je,n=E("useAlbedoMap",null!=e.map?1:0),r=q("map",a).sample(_e(s,e.map)),o=r.multiply(B(t,1)),l=B(t,1);M=z(l,o,n),e.vertexColors&&(M=M.multiply(_(I($.color.rgb),1)));const h=z(R(1),r.w,n);g=g.multiply(h)}const v=!0===e.userData.hasBloom;let P=D(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=A("emissive",(new i.Vector3).setFromColor(e.emissive)),a=E("emissiveIntensity",e.emissiveIntensity),n=e.emissiveMap??Xe,r=E("useEmissiveMap",null!=e.emissiveMap?1:0),o=q("emissiveMap",n).sample(_e(s,e.emissiveMap)).rgb.multiply(t);P=z(t,o,r),P=P.multiplyScalar(a)}else e instanceof C&&null!=e.outputEmissive&&(P=e.outputEmissive);let y=null;if(e instanceof i.MeshPhysicalMaterial&&e.sheen>0&&(y=A("sheenColor",(new i.Vector3).setFromColor(e.sheenColor).multiplyScalar(e.sheen)),e.sheen>0&&null!=e.sheenColorMap)){const t=q("sheenColorMap",e.sheenColorMap).sample(s).rgb;y=y.multiply(t)}let b=null;if(e instanceof i.MeshPhysicalMaterial&&e.sheen>0&&(b=E("sheenRoughness",e.sheenRoughness),e.sheen>0&&null!=e.sheenRoughnessMap)){const t=q("sheenRoughnessMap",e.sheenRoughnessMap).sample(s).r;b=b.multiply(t)}let w=null;if(e instanceof i.MeshPhysicalMaterial&&e.anisotropy>0&&(w=E("anisotropy",e.anisotropy),e.anisotropy>0&&null!=e.anisotropyMap)){const t=q("anisotropyMap",e.anisotropyMap).sample(s).r;w=w.multiply(t)}let x=null;if(e instanceof i.MeshPhysicalMaterial&&e.anisotropy>0){const t=e.anisotropyRotation??0;x=J("anisotropyDirection",new i.Vector2(Math.cos(t),Math.sin(t)))}const T=this.usesShaderUniform(e,ie),j=this.usesShaderUniform(e,ue),k=this.usesShaderUniform(e,ce),X=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,Y=E("alphaTest",e.alphaTest);let K,Q=e.alphaTest>0?g.lt(Y):X&&t===$e.opaque?g.lt(.8):null;!0===e.userData.isDecal&&(Q=Q?Q.or(Ie):Ie),K=X?_(0,0,0,0):(r=o,G(r).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?l:1);const Z=e instanceof C?e.outputPosition:void 0,ee=e instanceof C?e.outputTransform:void 0;let te,se=B("black",1);if(e instanceof C&&null!=e.outputColor)se=e.outputColor;else if(e instanceof i.MeshStandardMaterial)se=U({color:M,metalness:c,roughness:l,emissive:P.rgb,normal:o,ambientOcclusion:u,ambientOcclusionIntensity:d,bakedLight:h,sheenColor:y,sheenRoughness:b,anisotropy:w,anisotropyDirection:x});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)se=F({color:M.rgb,ambientOcclusion:u,ambientOcclusionIntensity:d});else if(e instanceof i.MeshBasicMaterial){let e=M.rgb,t=h??D("black");null!=u&&(t=t.multiplyScalar(u.subtract(1).multiply(d).add(1))),e=e.add(t),se=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(se=O({color:M,emissive:P.rgb,normal:o,ambientOcclusion:u,ambientOcclusionIntensity:d,bakedLight:h}));(e instanceof C||e instanceof i.MeshStandardMaterial)&&(te=e.envMap);let ae=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(ae=e.fog);let ne=B(se.rgb,g);ae&&(ne=new FogNode(ne));let re=!0;if(t===$e.opaque?(re&&(re=!T&&!j&&!k),re&&(re=!X)):t===$e.transparent&&re&&(re=X||T||j||k),!re)return n=Ke,a.set(e,n),n;n=new C({transform:ee,position:null==ee?Z:void 0,outputs:[ne,P.rgba(t===$e.opaque?Y:v?1:0),K],opacity:g,outputEncoding:!1,fog:ae,transparent:e.transparent,lights:!0,envMap:te,alphaTest:e.alphaTest,uniformNodes:e.uniformNodes??{},discard:Q}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=n.uniforms.envMapIntensity&&(n.uniforms.envMapIntensity.value=e.envMapIntensity),"alphaMap"in e&&null!=e.alphaMap&&(n.alphaMap=e.alphaMap),(e instanceof C||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(n),e instanceof C&&(Object.assign(n.defines,e.defines),null!=n.uniforms[ce]&&(n.uniforms[ce].value=this.aoPass.pdRenderTarget.texture,n.defines.USE_SSAO_MAP="")),n.userData.mrtOutputs=3,n.forceSinglePass=e.forceSinglePass,n.side=e.side,n.blending=e.blending,X?(n.depthWrite=!e.transparent,n.depthTest=e.depthTest,n.colorWrite=t===$e.transparent):(n.depthWrite=e.depthWrite,n.depthTest=e.depthTest),n.visible=e.visible,n.alphaTest=e.alphaTest,n.alphaHash=e.alphaHash,n.vertexColors=e.vertexColors,n.premultipliedAlpha=e.premultipliedAlpha,n.toneMapped=e.toneMapped,n.blendAlpha=e.blendAlpha,n.blendColor=e.blendColor,n.polygonOffset=e.polygonOffset,n.polygonOffsetFactor=e.polygonOffsetFactor,n.polygonOffsetUnits=e.polygonOffsetUnits,n.blending=e.blending,n.wireframe=e.wireframe??!1,n.userData.isGBufferMaterial=!0,n.visible=re,Object.assign(n.userData,e.userData),n.visible&&(this.csm.setupMaterial(n),e instanceof p&&this.inheritCustomUniformBindings(e,n)),a.set(e,n)}var r;return n.visible&&(e instanceof p?this.updateUniformValues(e,n):this.updateMaterialProperties(e,n)),this.usesShaderUniform(n,ue)&&this.initSceneColorUniform(n),this.initLightVolumeUniform(n),n}isDepthPrepassEnabled(){return!0===this.options.depthPrepass?.enabled}usesSceneFeedbackUniforms(e){return e instanceof p&&(this.usesShaderUniform(e,ie)||this.usesShaderUniform(e,ue)||this.usesShaderUniform(e,ce))}usesShaderUniform(e,t){return e instanceof p&&null!=e.uniforms[t]}isDepthPrepassEligibleMaterial(e){return null!=e&&(!1!==e.visible&&!1!==e.depthTest&&!1!==e.depthWrite&&(!e.transparent&&e.blending!==i.AdditiveBlending&&(!this.usesSceneFeedbackUniforms(e)&&(e instanceof C||e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshBasicMaterial))))}isDepthPrepassEligibleMesh(e){return!!this.isDepthPrepassEnabled()&&((e instanceof i.InstancedMesh||e instanceof Le)&&(!Array.isArray(e.material)&&this.isDepthPrepassEligibleMaterial(e.material)))}createDepthPrepassMaterial(e){if(!this.isDepthPrepassEligibleMaterial(e))return null;let t=this.depthPrepassMaterialCache.get(e);if(null==t){let s,a=R(1);e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(a=E("opacity",e.opacity??1),null!=e.map&&(a=a.multiply(q("map",e.map).sample(V.uv).a)),null!=e.alphaMap&&(a=a.multiply(q("alphaMap",e.alphaMap).sample(V.uv).r))):e instanceof C&&(a=e.outputOpacity??R(1)),null!=e.alphaTest&&e.alphaTest>0&&(s=a.lt(e.alphaTest));const n=e instanceof C?e.outputPosition:void 0,r=e instanceof C?e.outputTransform:void 0;t=new C({outputs:[B(0,0),B(0,0),B(0,0)],opacity:a,transform:r,position:null==r?n:void 0,discard:s,lights:!1,fog:!1,outputEncoding:!1,transparent:!1,alphaTest:e.alphaTest}),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=i.NoBlending,t.lights=!1,t.fog=!1,t.toneMapped=!1,t.side=e.side,t.alphaTest=e.alphaTest,t.visible=e.visible,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.onBeforeCompile=()=>{},t.customProgramCacheKey=()=>`depth-prepass:${e.id}:${e.version}:${e.alphaTest}:${e.side}`;for(const e of Ut)delete t.uniforms[e];for(const e of Et)delete t.uniforms[e];delete t.uniforms.receiveShadow,this.depthPrepassMaterialCache.set(e,t)}return e instanceof C?this.updateUniformValues(e,t):this.updateMaterialProperties(e,t),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=i.NoBlending,t.visible=e.visible,t.alphaTest=e.alphaTest,t.side=e.side,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t}applyDepthPrepassMaterials(){const e=this.depthPrepassCachedMaterials,t=this.depthPrepassCachedVisibility;e.clear(),t.length=0,Me(this.scene,s=>{if(Tt(s))return t.push(s),s.visible=!1,!1;if(!(s instanceof o))return;if(e.set(s,s.material),!this.isDepthPrepassEligibleMesh(s))return t.push(s),void(s.visible=!1);const i=this.createDepthPrepassMaterial(s.material);if(null==i)return t.push(s),void(s.visible=!1);s.material=i,s.visible=!0})}unapplyDepthPrepassMaterials(){this.depthPrepassCachedMaterials.forEach((e,t)=>{t.material=e}),this.depthPrepassCachedVisibility.forEach(e=>{e.visible=!0})}renderDepthPrepass(){if(!this.isDepthPrepassEnabled())return;this.applyDepthPrepassMaterials();const e=this.scene.matrixWorldAutoUpdate,t=this.scene.matrixAutoUpdate,s=this.renderer.shadowMap.autoUpdate;this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clearDepth();try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Depth prepass render failed",e)}this.unapplyDepthPrepassMaterials(),this.renderer.shadowMap.autoUpdate=s,this.scene.matrixWorldAutoUpdate=e,this.scene.matrixAutoUpdate=t}updateCsm(){const e=this.csmUpdateInvervals;if(this.renderer.shadowMap.autoUpdate&&null!=this.csmCascadeLastUpdate&&Array.isArray(e)){const t=performance.now();for(let s=0;s<this.csm.lights.length;++s){const i=e[s]??e[e.length-1]??16;(t-this.csmCascadeLastUpdate[s]>=i||0===s)&&this.csm.lights[s].shadow&&(this.csm.lights[s].shadow.needsUpdate=!0,this.csmCascadeLastUpdate[s]=t)}}this.csm.update()}loop(t,s=!1){const a=this.stats,n=a.addPanel(new ee.Panel("Calls","#83f","#002")),l=a.addPanel(new ee.Panel("Triangles","#c32","#002"));let h;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(h=new me(this.renderer.getContext()),a.addPanel(h)),this.showStats=s;let p=10,c=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>p&&(p=e,setTimeout(()=>p=10,5e3)),n.update(e,p);const t=this.renderer.info.render.triangles;t>c&&(c=t,setTimeout(()=>c=1e3,5e3)),l.update(t,c)};performance.now();i.Ray.prototype.intersectTriangle;this.resizeRender();const d=[],m=[],f=[];let g=0;const M=new r,v=new r;let P=0;let y=this.paused,b=!1,w=0,x=null,T=this.fpsCapRevision;const S=()=>{this.running&&!0!==this.options.enableXR&&requestAnimationFrame(E)},R=()=>{e.activeView=this,b&&(b=!1,requestAnimationFrame(()=>E(w)))},U=st();tt.set(this.container,e=>{this.isIntersecting=e,e&&R()}),U.observe(this.container),this.container.addEventListener("pointerdown",()=>{R()},{capture:!0});const E=s=>{b=!1;const n=this.renderer.getContext();if(!this.running||null===this.container.offsetParent||this.paused&&n.drawingBufferHeight>1)return b=!0,w=s,setTimeout(()=>{b&&E(s)},500),void(this.paused&&(y=!0));if(this.renderer.domElement.parentElement!==this.container){if(e.activeView!==this&&null!==e.activeView)return b=!0,void(w=s);this.attachRendererDomElement(),this.resizeRender()}if(!0!==this.options.enableXR){T!==this.fpsCapRevision&&(T=this.fpsCapRevision,x=null);const e=this.fpsCap;if(null!=e){const t=1e3/e;if(null!=x){const e=s-x;if(e<t)return void S();x=s-e%t}else x=s}else x=s}let r=(s*=.001)-g;if(g=s,y?(r=.016,y=!1,this.resetUpscalingHistory()):r>.25&&this.resetUpscalingHistory(),this.updateDynamicResolution(r,1e3*s),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),a.begin(),this.showStats&&h?.startQuery(),this.ssrPass.gpuPanel=h,M.copy(this.camera.matrixWorld),r>1){let e=r;for(;e>.05;)t(at),e-=at;t(e)}else t(r);this.onLoopCallbacks.forEach(e=>e(r)),this.paused||(this.simulationTime+=r*this.simulationTimeScale);const l=this.simulationTime;this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),s-P>.08&&!v.equals(M)&&(this.renderer.shadowMap.needsUpdate=!0,P=s),this.updateCsm();let p=!1;d.length=0,m.length=0,f.length=0;const c=lt;pt.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),c.setFromProjectionMatrix(pt);let R=!1,U=!1,A=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Fe&&(R=!0),e instanceof o&&this.initCustomDepthMaterial(e),(e instanceof o||e instanceof i.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),this.initShadowUniform(e,e.material),this.initLightVolumeUniform(e.material),null!=this.scene.environment&&ot(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(p=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[ie])&&isObjectInFrustum(e,c)?(this.initDepthUniform(e.material),U=!0):e instanceof X&&(e.visible=!1,m.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[ce]&&isObjectInFrustum(e,c)&&e.material instanceof C&&this.initAoUniform(e.material),e instanceof o||e instanceof i.Sprite){let t=!1;ot(e,e=>{this.usesShaderUniform(e,ue)&&(this.initSceneColorUniform(e),t=!0)}),t&&(f.push(e),A=!0)}if(e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[pe])e.material.uniforms[pe].value=l;else if(e instanceof o&&Array.isArray(e.material))for(const t of e.material)t.uniforms&&null!=t.uniforms[pe]&&(t.uniforms[pe].value=l)}),this.bloomPass.enabled=p,this.prepareUpscalingFrame(),this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderDepthPrepass(),this.renderScene($e.opaque),this.aoPass.output=te.OUTPUT.Off,(U||A)&&(this.fquadCopyOpaque.material.uniforms.tSceneColor.value=this.gRenderTarget.textures[0],this.fquadCopyOpaque.material.uniforms.tDepthTexture.value=this.gRenderTarget.depthTexture,this.initResolutionUniform(this.fquadCopyOpaque.material),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.clear(),this.fquadCopyOpaque.render(this.renderer),this.renderer.setRenderTarget(this.gRenderTarget)),f.length,d.forEach(e=>e.visible=!0),m.forEach(e=>e.visible=!0),f.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=s),this.volumetricFogPass&&R?(this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene),this.volumetricFogPass.enabled=!0):this.volumetricFogPass&&(this.volumetricFogPass.enabled=!1),this.updatePostProcessEffectUniforms(l);try{!this.paused&&this.running&&(this.render(r),this.finishUpscalingFrame(),this.showStats&&h?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}finally{this.finishUpscalingFrame()}a.end(),this.csm?.update(),S()};!0===this.options.enableXR?this.renderer.setAnimationLoop(E):requestAnimationFrame(E)}applyGBufferMaterials(e){const t=this.gBufferCachedMaterials,s=this.gBufferCachedVisibility;t.clear(),s.length=0;Me(this.scene,i=>{if(Tt(i))return s.push(i),i.visible=!1,!1;if(i instanceof o){t.set(i,i.material);let a=!1;if(Array.isArray(i.material)){i.material=i.material.slice();for(let t=0;t<i.material.length;t++)i.material[t]=this.createGBufferMaterial(i.material[t],e,e===$e.opaque&&this.isDepthPrepassEligibleMesh(i)),a||(a=i.material[t].visible),this.initShadowUniform(i,i.material[t])}else i.material=this.createGBufferMaterial(i.material,e,e===$e.opaque&&this.isDepthPrepassEligibleMesh(i)),a||(a=i.material.visible),this.initShadowUniform(i,i.material);a?i.visible=!0:null!=i.children&&0!=i.children.length||(s.push(i),i.visible=!1)}})}unapplyGBufferMaterials(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e}),this.gBufferCachedVisibility.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)})}initTextures(e=this.scene){e.traverse(e=>{if(e instanceof o)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++)this._initMaterialTextures(e.material[t]);else this._initMaterialTextures(e.material)})}_initMaterialTextures(e){if(!this._initiatedMaterialTextures.has(e))if(this._initiatedMaterialTextures.add(e),e instanceof p){for(const[t,s]of Object.entries(e.uniforms))if(s.value instanceof u){if(this._initiatedTextures.has(s.value))continue;this.renderer.initTexture(s.value),this._initiatedTextures.add(s.value)}}else for(const[t,s]of Object.entries(e))if(s instanceof u){if(this._initiatedTextures.has(s))continue;this.renderer.initTexture(s),this._initiatedTextures.add(s)}}async compileAsync(e=this.scene){if(this.compileInProgress)return;this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0,this.applyGBufferMaterials($e.opaque),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials($e.transparent),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.isDepthPrepassEnabled()&&(this.renderer.setRenderTarget(this.gRenderTarget),this.applyDepthPrepassMaterials(),await this.renderer.compileAsync(e,this.camera),this.unapplyDepthPrepassMaterials()),e===this.scene&&(this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.compileAsync(this.fquadBlendAO.mesh,this.fquadBlendAO.camera),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.compileAsync(this.fquadCopyOpaque.mesh,this.fquadCopyOpaque.camera));const t=this.csm.lights[0]?.shadow.camera;null!=t&&(this.applyDepthMaterial(),await this.renderer.compileAsync(e,t),this.unapplyDepthMaterial()),this.compileInProgress=!1,this.renderer.setRenderTarget(null)}applyDepthMaterial(){const e=this.gBufferCachedMaterials;e.clear(),this.scene.traverse(t=>{(t.isMesh||t.isPoints||t.isLine||t.isSprite)&&(this.initCustomDepthMaterial(t),e.set(t,t.material),t.castShadow?null!=t.customDepthMaterial?t.material=t.customDepthMaterial:t.material=Ot:t.material=null)})}unapplyDepthMaterial(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e})}renderScene(e){if(!this.running||this.paused)return;if(this.compileInProgress)return void console.error("Compile in progress, skipping render");this.applyGBufferMaterials(e);const t=this.scene.matrixWorldAutoUpdate,s=this.scene.matrixAutoUpdate,i=this.renderer.shadowMap.autoUpdate;e!==$e.opaque&&(this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1);try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Render failed",e)}e===$e.opaque&&this.gBufferCachedMaterials.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof p&&this.updateLightUniformValues(t.material,e)}),this.unapplyGBufferMaterials(),this.renderer.shadowMap.autoUpdate=i,this.scene.matrixWorldAutoUpdate=t,this.scene.matrixAutoUpdate=s}getEnvTexture(e){null==this.pmremGenerator&&(this.pmremGenerator=new i.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader());let t=this.pmremGeneratorResults.get(e);return null==t&&(t=this.pmremGenerator.fromEquirectangular(e).texture,this.pmremGeneratorResults.set(e,t)),t.colorSpace=i.SRGBColorSpace,t}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure);!function(e,t=i.NoToneMapping,s=1){e.tonemapMapping=t,e.tonemapExposure=s,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=e.colorTint??new i.Color("white"),e.colorTint.set("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.globalSaturation=ct(e.globalSaturation,1,1,1),e.globalContrast=ct(e.globalContrast,1,1,1),e.globalGamma=ct(e.globalGamma,1,1,1),e.globalGain=ct(e.globalGain,1,1,1),e.globalOffset=ct(e.globalOffset,0,0,0),e.shadowsSaturation=ct(e.shadowsSaturation,1,1,1),e.shadowsContrast=ct(e.shadowsContrast,1,1,1),e.shadowsGamma=ct(e.shadowsGamma,1,1,1),e.shadowsGain=ct(e.shadowsGain,1,1,1),e.shadowsOffset=ct(e.shadowsOffset,0,0,0),e.shadowsMax=.09,e.midtonesSaturation=ct(e.midtonesSaturation,1,1,1),e.midtonesContrast=ct(e.midtonesContrast,1,1,1),e.midtonesGamma=ct(e.midtonesGamma,1,1,1),e.midtonesGain=ct(e.midtonesGain,1,1,1),e.midtonesOffset=ct(e.midtonesOffset,0,0,0),e.highlightsSaturation=ct(e.highlightsSaturation,1,1,1),e.highlightsContrast=ct(e.highlightsContrast,1,1,1),e.highlightsGamma=ct(e.highlightsGamma,1,1,1),e.highlightsGain=ct(e.highlightsGain,1,1,1),e.highlightsOffset=ct(e.highlightsOffset,0,0,0),e.highlightsMin=.5,e.lut=void 0,e.lutIntensity=0}(this.postProcessSettings,this.baseToneMapping,this.baseToneMappingExposure);const e=this.postProcessSettings;let t,s=!1;if(null==this.camera)return;const a=this.camera.getWorldPosition(gt);let n=[];for(const r of this.postProcessVolumes){if(!nt(r.object))continue;let o=r.blendWeight??1;const l=r.distanceToPoint(a);l>r.blendRadius||(r.blendRadius>0&&(o*=ve(1-l/r.blendRadius,0,1)),o>1&&(o=1),o>0&&(n.push(r),void 0!==r.settings.tonemapMapping&&(e.tonemapMapping=r.settings.tonemapMapping),void 0!==r.settings.tonemapExposure&&(e.tonemapExposure=i.MathUtils.lerp(e.tonemapExposure,r.settings.tonemapExposure,o)),void 0!==r.settings.envTexture&&(e.envTexture=r.settings.envTexture),void 0!==r.settings.envIntensity&&(e.envIntensity=i.MathUtils.lerp(e.envIntensity,r.settings.envIntensity,o)),void 0!==r.settings.vignetteIntensity&&(e.vignetteIntensity=i.MathUtils.lerp(e.vignetteIntensity,r.settings.vignetteIntensity,o)),void 0!==r.settings.colorTint&&void 0!==r.settings.colorTintIntensity&&r.settings.colorTintIntensity>0&&(e.colorTint=e.colorTint.lerp(r.settings.colorTint,o)),void 0!==r.settings.colorTintIntensity&&(e.colorTintIntensity=i.MathUtils.lerp(e.colorTintIntensity,r.settings.colorTintIntensity,o)),void 0!==r.settings.depthFocus&&(s=!0,e.depthFocus=void 0!==e.depthFocus?i.MathUtils.lerp(e.depthFocus,r.settings.depthFocus,o):r.settings.depthFocus),void 0!==r.settings.depthAperture&&(s=!0,e.depthAperture=void 0!==e.depthAperture?i.MathUtils.lerp(e.depthAperture,r.settings.depthAperture,o):r.settings.depthAperture),void 0!==r.settings.depthMaxBlur&&(s=!0,e.depthMaxBlur=void 0!==e.depthMaxBlur?i.MathUtils.lerp(e.depthMaxBlur,r.settings.depthMaxBlur,o):r.settings.depthMaxBlur),void 0!==r.settings.temperature&&(e.temperature=i.MathUtils.lerp(e.temperature,r.settings.temperature,o)),void 0!==r.settings.temperatureTint&&(e.temperatureTint=i.MathUtils.lerp(e.temperatureTint,r.settings.temperatureTint,o)),void 0!==r.settings.globalSaturation&&e.globalSaturation.lerp(r.settings.globalSaturation,o),void 0!==r.settings.globalContrast&&e.globalContrast.lerp(r.settings.globalContrast,o),void 0!==r.settings.globalGamma&&e.globalGamma.lerp(r.settings.globalGamma,o),void 0!==r.settings.globalGain&&e.globalGain.lerp(r.settings.globalGain,o),void 0!==r.settings.globalOffset&&e.globalOffset.lerp(r.settings.globalOffset,o),void 0!==r.settings.shadowsSaturation&&e.shadowsSaturation.lerp(r.settings.shadowsSaturation,o),void 0!==r.settings.shadowsContrast&&e.shadowsContrast.lerp(r.settings.shadowsContrast,o),void 0!==r.settings.shadowsGamma&&e.shadowsGamma.lerp(r.settings.shadowsGamma,o),void 0!==r.settings.shadowsGain&&e.shadowsGain.lerp(r.settings.shadowsGain,o),void 0!==r.settings.shadowsOffset&&e.shadowsOffset.lerp(r.settings.shadowsOffset,o),void 0!==r.settings.shadowsMax&&(e.shadowsMax=i.MathUtils.lerp(e.shadowsMax,r.settings.shadowsMax,o)),void 0!==r.settings.midtonesSaturation&&e.midtonesSaturation.lerp(r.settings.midtonesSaturation,o),void 0!==r.settings.midtonesContrast&&e.midtonesContrast.lerp(r.settings.midtonesContrast,o),void 0!==r.settings.midtonesGamma&&e.midtonesGamma.lerp(r.settings.midtonesGamma,o),void 0!==r.settings.midtonesGain&&e.midtonesGain.lerp(r.settings.midtonesGain,o),void 0!==r.settings.midtonesOffset&&e.midtonesOffset.lerp(r.settings.midtonesOffset,o),void 0!==r.settings.highlightsSaturation&&e.highlightsSaturation.lerp(r.settings.highlightsSaturation,o),void 0!==r.settings.highlightsContrast&&e.highlightsContrast.lerp(r.settings.highlightsContrast,o),void 0!==r.settings.highlightsGamma&&e.highlightsGamma.lerp(r.settings.highlightsGamma,o),void 0!==r.settings.highlightsGain&&e.highlightsGain.lerp(r.settings.highlightsGain,o),void 0!==r.settings.highlightsOffset&&e.highlightsOffset.lerp(r.settings.highlightsOffset,o),void 0!==r.settings.highlightsMin&&(e.highlightsMin=i.MathUtils.lerp(e.highlightsMin,r.settings.highlightsMin,o)),void 0!==r.settings.lut&&(t=r.settings.lut),void 0!==r.settings.lutIntensity&&(e.lutIntensity=i.MathUtils.lerp(e.lutIntensity,r.settings.lutIntensity,o))))}if(0===n.length)return this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure);const r=e.vignetteIntensity>ft,o=(h=e.temperature,p=e.temperatureTint,!dt(h,6500)||!dt(p,0));var h,p;const c=(u=e.colorTint,e.colorTintIntensity>ft&&(!dt(u.r,1)||!dt(u.g,1)||!dt(u.b,1)));var u;const d=!(ut((m=e).globalSaturation,1,1,1)&&ut(m.globalContrast,1,1,1)&&ut(m.globalGamma,1,1,1)&&ut(m.globalGain,1,1,1)&&ut(m.globalOffset,0,0,0)&&ut(m.shadowsSaturation,1,1,1)&&ut(m.shadowsContrast,1,1,1)&&ut(m.shadowsGamma,1,1,1)&&ut(m.shadowsGain,1,1,1)&&ut(m.shadowsOffset,0,0,0)&&ut(m.midtonesSaturation,1,1,1)&&ut(m.midtonesContrast,1,1,1)&&ut(m.midtonesGamma,1,1,1)&&ut(m.midtonesGain,1,1,1)&&ut(m.midtonesOffset,0,0,0)&&ut(m.highlightsSaturation,1,1,1)&&ut(m.highlightsContrast,1,1,1)&&ut(m.highlightsGamma,1,1,1)&&ut(m.highlightsGain,1,1,1)&&ut(m.highlightsOffset,0,0,0));var m;const f=o||c||d||r,g=f&&e.tonemapMapping!==i.NoToneMapping,M=null!=t&&e.lutIntensity>ft;f?(this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1):(this.renderer.toneMapping=e.tonemapMapping,this.renderer.toneMappingExposure=e.tonemapExposure),null!=e.envTexture&&(this.scene.environment=this.getEnvTexture(e.envTexture)),this.scene.environmentIntensity=e.envIntensity,f?(this.colorPass.whiteBalanceEnabled=o,this.colorPass.whiteBalanceScale=o?function(e,t,s){const i=function(e){const t=ve(e,1e3,4e4)/100,s=t<=66?1:ve(1.292936186062745*Math.pow(t-60,-.1332047592),0,1),i=ve(t<=66?.3900815787690196*Math.log(t)-.6318414437886275:1.129890860895294*Math.pow(t-60,-.0755148492),0,1),a=t>=66?1:t<=19?0:ve(.5432067891101962*Math.log(t-10)-1.19625408914,0,1);return vt.set(s,i,a)}(t),a=1+.2*ve(s,-1,1),n=i.x,r=i.y*a,o=i.z,l=Math.max(r,1e-4);return e.set(1/Math.max(n/l,1e-4),1/Math.max(r/l,1e-4),1/Math.max(o/l,1e-4)),e}(Mt,e.temperature,e.temperatureTint):Mt.set(1,1,1),this.colorPass.vignetteIntensity=e.vignetteIntensity,this.colorPass.vignetteEnabled=r,this.colorPass.colorTintEnabled=c,this.colorPass.colorTint=e.colorTint,this.colorPass.colorTintIntensity=e.colorTintIntensity,this.colorPass.colorGradingEnabled=d,this.colorPass.toneMapping=e.tonemapMapping,this.colorPass.toneMappingEnabled=g,this.colorPass.toneMappingExposure=e.tonemapExposure,this.colorPass.globalSaturation=e.globalSaturation,this.colorPass.globalContrast=e.globalContrast,this.colorPass.globalGamma=e.globalGamma,this.colorPass.globalGain=e.globalGain,this.colorPass.globalOffset=e.globalOffset,this.colorPass.shadowsSaturation=e.shadowsSaturation,this.colorPass.shadowsContrast=e.shadowsContrast,this.colorPass.shadowsGamma=e.shadowsGamma,this.colorPass.shadowsGain=e.shadowsGain,this.colorPass.shadowsOffset=e.shadowsOffset,this.colorPass.shadowsMax=e.shadowsMax,this.colorPass.midtonesSaturation=e.midtonesSaturation,this.colorPass.midtonesContrast=e.midtonesContrast,this.colorPass.midtonesGamma=e.midtonesGamma,this.colorPass.midtonesGain=e.midtonesGain,this.colorPass.midtonesOffset=e.midtonesOffset,this.colorPass.highlightsSaturation=e.highlightsSaturation,this.colorPass.highlightsContrast=e.highlightsContrast,this.colorPass.highlightsGamma=e.highlightsGamma,this.colorPass.highlightsGain=e.highlightsGain,this.colorPass.highlightsOffset=e.highlightsOffset,this.colorPass.highlightsMin=e.highlightsMin,this.colorPass.enabled=!0):this.colorPass.enabled=!1,s&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==e.depthFocus&&(this.dofPass.uniforms.focus.value=e.depthFocus),void 0!==e.depthAperture&&(this.dofPass.uniforms.aperture.value=e.depthAperture),void 0!==e.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=e.depthMaxBlur)):this.dofPass.enabled=!1,this.lutPass.enabled=M,M&&(null!=t&&(t.flipY=!0,t.generateMipmaps=!1),this.lutPass.lut=t,this.lutPass.intensity=e.lutIntensity)}updatePostProcessEffectUniforms(e){if(0===this.postProcessEffects.length)return;const t=this.postProcessEffectUniformState;t.aoEnabled=this.aoPass.enabled,t.aoTexture=this.aoPass.enabled?this.aoPass.pdRenderTarget.texture:null,this.camera instanceof l?(t.cameraNear=this.camera.near,t.cameraFar=this.camera.far):(t.cameraNear=void 0,t.cameraFar=void 0),t.depthTexture=this.sceneColorRenderTarget.textures[1],t.normalTexture=this.gRenderTarget.textures[2],t.resolution.set(this.gRenderTarget.width,this.gRenderTarget.height),t.simulationTime=e;for(const e of this.postProcessEffects)e.pass.updateUniformState(t)}renderOverlay(){if(!this.running)return;if(0===this.overlayCameras.size)return;const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.previousClientWith/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}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;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof o&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,lt)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.options.bloom,this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=ge(this.scene,e=>e instanceof o&&!0===e.material?.userData?.hasBloom)}darkenNonBloomed(e){if((e instanceof o||e instanceof i.Sprite||e instanceof i.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)){if(e.material?.id===ke.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=ke:(e.visible=!1,this.bloomHidden.push(e))}else"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)}initSceneColorUniform(e){if(e instanceof p)return null==e.uniforms[ue]?(e.uniforms[ue]={value:this.sceneColorRenderTarget.texture},void(e.uniformsNeedUpdate=!0)):void(e.uniforms[ue].value!==this.sceneColorRenderTarget.texture&&(e.uniforms[ue].value=this.sceneColorRenderTarget.texture,e.uniformsNeedUpdate=!0))}initDepthUniform(e){e instanceof p&&(e.uniforms[ie].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[ne]&&(e.uniforms[ne].value=this.camera.near),null!=e.uniforms[ae]&&(e.uniforms[ae].value=this.camera.far)))}initNormalUniform(e){e instanceof p&&null!=e.uniforms[oe]&&(e.uniforms[oe].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof C&&(t.uniforms.receiveShadow?t.uniforms.receiveShadow.value=e.receiveShadow:t.uniforms.receiveShadow={value:e.receiveShadow})}initLightVolumeUniform(e){e instanceof C&&(null!=this.lightVolume?null==e.uniforms.uSH?(e.defines.USE_LIGHT_PROBE_VOLUME="",e.uniforms.gridOrigin={value:this.lightVolume.gridOrigin},e.uniforms.gridSize={value:this.lightVolume.gridSize},e.uniforms.gridRes={value:this.lightVolume.gridResolution},e.uniforms.giIntensity={value:this.lightProbeIntensity},e.uniforms.uSH={value:this.lightVolume.shTexture},e.uniformsNeedUpdate=!0,e.needsUpdate=!0):e.uniforms.giIntensity.value=this.lightProbeIntensity:null!=e.uniforms.uSH&&(delete e.defines.USE_LIGHT_PROBE_VOLUME,delete e.uniforms.gridOrigin,delete e.uniforms.gridSize,delete e.uniforms.gridRes,delete e.uniforms.giIntensity,delete e.uniforms.uSH,e.uniformsNeedUpdate=!0,e.needsUpdate=!0))}initResolutionUniform(e){e instanceof p&&null!=e.uniforms[re]&&e.uniforms[re].value.set(this.gRenderTarget.width,this.gRenderTarget.height)}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[ce].value=this.aoPass.pdRenderTarget.texture,null==e.defines.USE_SSAO_MAP&&(e.defines.USE_SSAO_MAP="",e.needsUpdate=!0),e.defines.USE_SSAO_MAP="";const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}else if(null!=e.defines.USE_SSAO_MAP){delete e.defines.USE_SSAO_MAP,e.needsUpdate=!0;const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}}initCustomDepthMaterial(e){if(null!=e.customDepthMaterial||!e.castShadow)return;const t=e.material;if(!(t instanceof C&&t.depthWrite&&t.alphaTest>0))return;let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Oe(Ae);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new C({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}};it.activeView=null,it=e=t([se(),s("design:paramtypes",[HTMLElement,Object])],it);export{it as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const at=.05;function nt(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}function rt(e,t){return e.priority!==t.priority?e.priority-t.priority:e.id-t.id}function ot(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}te.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.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};const lt=new i.Frustum,ht=new i.Box3,pt=new i.Matrix4;export function isObjectInFrustum(e,t){const s=ht.setFromObject(e);return t.intersectsBox(s)}function ct(e,t,s,a){return null==e?new i.Vector3(t,s,a):e.set(t,s,a)}function ut(e,t,s,i){return null!=e&&dt(e.x,t)&&dt(e.y,s)&&dt(e.z,i)}function dt(e,t,s=ft){return Math.abs(e-t)<=s}function mt(e,t){return null!=e&&Number.isFinite(e)&&e>0?e:t}const ft=1e-4,gt=new i.Vector3,Mt=new i.Vector3(1,1,1),vt=new i.Vector3(1,1,1);const Pt=new r,yt=new d;function bt(e,t,s=new i.Matrix3){return yt.copy(e),yt.x*=-1,yt.y*=-1,yt.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(yt.y*=-1,yt.z*=-1),s.setFromMatrix4(Pt.makeRotationFromEuler(yt))}const wt=new C({outputs:[_(0,0,0,0),_(0,0,0,0),B(D("white"),je(4))],transparent:!0}),xt=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});wt.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),xt);function Tt(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isLineSegments2||e.isTransformControls||e.isTransformControlsGizmo||e instanceof o&&St(e,e.material)}function St(e,t){return null==t||(Array.isArray(t)?t.some(t=>St(e,t)):t instanceof i.RawShaderMaterial||t instanceof i.ShaderMaterial&&!(t instanceof C))}class Rt extends Ve{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.cachedVisibility=[],this.toRender=[],this.needsSwap=!1}render(e,t,s,i,a){const n=e.autoClear;e.autoClear=!1;const r=this.scene.matrixWorldAutoUpdate,l=this.scene.matrixAutoUpdate,h=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const p=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),this.cachedVisibility.length=0;let c=0,u=this.toRender;if(u.length=0,this.scene.traverseVisible(e=>{const t=Tt(e);e instanceof o&&!t?(this.cachedVisibility.push(e),e.visible=!1):t&&(c++,u.push(e))}),c>0)for(const t of u)e.render(t,this.camera);this.cachedVisibility.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=n,s.depthTexture=p,this.scene.matrixWorldAutoUpdate=r,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class Ct extends Ve{constructor(e){super(),this.fn=e}render(e,t,s,i,a){this.fn(e,t,s,i,a)}}const Ut=["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"],Et=["directionalShadowMap","directionalShadowMatrix","pointLightShadows","pointShadowMap","pointShadowMatrix","spotLightShadows","spotShadowMap"],At=A("fogColor");export class FogNode extends k{constructor(e,t=At){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),a=e.get(this.fogColor),n=e.get(E("fogFar")),r=e.get(E("fogNear")),o=e.get(E("fogDensity")),l=e.get(I(j.mvPosition.z));return{pars:"\n ",chunk:`\n #ifdef FOG_EXP2\n float fogFactor_${t} = 1.0 - exp( - ${o} * ${o} * ${l} * ${l} );\n #else\n float fogFactor_${t} = smoothstep( ${r}, ${n}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${a}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}const Ot=new i.MeshDepthMaterial({depthPacking:i.RGBADepthPacking});/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,3 +1,4 @@
1
+ import type { BaseSurfaceDefinition } from '../data/surface-definition';
1
2
  import * as THREE from 'three';
2
3
  type Item = {
3
4
  start: number;
@@ -7,6 +8,7 @@ type Item = {
7
8
  export declare class BatchedMesh2 extends THREE.BatchedMesh {
8
9
  private uniformTextures;
9
10
  private uniformSize;
11
+ surfaceByInstance: BaseSurfaceDefinition[];
10
12
  customSort: (list: Item[], camera: THREE.Camera) => void;
11
13
  initUniform(name: string, elementSize: number, defaultValue?: number): void;
12
14
  setUniformAt(name: string, instanceId: number, value: number | THREE.Vector4 | THREE.Vector3 | THREE.Vector2 | THREE.Color): this;
@@ -1,4 +1,4 @@
1
- import*as t from"three";function e(t,e){return t.z-e.z}function r(t,e){return e.z-t.z}export class BatchedMesh2 extends t.BatchedMesh{constructor(){super(...arguments),this.uniformTextures={},this.uniformSize={},this.customSort=(t,i)=>{this.material.transparent?t.sort(r):t.sort(e)}}initUniform(e,r,i=0){if(r<1||r>4||3===r)throw"Element size must be between 1,2, or 4";let s=Math.sqrt(this.maxInstanceCount);s=Math.ceil(s);let o=t.RedFormat;2===r?o=t.RGFormat:4===r&&(o=t.RGBAFormat);const n=new Float32Array(s*s*r).fill(i),a=new t.DataTexture(n,s,s,o,t.FloatType);this.uniformTextures[e]=a,this.uniformSize[e]=r;const u=this.material;if(!(u instanceof t.ShaderMaterial))throw"Can not use custom uniforms with other materials than ShaderMaterial";for(const[t,e]of Object.entries(this.uniformTextures))u.uniforms[t]={value:e};u.uniformsNeedUpdate=!0}setUniformAt(e,r,i){const s=this.uniformTextures[e],o=s.image.data,n=this._drawInfo;if(r>=n.length||!1===n[r].active)return this;"number"==typeof i?o[r*this.uniformSize[e]]=i:i.toArray(o,r*this.uniformSize[e]),s.needsUpdate=!0;const a=this.material;a instanceof t.ShaderMaterial&&(a.uniformsNeedUpdate=!0)}getUniformAt(e,r,i){const s=this.uniformTextures[e].image.data,o=this._drawInfo;return r>=o.length||!1===o[r].active?null:1===this.uniformSize[e]?s[r]:void((i instanceof t.Vector2||i instanceof t.Vector2||i instanceof t.Vector3||i instanceof t.Vector4||i instanceof t.Color)&&i.fromArray(s,r*this.uniformSize[e]))}dispose(){super.dispose();for(const t of Object.values(this.uniformTextures))t.dispose();return this.uniformTextures=null,this}}/*
1
+ import*as t from"three";function e(t,e){return t.z-e.z}function r(t,e){return e.z-t.z}export class BatchedMesh2 extends t.BatchedMesh{constructor(){super(...arguments),this.uniformTextures={},this.uniformSize={},this.surfaceByInstance=[],this.customSort=(t,i)=>{this.material.transparent?t.sort(r):t.sort(e)}}initUniform(e,r,i=0){if(r<1||r>4||3===r)throw"Element size must be between 1,2, or 4";let s=Math.sqrt(this.maxInstanceCount);s=Math.ceil(s);let n=t.RedFormat;2===r?n=t.RGFormat:4===r&&(n=t.RGBAFormat);const o=new Float32Array(s*s*r).fill(i),a=new t.DataTexture(o,s,s,n,t.FloatType);this.uniformTextures[e]=a,this.uniformSize[e]=r;const u=this.material;if(!(u instanceof t.ShaderMaterial))throw"Can not use custom uniforms with other materials than ShaderMaterial";for(const[t,e]of Object.entries(this.uniformTextures))u.uniforms[t]={value:e};u.uniformsNeedUpdate=!0}setUniformAt(e,r,i){const s=this.uniformTextures[e],n=s.image.data,o=this._drawInfo;if(r>=o.length||!1===o[r].active)return this;"number"==typeof i?n[r*this.uniformSize[e]]=i:i.toArray(n,r*this.uniformSize[e]),s.needsUpdate=!0;const a=this.material;a instanceof t.ShaderMaterial&&(a.uniformsNeedUpdate=!0)}getUniformAt(e,r,i){const s=this.uniformTextures[e].image.data,n=this._drawInfo;return r>=n.length||!1===n[r].active?null:1===this.uniformSize[e]?s[r]:void((i instanceof t.Vector2||i instanceof t.Vector2||i instanceof t.Vector3||i instanceof t.Vector4||i instanceof t.Color)&&i.fromArray(s,r*this.uniformSize[e]))}dispose(){super.dispose();for(const t of Object.values(this.uniformTextures))t.dispose();return this.uniformTextures=null,this}}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */