@hology/core 0.0.176 → 0.0.178
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gameplay/actors/builtin/navmesh-actor.d.ts +1 -0
- package/dist/gameplay/actors/builtin/navmesh-actor.js +1 -1
- package/dist/gameplay/actors/camera/third-person-camera-component.d.ts +1 -1
- package/dist/gameplay/actors/camera/third-person-camera-component.js +1 -1
- package/dist/gameplay/initiate.js +1 -1
- package/dist/gameplay/services/physics/physics-system.d.ts +6 -1
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/rendering/outline-effect.js +1 -1
- package/dist/rendering.d.ts +9 -0
- package/dist/rendering.js +1 -1
- package/dist/shader-nodes/effects.js +1 -1
- package/package.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{Ball as n,Capsule as o,Cone as s,ConvexPolyhedron as i,Cuboid as r,Cylinder as a,Heightfield as l,ShapeType as c,TriMesh as h}from"@dimforge/rapier3d-compat";import{init as p}from"@recast-navigation/core";import{DebugDrawer as u,getPositionsAndIndices as d}from"@recast-navigation/three";import{BehaviorSubject as m,Subject as f,debounceTime as w,filter as g,firstValueFrom as b,takeUntil as y}from"rxjs";import*as x from"three";import{BufferGeometryUtils as v,ConvexHull as M}from"three/examples/jsm/Addons.js";import{Actor as B,BaseActor as S,Parameter as z,PhysicsSystem as A,ViewController as
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{Ball as n,Capsule as o,Cone as s,ConvexPolyhedron as i,Cuboid as r,Cylinder as a,Heightfield as l,ShapeType as c,TriMesh as h}from"@dimforge/rapier3d-compat";import{init as p}from"@recast-navigation/core";import{DebugDrawer as u,getPositionsAndIndices as d}from"@recast-navigation/three";import{BehaviorSubject as m,Subject as f,debounceTime as w,filter as g,firstValueFrom as b,takeUntil as y}from"rxjs";import*as x from"three";import{BufferGeometryUtils as v,ConvexHull as M}from"three/examples/jsm/Addons.js";import{Actor as B,BaseActor as S,Parameter as z,PhysicsSystem as A,ViewController as k,World as C,attach as j,inject as F}from"../../";import{sleepDelay as I}from"../../../utils/async";import{hasSharedArrayBufferSupport as P,toSharedFloat32Array as V,toSharedUint32Array as G}from"../../../utils/buffer";import{DynamicTiledNavMesh as N}from"../../ai/dynamic-tiled-navmesh";import{TriggerVolumeMesh as H}from"./components/volume-editor-component";var D;!function(e){e[e.none=0]="none",e[e.starting=1]="starting",e[e.started=2]="started"}(D||(D={}));let E=D.none,T=new m(!1);export async function safeRecastInit(){return E===D.none?(E=D.starting,p().then(()=>{T.next(!0),E=D.started})):b(T.pipe(g(e=>e)))}new x.Box3(new x.Vector3(-100,-100,-100),new x.Vector3(100,100,100));const R=navigator.hardwareConcurrency??1;let U=!1,q=class extends S{constructor(){super(...arguments),this.physics=F(A),this.view=F(k),this.world=F(C),this.editorVisualisation=j(H),this.debug=!0,this.refreshMs=4e3,this.tileSize=50,this.walkableClimb=.3,this.walkableSlopeAngle=45,this.walkableHeight=2,this.cellSize=.2,this.bounds=new x.Box3}async onInit(){U||(await safeRecastInit(),U=!0),setTimeout(()=>{this.init()},10),this.recreateInterval=setInterval(()=>{if("_hology_transform_group"===this.object.parent?.name)return;X.setFromCenterAndSize(this.position,this.object.scale).equals(this.bounds)||(this.disposed.next(!0),this.disposed=new f,this.init())},2e3)}onEndPlay(){clearInterval(this.recreateInterval)}init(){this.bounds.setFromCenterAndSize(this.position,this.object.scale),console.log(this.bounds);const e=this.bounds.max.x-this.bounds.min.x,t=this.bounds.max.z-this.bounds.min.z,n=Math.max(1,Math.min(e,t)),o=Math.min(400,Math.max(50,Math.ceil(n/2))),s=Math.max(this.cellSize,.01),i={tileSize:Math.max(32,Math.floor(o/s)),walkableClimb:this.walkableClimb/s,walkableSlopeAngle:this.walkableSlopeAngle,walkableRadius:2,walkableHeight:this.walkableHeight/s,detailSampleDist:1,minRegionArea:6,mergeRegionArea:400,cs:s,ch:s,maxSimplificationError:1.3,maxEdgeLen:200},r=new N({navMeshBounds:this.bounds,recastConfig:i,maxTiles:1024,workers:R,cacheId:"nav"+this.object.userData?.src?.id});this.navMesh=r.navMesh;const a=this.tileSize*i.cs*2,l=performance.now(),c=new Map,h=new u;h.userData.isDebugDrawer=!0;r.navMesh;const p=this.bounds,m=()=>{const e=this.view.getCamera().getWorldPosition(new x.Vector3),t=new x.Box3((new x.Vector3).copy(e).subScalar(a),(new x.Vector3).copy(e).addScalar(a)),n=[],o=this.physics.world.bodies;if(null==o)return[];const s=new x.Box3;for(const e of o.getAll())for(let o=0,i=e.numColliders();o<i;o++){const i=e.collider(o);if(i.isSensor()||null!=i.parent().userData&&!0===i.parent().userData.ignoreForNavMesh)continue;const r=e.handle+","+o,a=c.get(r)?.mesh,l=a??O(i);if(W(i,l),null!=l){s.copy(l.geometry.boundingBox),s.min.add(l.position),s.max.add(l.position);const e=s.intersectsBox(t)||!0,o=s.intersectsBox(this.bounds);c.set(r,{pos:i.translation(),mesh:l}),e&&o&&n.push(l)}}return n},f=new x.Box3,g=new Map,b=new Map;let v=!0,M=performance.now(),B=!1;const S=function(e,t){let n=!1;return(async()=>{for(;!n;)await e(),await I(t)})(),()=>{n=!0}}(async()=>{if(B)return;const e=new x.Box3,t=m();for(const n of t){const t=g.get(n);!0!==t?.equals(n.position)&&(null!=t&&e.expandByPoint(t),e.expandByObject(n),g.set(n,n.position.clone()))}e.min.subScalar(50),e.max.addScalar(50);const n=r.getTilesForBounds(e);n.length>500&&console.warn("Too many tiles to update. Consider increasing tile size");const o=n.slice(0,500);if(0!=o.length){const n=[];for(const o of t)f.setFromObject(o),f.intersectsBox(e)&&n.push(o);console.log("intersecting meshes",n.length);let[s,i]=d(n);i=function(e,t,n){const o=new x.Vector3,s=[];for(let i=0;i<t.length;i+=3){let r=!0;for(let s=0;s<3;s++){const a=3*t[i+s];if(o.fromArray(e,a),!n.containsPoint(o)){r=!1;break}}r&&s.push(t[i],t[i+1],t[i+2])}return new Uint32Array(s)}(s,i,p),P&&(s=V(s),i=G(i));const a=v;v=!1,await Promise.all(o.map(e=>(M=performance.now(),r.buildTile(s,i,e,a).then(()=>{const t=e[0]+","+e[1];b.set(t,(b.get(t)??0)+1),this.debug})))).then(()=>{this.debug,B=!1})}else B=!1},this.refreshMs??1e4);this.disposed.subscribe(()=>S()),r.onNavMeshUpdate.pipe(y(this.disposed),w(200)).subscribe(()=>{h.clear(),h.drawNavMesh(r.navMesh)}),console.log("Create navmesh with debug",this.debug),this.debug&&(this.object.rotation.set(0,0,0),this.object.updateMatrix(),this.object.updateMatrixWorld(),this.object.parent.add(h)),this.disposed.subscribe(()=>{r?.destroy(),h.removeFromParent(),h.dispose()});const z=performance.now()-l;z>1e3&&console.warn(`NavMesh update took ${z} ms. Consider changing tileSize or other parameter that may affect performance`)}};e([z(),t("design:type",Boolean)],q.prototype,"debug",void 0),e([z(),t("design:type",Number)],q.prototype,"walkableClimb",void 0),e([z({range:[0,89]}),t("design:type",Number)],q.prototype,"walkableSlopeAngle",void 0),e([z(),t("design:type",Number)],q.prototype,"walkableHeight",void 0),e([z({range:[.01,10]}),t("design:type",Number)],q.prototype,"cellSize",void 0),q=e([B()],q);export default q;function _(e){if(e.shape instanceof l)return function(e){const t=e.shape;if(t.type!==c.HeightField)throw new Error("The provided collider is not a height field.");let n=!1;const o=t,s=o.heights,i=o.nrows,r=o.ncols,a=o.scale.x,l=o.scale.z,h=o.scale.y,p=i+1,u=new x.PlaneGeometry(l,a,r,i);u.rotateX(-Math.PI/2);const d=u.attributes.position.array;let m=0;for(let e=0;e<p;e++)for(let t=0;t<p;t++)d[m+1]=s[t*p+e]*h,m+=3,0!=d[m+1]&&(n=!0);if(!n){const e=new x.PlaneGeometry(a,l,2,2);return e.rotateX(-Math.PI/2),e}return u}(e);if(e.shape instanceof n)return new x.SphereGeometry(e.shape.radius);if(e.shape instanceof r){const t=e.shape.halfExtents;return new x.BoxGeometry(2*t.x,2*t.y,2*t.z)}if(e.shape instanceof i)return function(e){const t=[];for(let n=0;n<e.length;n+=3)t.push(new x.Vector3(e[n],e[n+1],e[n+2]));const n=(new M).setFromPoints(t),o=[];n.faces.forEach(e=>{const t=e.edge.head().point,n=e.edge.next.head().point,s=e.edge.next.next.head().point;o.push(t.x,t.y,t.z),o.push(n.x,n.y,n.z),o.push(s.x,s.y,s.z)});const s=new x.BufferGeometry;return s.setAttribute("position",new x.Float32BufferAttribute(o,3)),s}(e.shape.vertices);if(e.shape instanceof h){const t=e.shape.vertices,n=e.shape.indices;let o=new x.BufferGeometry;return o.setAttribute("position",new x.Float32BufferAttribute(t,3)),null!=n?o.setIndex(new x.Uint16BufferAttribute(n,1)):o=v.mergeVertices(o),o.computeVertexNormals(),o}if(e.shape instanceof a){const t=e.shape.halfHeight,n=e.shape.radius;return new x.CylinderGeometry(n,n,2*t)}if(e.shape instanceof s){const t=e.shape.halfHeight,n=e.shape.radius;return new x.ConeGeometry(n,2*t)}if(e.shape instanceof o){const t=e.shape.halfHeight,n=e.shape.radius;return new x.CapsuleGeometry(n,2*t)}return console.warn("Unsupported shape",e.shape.type,e),null}function O(e){const t=_(e);if(null==t)return null;const n=L,o=new x.Mesh(t,n);return o.geometry.computeBoundingBox(),o.geometry.scale(1.01,1.01,1.01),o}function W(e,t){const n=e.translation(),o=e.rotation();t.position.set(n.x,n.y,n.z),t.quaternion.set(o.x,o.y,o.z,o.w)}const X=new x.Box3,L=new x.MeshBasicMaterial({wireframe:!1,color:16711680,side:x.FrontSide});/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -15,6 +15,7 @@ export declare class ThirdPersonCameraComponent extends ActorComponent {
|
|
|
15
15
|
far: number;
|
|
16
16
|
viewAngle: number;
|
|
17
17
|
collision: boolean;
|
|
18
|
+
collisionSphereRadius: number;
|
|
18
19
|
camera: PerspectiveCamera;
|
|
19
20
|
distance: number;
|
|
20
21
|
minDistance: number;
|
|
@@ -24,7 +25,6 @@ export declare class ThirdPersonCameraComponent extends ActorComponent {
|
|
|
24
25
|
offsetZ: number;
|
|
25
26
|
autoActivate: boolean;
|
|
26
27
|
bounceBackSpeed: number;
|
|
27
|
-
private collisionCheckRadius;
|
|
28
28
|
private restrictedDistance;
|
|
29
29
|
readonly rotationInput: RestrictedRotationInput;
|
|
30
30
|
readonly zoomInput: DecimalInput;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as t,__metadata as e}from"tslib";import{ActorComponent as i,Component as s}from"../component.js";import{Vector3 as o,MathUtils as n,PerspectiveCamera as h,Object3D as r}from"three";import{ViewController as a}from"../../services/render.js";import{DecimalInput as c,RestrictedRotationInput as d}from"../../input/index.js";import{PhysicsSystem as l
|
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import{ActorComponent as i,Component as s}from"../component.js";import{Vector3 as o,MathUtils as n,PerspectiveCamera as h,Object3D as r}from"three";import{ViewController as a}from"../../services/render.js";import{DecimalInput as c,RestrictedRotationInput as d}from"../../input/index.js";import{PhysicsSystem as l}from"../../services/physics/physics-system.js";import{Parameter as p}from"../../../shader/parameter.js";import{World as m}from"../../services/world.js";import{inject as f}from"../../inject.js";import{ease as u}from"@hology/nebula";const v=void 0!==window&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let w=class extends i{constructor(t,e){super(),this.viewController=t,this.physicsSystem=e,this.aspect=this.viewController.htmlElement.clientWidth/this.viewController.htmlElement.clientHeight,this.near=.5,this.far=500,this.viewAngle=v?30:45,this.collision=!0,this.collisionSphereRadius=.25,this.camera=new h(this.viewAngle,this.aspect,this.near,this.far),this.distance=9,this.minDistance=1.5,this.maxDistance=this.distance,this.height=3,this.offsetX=-1,this.offsetZ=1.5,this.autoActivate=!0,this.bounceBackSpeed=3,this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.rotationInput=new d(-Math.PI/4,Math.PI/2-.7),this.zoomInput=new c(1,0,1),this.offset=new o,this.lookAtOffset=new o(this.offsetX,0,this.offsetZ),this.fixedBehind=!0,this.world=f(m),this.activated=!1,this.isMouseLocked=!1,this.prevFixedBehind=!1,this.blendDurationLeft=0,this.canvas=null,this.pointerLockInactivatedAt=null,this.onMouseDown=t=>{this.isMouseLocked||"mouse"!==t.pointerType||this.hideCursor()},this.onKeyDown=t=>{"Escape"===t.key&&this.showCursor()},this.onPointerLockChange=()=>{null!=document.pointerLockElement||null!=document.mozPointerLockElement||this.showCursor()},this.prevLookAt=new o}async onInit(){this.prevFixedBehind=this.fixedBehind,this.world.scene.add(this.camera),this.rotationInput.rotation.copy(this.actor.rotation),this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.autoActivate&&this.activate()}activate(){this.activated=!0,this.viewController.setCamera(this.camera);const t=this.element;null!=document.body.requestPointerLock&&(t.addEventListener("pointerdown",this.onMouseDown),t.addEventListener("keydown",this.onKeyDown),document.addEventListener("pointerlockchange",this.onPointerLockChange,!1),this.disposed.subscribe(()=>{t.removeEventListener("pointerdown",this.onMouseDown),t.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("pointerlockchange",this.onPointerLockChange,!1)}))}onLateUpdate(t){this.activated&&this.setFromRotation(t)}get element(){return this.viewController.htmlElement}hideCursor(){null!=this.pointerLockInactivatedAt&&performance.now()-this.pointerLockInactivatedAt<1600||(this.element.style.cursor="none",null==this.canvas&&(this.canvas=this.element.getElementsByTagName("canvas")[0]),this.canvas&&(this.canvas.requestPointerLock(),this.isMouseLocked=!0))}showCursor(){this.pointerLockInactivatedAt=performance.now(),this.element.style.cursor="default",window.document.exitPointerLock(),this.isMouseLocked=!1}setFromRotation(t){this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.fixedBehind!==this.prevFixedBehind?(this.blendDurationLeft=1,this.prevFixedBehind=this.fixedBehind):this.blendDurationLeft>0&&(this.blendDurationLeft-=t),this.collision&&this.checkForCollision(t);const e=n.clamp(Math.min(this.restrictedDistance,this.distance),Math.min(this.minDistance,this.restrictedDistance),Math.max(this.distance*this.zoomInput.value,this.minDistance)),i=Math.cos(this.rotationInput.rotation.x)*e,s=this.fixedBehind?0:this.rotationInput.rotation.y;this.offset.x=Math.sin(-s)*i,this.offset.y=Math.sin(this.rotationInput.rotation.x)*e+2,this.offset.z=Math.cos(-s)*-i,this.fixedBehind&&this.offset.add(this.lookAtOffset),this.updateCameraPosition()}checkForCollision(t){const e=this.getLookAtPosition(),i=this.camera.getWorldPosition(x),s=L.subVectors(i,e),o=s.length();if(o<.001)return;s.divideScalar(o);const h=this.physicsSystem.sphereCast(e,this.collisionSphereRadius,s,this.distance,void 0,{excludeActor:this.actor,excludeTriggers:!0,collisionFilter:-2});if(h.hasHit){const t=Math.max(this.minDistance,h.distance-.05);t<this.restrictedDistance&&(this.restrictedDistance=t)}else this.restrictedDistance=n.lerp(this.restrictedDistance,this.distance,n.clamp(this.bounceBackSpeed*t,0,1))}getLookAtPosition(){const t=k;return t.set(0,0,0),t.y=this.height,this.fixedBehind&&t.add(this.lookAtOffset),t.applyMatrix4(this.actor.object.matrixWorld),t}updateCameraPosition(){this.fixedBehind?(y.position.set(this.offset.x,this.offset.y,this.offset.z),y.rotation.set(0,0,0),y.scale.set(1,1,1),y.applyMatrix4(this.actor.object.matrix)):y.position.copy(this.actor.position).add(this.offset);const t=u.easeInOutCubic(1-this.blendDurationLeft);this.blendDurationLeft>0?this.camera.position.lerp(y.position,t):this.camera.position.copy(y.position);const e=this.getLookAtPosition();this.blendDurationLeft>0?(this.prevLookAt.lerp(e,t),this.camera.lookAt(this.prevLookAt)):(this.camera.lookAt(e),this.prevLookAt.copy(e))}};t([p(),e("design:type",Number)],w.prototype,"near",void 0),t([p(),e("design:type",Number)],w.prototype,"far",void 0),t([p(),e("design:type",Number)],w.prototype,"viewAngle",void 0),t([p(),e("design:type",Boolean)],w.prototype,"collision",void 0),t([p(),e("design:type",Number)],w.prototype,"collisionSphereRadius",void 0),w=t([s(),e("design:paramtypes",[a,l])],w);export{w as ThirdPersonCameraComponent};const y=new r,k=new o,L=(new o,new o),x=(new o,new o);export class ThirdPartyCameraComponent extends w{}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"typedi";import{loadScene as t}from"../scene/bootstrap.js";import{ActorFactory as n}from"./actors/factory.js";import{World as s}from"./services/world.js";import{SceneMaterializer as o}from"../scene/materializer.js";import{ViewController as r}from"./services/render.js";import{RenderingView as i}from"../rendering.js";import{PhysicsSystem as a}from"./services/physics/physics-system.js";import{MeshComponent as c}from"./actors/builtin/components/mesh-component.js";import{builtInComponents as m}from"./actors/builtin/components/index.js";import{activeContainerInstance as d}from"./actors/internal/container-map.js";import{InputService as l}from"./input/index.js";import{RuntimeAssetsService as p}from"../scene/runtime-asset-service.js";import{AssetResourceLoader as h}from"../scene/asset-resource-loader.js";import{AssetLoader as f}from"./services/asset-loader.js";import{polyfillClient as u}from"./polyfill.js";import{Subject as g}from"rxjs";import{PointerEvents as w}from"./services/pointer-events.js";import{RuntimeBundledBackendService as j}from"../scene/runtime-bundled-backend-service.js";import{Scene as b}from"three";import{ShaderProvider as v}from"./services/shader-provider.js";import{SceneDataService as S}from"../scene/scene-data-service.js";export function initiateGame(l,g){if(u(),0!=g.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(r);const y=e.of("default"),I=new HologyRuntime(y),x=new n(y,{inEditor:!1});var D;e.set(n,x),D=g.element,Object.assign(D.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"hidden"});const R=new i(g.element,{enableXR:!0===g.xr?.enabled,maxPixelRatio:g.rendering?.maxPixelRatio,resolutionScale:g.rendering?.resolutionScale,bloom:{enabled:!1!==g?.rendering?.bloom?.enabled},reflection:{enabled:!1!==g?.rendering?.reflection?.enabled}});R.renderer.shadowMap.enabled=g.rendering?.shadows?.enabled??!0,R.renderer.shadowMap.autoUpdate=g.rendering?.shadows?.autoUpdate??!0,R.renderer.debug.checkShaderErrors=!1,e.set(i,R);const A=new r(R);e.set(r,A);const G=new j,O=new p(G),P=new h;P.setDataDir(g.dataDir),P.initKtx2(R.renderer);const z=Object.entries(g.shaders).map(([e,t])=>({name:e,type:t})),E=Object.entries(g.actors).map(([e,t])=>({name:e,type:t})),H={...m,...g.components??{}},M=Object.entries(H).map(([e,t])=>({name:e,type:t})),
|
|
1
|
+
import e from"typedi";import{loadScene as t}from"../scene/bootstrap.js";import{ActorFactory as n}from"./actors/factory.js";import{World as s}from"./services/world.js";import{SceneMaterializer as o}from"../scene/materializer.js";import{ViewController as r}from"./services/render.js";import{RenderingView as i}from"../rendering.js";import{PhysicsSystem as a}from"./services/physics/physics-system.js";import{MeshComponent as c}from"./actors/builtin/components/mesh-component.js";import{builtInComponents as m}from"./actors/builtin/components/index.js";import{activeContainerInstance as d}from"./actors/internal/container-map.js";import{InputService as l}from"./input/index.js";import{RuntimeAssetsService as p}from"../scene/runtime-asset-service.js";import{AssetResourceLoader as h}from"../scene/asset-resource-loader.js";import{AssetLoader as f}from"./services/asset-loader.js";import{polyfillClient as u}from"./polyfill.js";import{Subject as g}from"rxjs";import{PointerEvents as w}from"./services/pointer-events.js";import{RuntimeBundledBackendService as j}from"../scene/runtime-bundled-backend-service.js";import{Scene as b}from"three";import{ShaderProvider as v}from"./services/shader-provider.js";import{SceneDataService as S}from"../scene/scene-data-service.js";export function initiateGame(l,g){if(u(),0!=g.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(r);const y=e.of("default"),I=new HologyRuntime(y),x=new n(y,{inEditor:!1});var D;e.set(n,x),D=g.element,Object.assign(D.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"hidden"});const R=new i(g.element,{enableXR:!0===g.xr?.enabled,maxPixelRatio:g.rendering?.maxPixelRatio,resolutionScale:g.rendering?.resolutionScale,bloom:{enabled:!1!==g?.rendering?.bloom?.enabled},reflection:{enabled:!1!==g?.rendering?.reflection?.enabled},shadows:{cascadeUpdateIntervals:[22,135,250,500]}});R.renderer.shadowMap.enabled=g.rendering?.shadows?.enabled??!0,R.renderer.shadowMap.autoUpdate=g.rendering?.shadows?.autoUpdate??!0,R.renderer.debug.checkShaderErrors=!1,e.set(i,R);const A=new r(R);e.set(r,A);const G=new j,O=new p(G),P=new h;P.setDataDir(g.dataDir),P.initKtx2(R.renderer);const z=Object.entries(g.shaders).map(([e,t])=>({name:e,type:t})),E=Object.entries(g.actors).map(([e,t])=>({name:e,type:t})),H={...m,...g.components??{}},M=Object.entries(H).map(([e,t])=>({name:e,type:t})),U=new v(z);e.set(v,U);const W=new f(P,O,z);e.set(f,W);const k=new b,F=new o(k,new S,O,P,R,z,E,x,M);e.set(o,F);const N=e.get(s);return e.set(s,N),N.materializer=F,(async()=>{const n=e.get(a);if(await n.start(),I.isShutdown)return;if(await G.preloadData(),I.isShutdown)return;N.scene=k;const{scene:s,actors:o}=await t(R,g.sceneName,g.dataDir,g.shaders,g.actors,H,x,G,O,P,{detailTier:g.detailTier});N.scene=s,n.scene=N.scene;for(const e of k.children)N.scene.add(e);if(I.isShutdown)return void R.stop();e.import([c]);for(const e of o)N.addActor(e);n.addFromScene(s),console.log("Start compile shaders"),console.time("compile shaders"),await R.compileAsync(),console.timeEnd("compile shaders"),console.log("Finished compile shaders. Programs: ",R.renderer.info.programs?.length??0),R.loop(e=>{}),I.status=5,I.shutdownStarted.subscribe(()=>{P.disposeAll()}),d.value=y,y.remove(l),y.set({id:l,type:l});const r=y.get(l);d.value=null,I.gameInstance=r,y.get(w).start(),r instanceof GameInstance&&await r.onStart(),I._resolver(!0)})(),I}export class GameInstance{onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(e){this.containerInstance=e,this.status=0,this.isShutdown=!1,this.shutdownStarted=new g,this.ready=new Promise(e=>{this._resolver=e})}getWorld(){return this.containerInstance.get(s)}getService(e){return this.containerInstance.get(e)}shutdown(){this.isShutdown=!0;const e=this.shutdownStarted;e.next(),e.complete(),this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(l).stop();const t=this.containerInstance.get(i);t?.stop();const n=this.containerInstance.get(r);n.setMuted(!0),n.dispose();for(const e of this.getWorld().actors)this.getWorld().removeActor(e);this.containerInstance.get(a).stop(),this.containerInstance.get(o).dispose(),this.containerInstance.get(w).stop(),this.containerInstance.reset()}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -41,6 +41,11 @@ interface RayTestOptions {
|
|
|
41
41
|
excludeActor?: BaseActor;
|
|
42
42
|
excludeTriggers?: boolean;
|
|
43
43
|
}
|
|
44
|
+
interface ShapeCastOptions {
|
|
45
|
+
collisionFilter?: InteractionGroups;
|
|
46
|
+
excludeActor?: BaseActor;
|
|
47
|
+
excludeTriggers?: boolean;
|
|
48
|
+
}
|
|
44
49
|
export declare class ShapeCastResult {
|
|
45
50
|
static shared: ShapeCastResult;
|
|
46
51
|
actor?: BaseActor;
|
|
@@ -572,7 +577,7 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
|
|
|
572
577
|
* @param collisionFilter - Optional. An interaction group filter to restrict which objects are considered for collision.
|
|
573
578
|
* @returns The ShapeCastResult containing hit information if a collision occurred, or indicating no hit otherwise.
|
|
574
579
|
*/
|
|
575
|
-
sphereCast(position: Vector3, radius: number, direction: Vector3, distance: number, result?: ShapeCastResult,
|
|
580
|
+
sphereCast(position: Vector3, radius: number, direction: Vector3, distance: number, result?: ShapeCastResult, options?: ShapeCastOptions): ShapeCastResult;
|
|
576
581
|
/**
|
|
577
582
|
* Performs a shape cast (swept collision test) for the given actor in a specified direction and distance.
|
|
578
583
|
* This method checks if the actor's collider(s) would intersect with any other colliders in the physics world
|
|
@@ -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 y,BufferGeometry as u,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as B,Scene as x,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,CollisionShapeSource as R,ConeCollisionShape as D,ConvexPolyhedronCollisionShape as z,CylinderCollisionShape as T,PhysicalShapeMesh as E,PlaneCollisionShape as M,SphereCollisionShape as P,TrimeshCollisionShape as V}from"../../../index.js";import{LandscapeGroup as _}from"../../../scene/landscape/landscape.js";import{ViewController as I}from"../render.js";import{World as k}from"../world.js";import*as F from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as W}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as N}from"./abstract-physics-system.js";import{ActorComponent as j,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(t){super(),this.viewController=t,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.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new B,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 u,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 y(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 rt(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe(t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach(t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;null!=e&&e.parent instanceof x&&(ct(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&dt(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(st,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;at(mt.origin,t),at(mt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(mt,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=mt.pointAt(a.timeOfImpact);i._internal=a,ct(i.hitNormal,a.normal),ct(i.hitPoint,e),i.distance=yt.subVectors(i.hitPoint,t).length();const s=this.world.bodies.getAll().find(t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,t=>t===a.collider));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){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 J.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())ht(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 E&&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){const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}}else t instanceof _?this.addLandscapeGroup(t):(t instanceof p||t instanceof x)&&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;let e=t.userData.collisionShapes?.[o];if(null==e&&t.parent instanceof C&&(e=t.parent.collisionShapes),null==e)continue;let n=s.get(e);null==n&&(n=this.instancedShapeReset(e),s.set(e,n));const r=new f;r.matrix.identity(),t.getMatrixAt(o,i),r.applyMatrix4(i);this.createStaticBody(r,n)}}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=>t.source===R.rendered?t.withOffset(wt):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,pt);const a=e.computedMovement();return ct(ut,a),ut}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,pt);const r=e.computedMovement();return ct(ut,r),ut}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(X),s=e.getWorldQuaternion(Y);t.setNextKinematicTranslation(ot(i)),t.setNextKinematicRotation(nt(s))}(this.actorBodies.get(t.id),t.object)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.setAngvel(tt,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.setLinvel(tt,!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(ot(e),!1)}getPosition(t,e=new b){const i=this.actorBodies.get(t.id);i&&ct(e,i.translation())}setRotation(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(nt(e),!1)}getRotation(t,e=new w){const i=this.actorBodies.get(t.id);i&&dt(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(),s=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=s.x,a[t+1]*=s.y,a[t+2]*=s.z;const l=t.index;for(let t=0;t<l.count;t+=3){const e=r.getX(l.getX(t)),i=r.getX(l.getY(t)),s=r.getX(l.getZ(t));(e>.5||i>.5||s>.5)&&(l.setX(t,0),l.setY(t,0),l.setZ(t,0))}const c=i.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);at(e,o),t.setTranslation(e,!1),this.world.createCollider(c,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(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);at(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 ht(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)}),Z(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);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.addTorque(tt,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.applyTorqueImpulse(tt,!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);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.addForce(tt,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.applyImpulse(tt,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);at(tt,e),null==i?s?.addForce(tt,!0):(at(et,i),s?.addForceAtPoint(tt,et,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);at(tt,e),null==i?s.applyImpulse(tt,!0):(at(et,i),s.applyImpulseAtPoint(tt,et,!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=it;ct(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);tt.x=a.x,tt.y=a.y,tt.z=a.z,o.applyImpulse(tt,!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 _){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&&Z(e,t.object)}setupWorld(){const t=new i.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,i,s,o=ShapeCastResult.shared,n=void 0){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=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n,null,void 0,void 0);if(null!=c){ct(o.hitPoint,c.witness1),o.normal.set(c.normal1.x,c.normal1.y,c.normal1.z),o.distance=c.time_of_impact,o.hasHit=!0;const t=c.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 y=this.world.castShape(l,c,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=y){y.collider;const t=r;return ct(s.hitPoint,y.witness1),Bt(t.rotation(),y.normal1,s.normal,q),s.distance=y.time_of_impact,s.actor=this.bodyActors.get(y.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);for(const i of e){if(null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return Z(n,t),n.userData=t.uuid,n.sleep(),n}addShape(t=void 0,e,i){const s=i?.getWorldScale(gt)??$,o=this.createShape(e,s);this.applyShapeSettings(o,e);const n=e.offset.clone().multiply(s);at(o.translation,n);const r=(new w).setFromEuler(e.rotation);e instanceof z&&e.mesh instanceof d.Mesh&&r.multiply(e.mesh.getWorldQuaternion(Y)),lt(o.rotation,r);return this.world.createCollider(o,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 i.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 i.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof V){const s=null!=t.geometry.getIndex()?t.geometry:F.mergeVertices(t.geometry),o=extractFloat32Array(s.getAttribute("position"));for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(t instanceof z){let s;t.mesh instanceof d.Mesh?s=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?s=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=extractFloat32Array(s.getAttribute("position"));if(t.mesh instanceof d.Mesh){const e=W(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;n.length;return i.ColliderDesc.convexHull(n)}if(t instanceof P){const s=2*e.x-e.y-e.z;return Math.abs(s)>.01?this.createShape(new z(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):i.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof T?i.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof D?i.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof M?i.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};Q=t([v(),e("design:paramtypes",[I])],Q);export{Q as PhysicsSystem};const X=new b,Y=new d.Quaternion;function Z(t,e){const i=e.getWorldPosition(X),s=e.getWorldQuaternion(Y);t.setTranslation(ot(i),!1),t.setRotation(nt(s),!1)}const J=new b,$=new b(1,1,1),tt=new i.Vector3(0,0,0),et=new i.Vector3(0,0,0),it=new b,st=new d.Vector2;function ot(t){return at(tt,t),tt}function nt(t){return lt(q,t),q}const rt=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function at(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function lt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}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){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const yt=new b,ut=new b,pt=t=>!t.isSensor(),gt=new b;const mt=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));let ft=class extends j{constructor(){super(...arguments),this._active=!0,this.physics=O(Q),this.world=O(k)}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}};ft=t([L()],ft);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}const wt=new b;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()}}/*
|
|
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 y,BufferGeometry as u,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as B,Scene as x,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,CollisionShapeSource as R,ConeCollisionShape as D,ConvexPolyhedronCollisionShape as z,CylinderCollisionShape as T,PhysicalShapeMesh as E,PlaneCollisionShape as M,SphereCollisionShape as P,TrimeshCollisionShape as V}from"../../../index.js";import{LandscapeGroup as _}from"../../../scene/landscape/landscape.js";import{ViewController as F}from"../render.js";import{World as I}from"../world.js";import*as k from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as W}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as N}from"./abstract-physics-system.js";import{ActorComponent as j,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(t){super(),this.viewController=t,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.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new B,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 u,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 y(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 rt(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe(t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach(t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;null!=e&&e.parent instanceof x&&(ct(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&dt(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(st,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;at(mt.origin,t),at(mt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(mt,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=mt.pointAt(a.timeOfImpact);i._internal=a,ct(i.hitNormal,a.normal),ct(i.hitPoint,e),i.distance=yt.subVectors(i.hitPoint,t).length();const s=this.world.bodies.getAll().find(t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,t=>t===a.collider));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){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 J.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())ht(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 E&&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){const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}}else t instanceof _?this.addLandscapeGroup(t):(t instanceof p||t instanceof x)&&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;let e=t.userData.collisionShapes?.[o];if(null==e&&t.parent instanceof C&&(e=t.parent.collisionShapes),null==e)continue;let n=s.get(e);null==n&&(n=this.instancedShapeReset(e),s.set(e,n));const r=new f;r.matrix.identity(),t.getMatrixAt(o,i),r.applyMatrix4(i);this.createStaticBody(r,n)}}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=>t.source===R.rendered?t.withOffset(wt):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,pt);const a=e.computedMovement();return ct(ut,a),ut}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,pt);const r=e.computedMovement();return ct(ut,r),ut}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(X),s=e.getWorldQuaternion(Y);t.setNextKinematicTranslation(ot(i)),t.setNextKinematicRotation(nt(s))}(this.actorBodies.get(t.id),t.object)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.setAngvel(tt,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.setLinvel(tt,!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(ot(e),!1)}getPosition(t,e=new b){const i=this.actorBodies.get(t.id);i&&ct(e,i.translation())}setRotation(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(nt(e),!1)}getRotation(t,e=new w){const i=this.actorBodies.get(t.id);i&&dt(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(),s=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=s.x,a[t+1]*=s.y,a[t+2]*=s.z;const l=t.index;for(let t=0;t<l.count;t+=3){const e=r.getX(l.getX(t)),i=r.getX(l.getY(t)),s=r.getX(l.getZ(t));(e>.5||i>.5||s>.5)&&(l.setX(t,0),l.setY(t,0),l.setZ(t,0))}const c=i.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);at(e,o),t.setTranslation(e,!1),this.world.createCollider(c,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(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);at(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 ht(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)}),Z(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);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.addTorque(tt,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.applyTorqueImpulse(tt,!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);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.addForce(tt,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.applyImpulse(tt,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);at(tt,e),null==i?s?.addForce(tt,!0):(at(et,i),s?.addForceAtPoint(tt,et,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);at(tt,e),null==i?s.applyImpulse(tt,!0):(at(et,i),s.applyImpulseAtPoint(tt,et,!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=it;ct(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);tt.x=a.x,tt.y=a.y,tt.z=a.z,o.applyImpulse(tt,!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 _){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&&Z(e,t.object)}setupWorld(){const t=new i.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){ct(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 y=this.world.castShape(l,c,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=y){y.collider;const t=r;return ct(s.hitPoint,y.witness1),Bt(t.rotation(),y.normal1,s.normal,q),s.distance=y.time_of_impact,s.actor=this.bodyActors.get(y.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);for(const i of e){if(null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return Z(n,t),n.userData=t.uuid,n.sleep(),n}addShape(t=void 0,e,i){const s=i?.getWorldScale(gt)??$,o=this.createShape(e,s);this.applyShapeSettings(o,e);const n=e.offset.clone().multiply(s);at(o.translation,n);const r=(new w).setFromEuler(e.rotation);e instanceof z&&e.mesh instanceof d.Mesh&&r.multiply(e.mesh.getWorldQuaternion(Y)),lt(o.rotation,r);return this.world.createCollider(o,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 i.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 i.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof V){const s=null!=t.geometry.getIndex()?t.geometry:k.mergeVertices(t.geometry),o=extractFloat32Array(s.getAttribute("position"));for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(t instanceof z){let s;t.mesh instanceof d.Mesh?s=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?s=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=extractFloat32Array(s.getAttribute("position"));if(t.mesh instanceof d.Mesh){const e=W(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;n.length;return i.ColliderDesc.convexHull(n)}if(t instanceof P){const s=2*e.x-e.y-e.z;return Math.abs(s)>.01?this.createShape(new z(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):i.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof T?i.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof D?i.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof M?i.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};Q=t([v(),e("design:paramtypes",[F])],Q);export{Q as PhysicsSystem};const X=new b,Y=new d.Quaternion;function Z(t,e){const i=e.getWorldPosition(X),s=e.getWorldQuaternion(Y);t.setTranslation(ot(i),!1),t.setRotation(nt(s),!1)}const J=new b,$=new b(1,1,1),tt=new i.Vector3(0,0,0),et=new i.Vector3(0,0,0),it=new b,st=new d.Vector2;function ot(t){return at(tt,t),tt}function nt(t){return lt(q,t),q}const rt=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function at(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function lt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}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){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const yt=new b,ut=new b,pt=t=>!t.isSensor(),gt=new b;const mt=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));let ft=class extends j{constructor(){super(...arguments),this._active=!0,this.physics=O(Q),this.world=O(I)}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}};ft=t([L()],ft);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}const wt=new b;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 (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{BackSide as e,Color as t,ShaderMaterial as i,UniformsLib as n,UniformsUtils as a,Object3D as l,Mesh as r,InstancedMesh as o,BatchedMesh as s,Vector3 as c}from"three";import{glslFunction as p,NodeShaderMaterial as u,Vec4Node as d,uniforms as m,transformed as v,neg as f,uniformFloat as h,uniformVec3 as _,vec3 as g,rgba as x,vec4 as k,negVec3 as A,ifDefApply as
|
|
1
|
+
import{BackSide as e,Color as t,ShaderMaterial as i,UniformsLib as n,UniformsUtils as a,Object3D as l,Mesh as r,InstancedMesh as o,BatchedMesh as s,Vector3 as c}from"three";import{glslFunction as p,NodeShaderMaterial as u,Vec4Node as d,uniforms as m,transformed as v,neg as f,uniformFloat as h,uniformVec3 as _,vec3 as g,rgba as x,vec4 as k,negVec3 as A,ifDefApply as w,BooleanExpression as y,select as b,attributes as M}from"three-shader-graph";export class OutlineEffect{constructor(i,n={}){this.applied=new WeakSet,this.enabled=!0;const a=void 0!==n.defaultThickness?n.defaultThickness:.003,l=((new t).fromArray(void 0!==n.defaultColor?n.defaultColor:[0,0,0]),void 0!==n.defaultAlpha?n.defaultAlpha:1),r=void 0!==n.defaultKeepAlive&&n.defaultKeepAlive,o={},s={};["#include <common>","#include <uv_pars_vertex>","#include <displacementmap_pars_vertex>","#include <fog_pars_vertex>","#include <morphtarget_pars_vertex>","#include <skinning_pars_vertex>","#include <logdepthbuf_pars_vertex>","#include <clipping_planes_pars_vertex>","uniform float outlineThickness;","vec4 calculateOutline( vec4 pos, vec3 normal, vec4 skinned ) {","\tfloat thickness = outlineThickness;","\tconst float ratio = 1.0;","\tvec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );"," float viewDistance = length((modelViewMatrix * vec4(skinned.xyz, 1.0)).xyz);"," float scale = pow(viewDistance, 0.5); // sqrt, or any exponent","\tvec4 norm = normalize( pos - pos2 );","\treturn pos + norm * thickness * scale * ratio;","}","void main() {","\t#include <uv_vertex>","\t#include <beginnormal_vertex>","\t#include <morphnormal_vertex>","\t#include <skinbase_vertex>","\t#include <skinnormal_vertex>","\t#include <begin_vertex>","\t#include <morphtarget_vertex>","\t#include <skinning_vertex>","\t#include <displacementmap_vertex>","\t#include <project_vertex>","\tvec3 outlineNormal = - objectNormal;","\tgl_Position = calculateOutline( gl_Position, outlineNormal, vec4( transformed, 1.0 ) );","\t#include <logdepthbuf_vertex>","\t#include <clipping_planes_vertex>","\t#include <fog_vertex>","}"].join("\n"),["#include <common>","#include <fog_pars_fragment>","#include <logdepthbuf_pars_fragment>","#include <clipping_planes_pars_fragment>","uniform vec3 outlineColor;","uniform float outlineAlpha;","void main() {","\t#include <clipping_planes_fragment>","\t#include <logdepthbuf_fragment>","\tgl_FragColor = vec4( outlineColor, outlineAlpha );","\t#include <tonemapping_fragment>","\t#include <colorspace_fragment>","\t#include <fog_fragment>","\t#include <premultiplied_alpha_fragment>","}"].join("\n");function f(t){Array.isArray(t)&&(t=t[0]);const i=m.projectionMatrix.multiply(m.modelViewMatrix).multiplyVec(v.position);let n=v.normal;n=w("DOUBLE_SIDED",n,e=>b(new y("gl_FrontFacing"),e,e.multiplyScalar(-1)));const r=h("outlineThickness",a),o=_("outlineColor",new c(0,0,0)),s=h("outlineAlpha",l),f=p(d,{pos:i,normal:n,skinned:v.position,outlineThickness:r},"\n\t\t\t\tfloat thickness = outlineThickness;\n\t\t\t\tvec4 viewPos = modelViewMatrix * vec4(skinned.xyz, 1.0);\n\t\t\t\tfloat viewDistance = length(viewPos.xyz);\n\t\t\t\tfloat scale = pow(viewDistance, 0.4) * 0.5;\n\t\t\t\tvec3 displaced = viewPos.xyz + normal * thickness * scale;\n\t\t\t\treturn projectionMatrix * vec4(displaced, 1.0);\n\t\t\t"),g=x(o,s),A=[g,k(0),k(0)],M="number"==typeof t.userData.mrtOutputs&&t.userData.mrtOutputs>1,D=new u({position:f,outputs:M?A:void 0,color:M?void 0:g});return D.side=e,D.depthTest=!0,D.depthWrite=!0,D.transparent=!0,D}this.createMaterial=f,this.getOutlineMaterial=function(e){const t=function(e){let t=o[e.uuid];return void 0===t&&(t={material:f(e),used:!0,keepAlive:r,count:0},o[e.uuid]=t),t.used=!0,t.material}(e);return s[t.uuid]=e,function(e,t){Array.isArray(t)&&(t=t[0]);if("invisible"===e.name)return;const i=t.userData.outlineParameters;e.fog=t.fog,e.toneMapped=t.toneMapped,e.premultipliedAlpha=t.premultipliedAlpha,e.displacementMap=t.displacementMap,void 0!==i?(!1===t.visible?e.visible=!1:e.visible=void 0===i.visible||i.visible,e.transparent=void 0!==i.alpha&&i.alpha<1||t.transparent,void 0!==i.keepAlive&&(o[t.uuid].keepAlive=i.keepAlive)):(e.transparent=t.transparent,e.visible=t.visible);!0!==t.wireframe&&!1!==t.depthTest||(e.visible=!1);t.clippingPlanes&&(e.clipping=!0,e.clippingPlanes=t.clippingPlanes,e.clipIntersection=t.clipIntersection,e.clipShadows=t.clipShadows);e.version=t.version}(t,e),t},this.updateUniforms=function(e,t){const i=t.userData.outlineParameters;e.uniforms.outlineAlpha.value=t.opacity,void 0!==i&&(void 0!==i.thickness&&(e.uniforms.outlineThickness.value=i.thickness),void 0!==i.color&&e.uniforms.outlineColor.value.fromArray(i.color),void 0!==i.alpha&&(e.uniforms.outlineAlpha.value=i.alpha)),t.displacementMap&&(e.uniforms.displacementMap.value=t.displacementMap,e.uniforms.displacementScale.value=t.displacementScale,e.uniforms.displacementBias.value=t.displacementBias)}}apply(e){if(!(e instanceof r)||e instanceof s||e instanceof o)return;if(this.applied.has(e))return;this.applied.add(e);const t=e.onAfterRender;e.onAfterRender=(i,n,a,l,r,o)=>{t(i,n,a,l,r);let s=!1;if(Array.isArray(r)?s=r.some(e=>e&&e.userData&&e.userData.outlineParameters):r&&r.userData&&r.userData.outlineParameters&&(s=!0),!s)return;const c=e.material,p=this.getOutlineMaterial(c);e.material=p,this.updateUniforms(p,r),i.renderBufferDirect(a,n,l,p,e,o),e.material=c}}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
package/dist/rendering.d.ts
CHANGED
|
@@ -19,6 +19,11 @@ export type RenderingViewOptions = {
|
|
|
19
19
|
};
|
|
20
20
|
shadows?: {
|
|
21
21
|
autoUpdate?: boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Array of update intervals (ms) for each CSM cascade. The first value is for the closest shadow, the next for the next cascade, etc.
|
|
24
|
+
* Example: [16, 100, 250, 500] updates the closest every 16ms, the next every 100ms, etc.
|
|
25
|
+
*/
|
|
26
|
+
cascadeUpdateIntervals?: number[];
|
|
22
27
|
};
|
|
23
28
|
ao?: {
|
|
24
29
|
enabled: boolean;
|
|
@@ -47,6 +52,9 @@ export declare class RenderingView {
|
|
|
47
52
|
fpsCap: number | null;
|
|
48
53
|
postProcessVolumes: PostProcessVolume[];
|
|
49
54
|
postProcessSettings: PostProcessSettings;
|
|
55
|
+
/** Tracks last update time (ms) for each CSM cascade. */
|
|
56
|
+
private csmCascadeLastUpdate?;
|
|
57
|
+
private csmUpdateInvervals;
|
|
50
58
|
aoPass: GTAOPass;
|
|
51
59
|
private bloomPass;
|
|
52
60
|
private colorPass;
|
|
@@ -114,6 +122,7 @@ export declare class RenderingView {
|
|
|
114
122
|
*/
|
|
115
123
|
private updateLightUniformValues;
|
|
116
124
|
private createGBufferMaterial;
|
|
125
|
+
private updateCsm;
|
|
117
126
|
loop(onFrame: (deltaTime: number) => any, showStats?: boolean): void;
|
|
118
127
|
private applyGBufferMaterials;
|
|
119
128
|
private unapplyGBufferMaterials;
|
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 r,Material as a,Matrix4 as n,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as d,WebGLRenderTarget as u,Texture as c,Euler as p,MeshStandardMaterial as m}from"three";import{CopyShader as f,EffectComposer as g,FXAAShader as M,GammaCorrectionShader as v,LUTPass as T,RenderPass as x,ShaderPass as P,VRButton as b}from"three-stdlib";import{CSMShader as y,CSMUtil as w}from"./csm.js";import{bool as R,colorToNormal as S,float as C,NodeShaderMaterial as A,standardMaterial as F,uniformFloat as U,uniformVec3 as B,toonMaterial as I,lambertMaterial as E,normalize as O,rgb as D,rgba as L,textureSampler2d as W,transformed as j,varying as G,varyingAttributes as V,varyingTransformed as _,vec4 as N,BooleanExpression as q,select as k,ifDefApply as z,uniformSampler2d as H,RgbaNode as $,mix as X}from"three-shader-graph";import{Reflector as Y}from"three-stdlib";import{BokehPass as Q,OutputPass as K}from"three/examples/jsm/Addons.js";import{CSM as J}from"three/examples/jsm/csm/CSM.js";import Z from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as ee}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as te}from"typedi";import{depthUniformName as se,farUniformName as ie,nearUniformName as re,resolutionUniformName as ae,sceneNormalUniformName as ne,screenUV as oe,supportsDepthTextureExtension as le}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as he}from"./shader-nodes/time.js";import{aoMapUniformName as de,sceneMapUniformName as ue}from"./shader-nodes/scene-sample.js";import{DepthPass as ce}from"./utils/three/depth-pass.js";import{GPUStatsPanel as pe}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as me}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as fe,traverseVisibleStop as ge}from"./utils/three/traverse.js";import{clamp as Me}from"./utils/math.js";import{ColorPass as ve}from"./rendering/color-pass.js";import{SSRPass as Te}from"./rendering/ssr/SSRPass.js";import{SSRShader as xe}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as Pe}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as be}from"./rendering/outline-effect.js";import{UnrealBloomPass as ye}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as we}from"./shader-nodes/depth.js";import{packDepthToRGBA as Re}from"three-shader-graph";import{FogVolumeObject as Se}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Ce}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Ae}from"./shader-nodes/pom.js";import{FullScreenQuad as Fe}from"three-stdlib";import{edgeDepthEffect as Ue}from"./shader-nodes/effects";import{decalDiscard as Be}from"./shader-nodes/decal.js";import{Pass as Ie}from"three/examples/jsm/Addons.js";w.patchSetupMaterial();const Ee=document.createElement("div");Ee.style.position="absolute",Ee.style.left="50%",Ee.style.top="50%",Ee.style.color="black",Ee.style.zIndex="999";(new i.Layers).set(9);const Oe=new i.MeshBasicMaterial({color:"black"}),De=new i.MeshDepthMaterial;var Le;De.depthPacking=i.RGBADepthPacking,De.blending=i.NoBlending,De.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(Le||(Le={}));const We=(()=>{const e=new Uint8Array([255,255,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),je=(()=>{const e=new Uint8Array([0,0,0,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ge=(()=>{const e=new Uint8Array([128,128,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ve=new A({color:C(0),position:N(C(0))});Ve.visible=!1;const _e=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let Ne=0,qe=e=class{setPaused(e){this.paused=e}resizeRender(){const e=this.container.clientWidth,t=this.container.clientHeight;this.previousClientWith===e&&this.previousClientHeight===t||0!==e&&0!==t&&(this.previousClientWith=e,this.previousClientHeight=t,this.camera instanceof l&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(e,t),this.composer.setSize(e,t),this.dofPass.setSize(e*this.renderer.getPixelRatio(),t*this.renderer.getPixelRatio()),this.fxaaPass.setSize(e*this.renderer.getPixelRatio(),t*this.renderer.getPixelRatio()),this.fxaaPass.uniforms.resolution.value.set(1/(e*this.renderer.getPixelRatio()),1/(t*this.renderer.getPixelRatio())),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)}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)}constructor(t,s={}){this.container=t,this.options=s,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.postProcessVolumes=[],this.postProcessSettings={},this._id=Ne++,this.fquadCopy=new Fe(new d(f)),this.fquadCopyOpaque=new Fe(new A({outputs:[H("tSceneColor",new c).sample(V.uv),N(H("tDepthTexture",new i.DepthTexture(1,1)).sample(V.uv).r)]})),this.fquadBlendAO=(()=>{const e=N(1),t=new A({outputs:[H("tAO",new c).sample(oe),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Fe(t)})(),this.resolutionScale=1,this.maxPixelRatio=_e?1:window.devicePixelRatio,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 Z,this._showStats=!0,this.gbufferMaterialCache=new Map,this.tbufferMaterialCache=new Map,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 r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,window.renderer=this.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(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(b.createButton(this.renderer));const a=new be(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=a,this.createGRenderTarget(),this.composer=new g(this.renderer),this.composer.setSize(t.clientWidth,t.clientHeight);var n=(t.clientWidth||1)/(t.clientHeight||1);const o=new i.PerspectiveCamera(45,n,.5,800);o.layers.enable(19),this.setCamera(o),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.renderer.gammaFactor=1.4,w.renderingView=this,this.isDepthTextureExtensionSupported=le(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container);const l=new i.Vector2(t.clientWidth,t.clientHeight),h=(new x(this.scene,this.camera),new P(f,"prevtexture"));h.enabled=!0,h.needsSwap=!0,h.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=h;const u=new ye(l,1.5,.4,.85);u.threshold=1,u.strength=.9,u.radius=.5,this.bloomPass=u;const p=new ee(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});p.normalRenderTarget?.dispose(),p.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),p.output=ee.OUTPUT.Off,p.enabled=!1,this.aoPass=p,this.fquadBlendAO.material.uniforms.tAO.value=p.pdRenderTarget.texture,xe.fragmentShader=xe.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const m=new Te({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});m.output=Te.OUTPUT.Default,m.blur=!0,m.fresnel=!1,m.distanceAttenuation=!0,m.maxDistance=50,m.selective=!0,m.bouncing=!1,m.opacity=.4,m.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=m,!1!==this.options.ao?.enabled&&this.composer.addPass(p);const y=new nt((e,t,s,i,r)=>{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(y);const R=new nt((e,t,s,i,r)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(Le.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(R),this.composer.addPass(h),this.composer.addPass(m),this.phasedRenderPass=new at(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(u),u.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new Pe(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new Q(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const S=new ve;this.composer.addPass(S),this.colorPass=S,S.vignetteEnabled=!1,this.outlinePass=new me(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 C=new P(M);C.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(C),this.fxaaPass=C,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new P(v).clear=!1,this.fixStatsStyle(),this.lutPass=new T({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const F=new P(f,"prevtexture");F.enabled=!0,F.needsSwap=!1,F.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],F.renderToScreen=!0;const U=new K;this.composer.addPass(U)}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){this.camera=e,this.composer.passes.forEach(t=>{t instanceof x?t.camera=e:t instanceof me?t.renderCamera=e:(t instanceof ce||t instanceof ee)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),this.phasedRenderPass&&(this.phasedRenderPass.camera=e),null==this.csm?(this.csm=new J({maxFar:100,lightFar:250,lightMargin:20,cascades:_e?2:4,shadowMapSize:2048*(_e?.5:1),lightDirection:new i.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"}),this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,h.lights_fragment_begin=y.lights_fragment_begin):(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 r=Math.max(1,Math.floor(t.clientWidth*s)),a=Math.max(1,Math.floor(t.clientHeight*s)),n=new i.WebGLRenderTarget(r,a);return n.texture.minFilter=i.NearestFilter,n.texture.magFilter=i.NearestFilter,n.texture.generateMipmaps=!1,n.stencilBuffer=!1,n.depthTexture=new i.DepthTexture(r,a),n.depthTexture.type=i.UnsignedShortType,n.depthTexture.minFilter=i.NearestFilter,n.depthTexture.magFilter=i.NearestFilter,n}static createAOMaskDepthRenderTarget(e,t){const s=Math.max(1,t.clientWidth*e.getPixelRatio()),r=Math.max(1,t.clientHeight*e.getPixelRatio()),a=new i.DepthTexture(s,r);a.type=i.UnsignedInt248Type,a.minFilter=i.NearestFilter,a.magFilter=i.NearestFilter;const n=new i.WebGLRenderTarget(s,r,{type:i.HalfFloatType,depthTexture:a});return n.texture.minFilter=i.NearestFilter,n.texture.magFilter=i.NearestFilter,n.texture.generateMipmaps=!1,n.stencilBuffer=!1,n}createSceneColorRenderTarget(e,t){const s=this.gRenderTarget.width,r=this.gRenderTarget.height,a=new i.WebGLRenderTarget(s,r,{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return a.texture.minFilter=i.LinearFilter,a.texture.magFilter=i.LinearFilter,a.texture.generateMipmaps=!1,a.textures[1].minFilter=i.NearestFilter,a.textures[1].magFilter=i.NearestFilter,a}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose();const t=Math.max(1,e.clientWidth*this.renderer.getPixelRatio()),s=Math.max(1,e.clientHeight*this.renderer.getPixelRatio()),r=new i.DepthTexture(t,s);r.type=i.UnsignedIntType,r.minFilter=i.NearestFilter,r.magFilter=i.NearestFilter,this.gRenderTarget=new u(t,s,{count:3,minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat,depthTexture:r}),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(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren(),this.volumetricFogPass.dispose(),w.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){if(null!=this.scene.environment&&(e instanceof A&&(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:Je(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 A||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)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],r=s[e].value;null!=t&&t.value!==r&&(t.value=r)}}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of ot){const t=i[e],r=s[e];null!=r&&null!=t&&(t.value=r.value)}}createGBufferMaterial(e,t){const s=t===Le.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let r=s.get(e);if(null==r){let n=V.uv;if(e instanceof Ce&&null!=e.heightMap){const t=U("heightScale",e.heightScale??1);n=Ae(n,W(e.heightMap),t)}let o=_.normal;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.normalMap??Ge,s=U("useNormalMap",null!=e.normalMap?1:0),i=U("normalScale",e.normalScale?.x??1),r=S(W(t).sample(n),i);o=X(_.normal,r,s)}else e instanceof A&&null!=e.outputNormal&&(o=e.outputNormal);!0!==e.userData.disableAO&&(o=z("DOUBLE_SIDED",o,e=>k(new q("gl_FrontFacing"),e,e.multiplyScalar(-1))));let l=e.userData?.reflective?C(0):C(1);if(e instanceof i.MeshStandardMaterial){const t=U("roughness",e.roughness??1),s=e.roughnessMap??We,i=U("useRoughnessMap",null!=e.roughnessMap?1:0),r=W(s).sample(n).g.multiply(t);l=X(t,r,i)}else e instanceof A&&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){const t=e.lightMap??je,s=U("useLightMap",null!=e.lightMap?1:0),i=U("lightMapIntensity",e.lightMapIntensity??1),r=W(t).sample(n).rgb.multiplyScalar(i);h=X(D(0),r,s)}let u=C(0);if(e instanceof i.MeshStandardMaterial){const t=U("metalness",e.metalness??0),s=e.metalnessMap??je,i=U("useMetalnessMap",null!=e.metalnessMap?1:0),r=W(s).sample(n).b.multiply(t);u=X(t,r,i)}else e instanceof A&&e.outputRoughness;let c=null,p=C(1);if(e instanceof i.MeshStandardMaterial){const t=e.aoMap??We,s=U("useAoMap",null!=e.aoMap?1:0);p=U("aoMapIntensity",e.aoMapIntensity??1);const i=W(t).sample(n).r;c=X(C(1),i,s)}else e instanceof A&&e.outputRoughness;const f=U("opacity",e.opacity??1);let g=C(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.alphaMap??We,s=U("useAlphaMap",null!=e.alphaMap?1:0),i=W(t).sample(n).r;g=X(C(1),i,s),g=g.multiply(f)}else e instanceof A&&null!=e.outputOpacity&&(g=e.outputOpacity);let M=L(0,1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){const t=B("color",(new i.Vector3).setFromColor(e.color)),s=e.map??We,r=U("useAlbedoMap",null!=e.map?1:0),a=W(s).sample(n),o=a.multiply(L(t,1)),l=L(t,1);M=X(l,o,r);const h=X(C(1),a.w,r);g=g.multiply(h)}const v=!0===e.userData.hasBloom;let T=D(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=B("emissive",(new i.Vector3).setFromColor(e.emissive)),s=U("emissiveIntensity",e.emissiveIntensity),r=e.emissiveMap??je,a=U("useEmissiveMap",null!=e.emissiveMap?1:0),o=W(r).sample(n).rgb.multiply(t);T=X(t,o,a),T=T.multiplyScalar(s)}else e instanceof A&&null!=e.outputEmissive&&(T=e.outputEmissive);const x=e instanceof d&&null!=e.uniforms[se],P=e instanceof d&&null!=e.uniforms[ue],b=e instanceof d&&null!=e.uniforms[de],y=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,w=U("alphaTest",e.alphaTest);let j,G=e.alphaTest>0?g.lt(w):y&&t===Le.opaque?g.lt(.8):R(!1);!0===e.userData.isDecal&&(G=G.or(Be)),j=y?N(0,0,0,0):(a=o,O(a).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?l:1);const H=e instanceof A?e.outputPosition:void 0,$=e instanceof A?e.outputTransform:void 0;let Y,Q=L("black",1);if(e instanceof A&&null!=e.outputColor)Q=e.outputColor;else if(e instanceof i.MeshStandardMaterial)Q=F({color:M,metalness:u,roughness:l,emissive:T.rgb,normal:o,ambientOcclusion:c,ambientOcclusionIntensity:p,bakedLight:h});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)Q=E({color:M.rgb});else if(e instanceof i.MeshBasicMaterial){let e=M.rgb,t=h??D("white");null!=c&&(t=t.multiplyScalar(c.subtract(1).multiply(p).add(1))),e=e.multiply(t),Q=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(Q=I({color:M,emissive:T.rgb,normal:o,ambientOcclusion:c,ambientOcclusionIntensity:p,bakedLight:h}));(e instanceof A||e instanceof i.MeshStandardMaterial)&&(Y=e.envMap);let K=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(K=e.fog);let J=L(Q.rgb,g);K&&(J=new FogNode(J));let Z=!0;if(t===Le.opaque?(Z&&(Z=!x&&!P&&!b),Z&&(Z=!y)):t===Le.transparent&&Z&&(Z=y||x||P||b),!Z)return r=Ve,s.set(e,r),r;r=new A({transform:$,position:null==$?H:void 0,outputs:[J,T.rgba(t===Le.opaque?w:v?1:0),j],opacity:g,outputEncoding:!1,fog:K,transparent:e.transparent,lights:!0,envMap:Y,discard:G}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=r.uniforms.envMapIntensity&&(r.uniforms.envMapIntensity.value=e.envMapIntensity),(e instanceof A||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(r),e instanceof A&&Object.assign(r.defines,e.defines),r.userData.mrtOutputs=3,r.forceSinglePass=e.forceSinglePass,r.side=e.side,r.blending=e.blending,y?(r.depthWrite=!e.transparent,r.depthTest=e.depthTest,r.colorWrite=t===Le.transparent):(r.depthWrite=e.depthWrite,r.depthTest=e.depthTest),r.visible=e.visible,r.alphaTest=e.alphaTest,r.alphaHash=e.alphaHash,Object.assign(r.userData,e.userData),r.visible&&(this.csm.setupMaterial(r),e instanceof d&&Object.assign(r.uniforms,e.uniforms)),s.set(e,r)}var a;return r.visible&&e instanceof d&&this.updateUniformValues(e,r),r}loop(e,t=!1){const s=this.stats,r=s.addPanel(new Z.Panel("Calls","#83f","#002")),a=s.addPanel(new Z.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new pe(this.renderer.getContext()),s.addPanel(l)),this.showStats=t;let h=10,d=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout(()=>h=10,5e3)),r.update(e,h);const t=this.renderer.info.render.triangles;t>d&&(d=t,setTimeout(()=>d=1e3,5e3)),a.update(t,d)};performance.now();i.Ray.prototype.intersectTriangle;this.resizeRender();const c=[],p=[],m=[];let f=0;const g=new n,M=new n;let v=0;let T=this.paused;const x=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return setTimeout(()=>x(t),500),void(T=!0);this.renderer.clear(),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,s.begin(),this.showStats&&l?.startQuery(),this.ssrPass.gpuPanel=l;let a=(t*=.001)-f;if(f=t,T&&(a=.016,T=!1),g.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(ke),t-=ke;e(t)}else e(a);this.onLoopCallbacks.forEach(e=>e(a)),this.camera?.updateMatrixWorld(),M.copy(this.camera.matrixWorld),t-v>.08&&!M.equals(g)&&(this.renderer.shadowMap.needsUpdate=!0,v=t),this.csm.update();let n=!1;c.length=0,p.length=0,m.length=0;const h=He;Xe.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(Xe);let d=!1,P=!1,b=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Se&&(d=!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),null!=this.scene.environment&&function(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(n=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[se])&&isObjectInFrustum(e,h)?(this.initDepthUniform(e.material),P=!0):e instanceof Y&&(e.visible=!1,p.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[de]&&isObjectInFrustum(e,h)&&e.material instanceof A&&this.initAoUniform(e.material),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[ue]&&isObjectInFrustum(e,h)&&(m.push(e),e.material.uniforms[ue].value=this.sceneColorRenderTarget.texture,b=!0),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[he])e.material.uniforms[he].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const s of e.material)s.uniforms&&null!=s.uniforms[he]&&(s.uniforms[he].value=t)}),this.bloomPass.enabled=n,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderScene(Le.opaque),this.aoPass.output=ee.OUTPUT.Off,(P||b)&&(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)),m.length,c.forEach(e=>e.visible=!0),p.forEach(e=>e.visible=!0),m.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=t),this.volumetricFogPass&&d&&this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene);try{!this.paused&&this.running&&(this.render(a),this.showStats&&l?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}s.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout(()=>{requestAnimationFrame(x)},1e3/this.fpsCap):requestAnimationFrame(x))};!0===this.options.enableXR?this.renderer.setAnimationLoop(x):requestAnimationFrame(x)}applyGBufferMaterials(e){tt.clear(),st.length=0;ge(this.scene,t=>{if(it(t))return st.push(t),t.visible=!1,!1;if(t instanceof o){tt.set(t,t.material);let s=!1;if(Array.isArray(t.material)){t.material=t.material.slice();for(let i=0;i<t.material.length;i++)t.material[i]=this.createGBufferMaterial(t.material[i],e),s||(s=t.material[i].visible)}else t.material=this.createGBufferMaterial(t.material,e),s||(s=t.material.visible);s?t.visible=!0:null!=t.children&&0!=t.children.length||(st.push(t),t.visible=!1)}})}unapplyGBufferMaterials(){tt.forEach((e,t)=>{t.material=e}),st.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)})}async compileAsync(){this.compileInProgress||(this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0,this.applyGBufferMaterials(Le.opaque),await this.renderer.compileAsync(this.scene,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials(Le.transparent),await this.renderer.compileAsync(this.scene,this.camera),this.unapplyGBufferMaterials(),this.compileInProgress=!1,this.renderer.setRenderTarget(null))}renderScene(e){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!==Le.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===Le.opaque&&tt.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof d&&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,void(this.colorPass.enabled=!1);var e;(e=this.postProcessSettings).tonemapMapping=void 0,e.tonemapExposure=1,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=new i.Color("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.lut=void 0,e.lutIntensity=0;const t=this.postProcessSettings;let s,r=!1,a=!1,n=!1,o=!1;if(null==this.camera)return;const h=this.camera.getWorldPosition(Ye);let d=[];for(const e of this.postProcessVolumes){if(!ze(e.object))continue;let l=e.blendWeight??1;const u=e.distanceToPoint(h);u>e.blendRadius||(e.blendRadius>0&&(l*=Me(1-u/e.blendRadius,0,1)),l>1&&(l=1),l>0&&(d.push(e),void 0!==e.settings.tonemapMapping&&(t.tonemapMapping=e.settings.tonemapMapping),void 0!==e.settings.tonemapExposure&&(t.tonemapExposure=i.MathUtils.lerp(t.tonemapExposure,e.settings.tonemapExposure,l)),void 0!==e.settings.envTexture&&(t.envTexture=e.settings.envTexture),void 0!==e.settings.envIntensity&&(t.envIntensity=i.MathUtils.lerp(t.envIntensity,e.settings.envIntensity,l)),void 0!==e.settings.vignetteIntensity&&(t.vignetteIntensity=i.MathUtils.lerp(t.vignetteIntensity,e.settings.vignetteIntensity,l),a=!0),void 0!==e.settings.colorTint&&void 0!==e.settings.colorTintIntensity&&e.settings.colorTintIntensity>0&&(t.colorTint=t.colorTint.lerp(e.settings.colorTint,l),o=!0),void 0!==e.settings.colorTintIntensity&&(t.colorTintIntensity=i.MathUtils.lerp(t.colorTintIntensity,e.settings.colorTintIntensity,l)),void 0!==e.settings.depthFocus&&(r=!0,t.depthFocus=void 0!==t.depthFocus?i.MathUtils.lerp(t.depthFocus,e.settings.depthFocus,l):e.settings.depthFocus),void 0!==e.settings.depthAperture&&(r=!0,t.depthAperture=void 0!==t.depthAperture?i.MathUtils.lerp(t.depthAperture,e.settings.depthAperture,l):e.settings.depthAperture),void 0!==e.settings.depthMaxBlur&&(r=!0,t.depthMaxBlur=void 0!==t.depthMaxBlur?i.MathUtils.lerp(t.depthMaxBlur,e.settings.depthMaxBlur,l):e.settings.depthMaxBlur),void 0!==e.settings.temperature&&(t.temperature=i.MathUtils.lerp(t.temperature,e.settings.temperature,l)),void 0!==e.settings.temperatureTint&&(t.temperatureTint=i.MathUtils.lerp(t.temperatureTint,e.settings.temperatureTint,l)),void 0!==e.settings.lut&&(s=e.settings.lut,n=!0),void 0!==e.settings.lutIntensity&&(t.lutIntensity=i.MathUtils.lerp(t.lutIntensity,e.settings.lutIntensity,l),n=!0)))}this.renderer.toneMapping=t.tonemapMapping??i.NoToneMapping,this.renderer.toneMappingExposure=t.tonemapExposure,null!=t.envTexture&&(this.scene.environment=this.getEnvTexture(t.envTexture)),this.scene.environmentIntensity=t.envIntensity,this.colorPass.vignetteIntensity=t.vignetteIntensity,this.colorPass.vignetteEnabled=a,this.colorPass.colorTint=t.colorTint,this.colorPass.colorTintIntensity=t.colorTintIntensity,this.colorPass.enabled=a||o,r&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==t.depthFocus&&(this.dofPass.uniforms.focus.value=t.depthFocus),void 0!==t.depthAperture&&(this.dofPass.uniforms.aperture.value=t.depthAperture),void 0!==t.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=t.depthMaxBlur)):this.dofPass.enabled=!1,this.colorPass.temperature=t.temperature,this.colorPass.temperatureTint=t.temperatureTint,this.lutPass.enabled=n,n&&(null!=s&&(s.flipY=!0,s.generateMipmaps=!1),this.lutPass.lut=s,this.lutPass.intensity=t.lutIntensity)}renderOverlay(){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,He)&&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!=fe(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===Oe.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=Oe:(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)}initDepthUniform(e){e instanceof d&&(e.uniforms[se].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[re]&&(e.uniforms[re].value=this.camera.near),null!=e.uniforms[ie]&&(e.uniforms[ie].value=this.camera.far)))}initNormalUniform(e){e instanceof d&&null!=e.uniforms[ne]&&(e.uniforms[ne].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof A&&t.uniforms.receiveShadow&&(t.uniforms.receiveShadow.value=e.receiveShadow)}initResolutionUniform(e){e instanceof d&&null!=e.uniforms[ae]&&e.uniforms[ae].value.set(this.gRenderTarget.width,this.gRenderTarget.height)}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[de].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 A&&!t.transparent&&t.depthWrite){let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Re(we);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new A({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}}};qe=e=t([te(),s("design:paramtypes",[HTMLElement,Object])],qe);export{qe as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const ke=.05;function ze(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}ee.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 He=new i.Frustum,$e=new i.Box3,Xe=new i.Matrix4;export function isObjectInFrustum(e,t){const s=$e.setFromObject(e);return t.intersectsBox(s)}const Ye=new i.Vector3;const Qe=new n,Ke=new p;function Je(e,t,s=new i.Matrix3){return Ke.copy(e),Ke.x*=-1,Ke.y*=-1,Ke.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(Ke.y*=-1,Ke.z*=-1),s.setFromMatrix4(Qe.makeRotationFromEuler(Ke))}const Ze=new A({outputs:[N(0,0,0,0),N(0,0,0,0),L(D("white"),Ue(4))],transparent:!0}),et=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});Ze.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),et);const tt=new Map,st=[];function it(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isTransformControls||e.isTransformControlsGizmo||e instanceof o&&rt(e,e.material)}function rt(e,t){return null==t||(Array.isArray(t)?t.some(t=>rt(e,t)):t instanceof i.RawShaderMaterial||t instanceof i.ShaderMaterial&&!(t instanceof A))}class at extends Ie{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.needsSwap=!1}render(e,t,s,i,r){const a=e.autoClear;e.autoClear=!1;const n=this.scene.matrixWorldAutoUpdate,l=this.scene.matrixAutoUpdate,h=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const d=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),st.length=0;let u=0;this.scene.traverseVisible(e=>{const t=it(e);e instanceof o&&!t?(st.push(e),e.visible=!1):t&&u++}),u>0&&e.render(this.scene,this.camera),st.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=a,s.depthTexture=d,this.scene.matrixWorldAutoUpdate=n,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class nt extends Ie{constructor(e){super(),this.fn=e}render(e,t,s,i,r){this.fn(e,t,s,i,r)}}const ot=["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"],lt=B("fogColor");export class FogNode extends ${constructor(e,t=lt){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),r=e.get(this.fogColor),a=e.get(U("fogFar")),n=e.get(U("fogNear")),o=e.get(U("fogDensity")),l=e.get(G(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( ${n}, ${a}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${r}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}/*
|
|
1
|
+
var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as r,Material as a,Matrix4 as n,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as d,WebGLRenderTarget as u,Texture as c,Euler as p,MeshStandardMaterial as m}from"three";import{CopyShader as f,EffectComposer as g,FXAAShader as M,GammaCorrectionShader as v,LUTPass as T,RenderPass as y,ShaderPass as b,VRButton as w}from"three-stdlib";import{CSMShader as x,CSMUtil as P}from"./csm.js";import{bool as S,colorToNormal as R,float as C,NodeShaderMaterial as A,standardMaterial as U,uniformFloat as F,uniformVec3 as B,toonMaterial as O,lambertMaterial as I,normalize as E,rgb as D,rgba as L,textureSampler2d as W,transformed as j,varying as G,varyingAttributes as V,varyingTransformed as _,vec4 as N,BooleanExpression as k,select as q,ifDefApply as z,uniformSampler2d as H,RgbaNode as $,mix as X,vec3 as Y,Vec3ExpressionNode as Q}from"three-shader-graph";import{Reflector as K}from"three-stdlib";import{BokehPass as J,OutputPass as Z}from"three/examples/jsm/Addons.js";import{CSM as ee}from"three/examples/jsm/csm/CSM.js";import te from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as se}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as ie}from"typedi";import{depthUniformName as re,farUniformName as ae,nearUniformName as ne,resolutionUniformName as oe,sceneNormalUniformName as le,screenUV as he,supportsDepthTextureExtension as de}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as ue}from"./shader-nodes/time.js";import{aoMapUniformName as ce,sceneMapUniformName as pe}from"./shader-nodes/scene-sample.js";import{DepthPass as me}from"./utils/three/depth-pass.js";import{GPUStatsPanel as fe}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as ge}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as Me,traverseVisibleStop as ve}from"./utils/three/traverse.js";import{clamp as Te}from"./utils/math.js";import{ColorPass as ye}from"./rendering/color-pass.js";import{SSRPass as be}from"./rendering/ssr/SSRPass.js";import{SSRShader as we}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as xe}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as Pe}from"./rendering/outline-effect.js";import{UnrealBloomPass as Se}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as Re}from"./shader-nodes/depth.js";import{packDepthToRGBA as Ce}from"three-shader-graph";import{FogVolumeObject as Ae}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Ue}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Fe}from"./shader-nodes/pom.js";import{FullScreenQuad as Be}from"three-stdlib";import{edgeDepthEffect as Oe}from"./shader-nodes/effects";import{decalDiscard as Ie}from"./shader-nodes/decal.js";import{Pass as Ee}from"three/examples/jsm/Addons.js";P.patchSetupMaterial();const De=document.createElement("div");De.style.position="absolute",De.style.left="50%",De.style.top="50%",De.style.color="black",De.style.zIndex="999";(new i.Layers).set(9);const Le=new i.MeshBasicMaterial({color:"black"}),We=new i.MeshDepthMaterial;var je;We.depthPacking=i.RGBADepthPacking,We.blending=i.NoBlending,We.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(je||(je={}));const Ge=(()=>{const e=new Uint8Array([255,255,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ve=(()=>{const e=new Uint8Array([0,0,0,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),_e=(()=>{const e=new Uint8Array([128,128,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ne=new A({color:C(0),position:N(C(0))});Ne.visible=!1;const ke=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let qe=0,ze=e=class{setPaused(e){this.paused=e}resizeRender(){if(!this.running)return;const e=this.container.clientWidth,t=this.container.clientHeight;this.previousClientWith===e&&this.previousClientHeight===t||0!==e&&0!==t&&(this.previousClientWith=e,this.previousClientHeight=t,this.camera instanceof l&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(e,t),this.composer.setSize(e,t),this.dofPass.setSize(e*this.renderer.getPixelRatio(),t*this.renderer.getPixelRatio()),this.fxaaPass.setSize(e*this.renderer.getPixelRatio(),t*this.renderer.getPixelRatio()),this.fxaaPass.uniforms.resolution.value.set(1/(e*this.renderer.getPixelRatio()),1/(t*this.renderer.getPixelRatio())),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)}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)}constructor(t,s={}){this.container=t,this.options=s,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.postProcessVolumes=[],this.postProcessSettings={},this.csmUpdateInvervals=this.options.shadows?.cascadeUpdateIntervals,this._id=qe++,this.fquadCopy=new Be(new d(f)),this.fquadCopyOpaque=new Be(new A({outputs:[H("tSceneColor",new c).sample(V.uv),N(H("tDepthTexture",new i.DepthTexture(1,1)).sample(V.uv).r)]})),this.fquadBlendAO=(()=>{const e=N(1),t=new A({outputs:[H("tAO",new c).sample(he),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Be(t)})(),this.resolutionScale=1,this.maxPixelRatio=ke?1:window.devicePixelRatio,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 te,this._showStats=!0,this.gbufferMaterialCache=new Map,this.tbufferMaterialCache=new Map,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 r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,window.renderer=this.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(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(w.createButton(this.renderer));const a=new Pe(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=a,this.createGRenderTarget(),this.composer=new g(this.renderer),this.composer.setSize(t.clientWidth,t.clientHeight);var n=(t.clientWidth||1)/(t.clientHeight||1);const o=new i.PerspectiveCamera(45,n,.5,800);o.layers.enable(19),this.setCamera(o),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.renderer.gammaFactor=1.4,P.renderingView=this,this.isDepthTextureExtensionSupported=de(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container);const l=new i.Vector2(t.clientWidth,t.clientHeight),h=(new y(this.scene,this.camera),new b(f,"prevtexture"));h.enabled=!0,h.needsSwap=!0,h.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=h;const u=new Se(l,1.5,.4,.85);u.threshold=1,u.strength=.9,u.radius=.5,this.bloomPass=u;const p=new se(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});p.normalRenderTarget?.dispose(),p.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),p.output=se.OUTPUT.Off,p.enabled=!1,this.aoPass=p,this.fquadBlendAO.material.uniforms.tAO.value=p.pdRenderTarget.texture,we.fragmentShader=we.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const m=new be({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});m.output=be.OUTPUT.Default,m.blur=!0,m.fresnel=!1,m.distanceAttenuation=!0,m.maxDistance=50,m.selective=!0,m.bouncing=!1,m.opacity=.4,m.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=m,!1!==this.options.ao?.enabled&&this.composer.addPass(p);const x=new lt((e,t,s,i,r)=>{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(x);const S=new lt((e,t,s,i,r)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(je.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(S),this.composer.addPass(h),this.composer.addPass(m),this.phasedRenderPass=new ot(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(u),u.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new xe(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new J(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const R=new ye;this.composer.addPass(R),this.colorPass=R,R.vignetteEnabled=!1,this.outlinePass=new ge(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 C=new b(M);C.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(C),this.fxaaPass=C,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new b(v).clear=!1,this.fixStatsStyle(),this.lutPass=new T({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const U=new b(f,"prevtexture");U.enabled=!0,U.needsSwap=!1,U.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],U.renderToScreen=!0;const F=new Z;this.composer.addPass(F)}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.composer.passes.forEach(t=>{t instanceof y?t.camera=e:t instanceof ge?t.renderCamera=e:(t instanceof me||t instanceof se)&&(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 ee({maxFar:100,lightFar:250,lightMargin:20,cascades:ke?2:4,shadowMapSize:2048*(ke?.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 r=Math.max(1,Math.floor(t.clientWidth*s)),a=Math.max(1,Math.floor(t.clientHeight*s)),n=new i.WebGLRenderTarget(r,a);return n.texture.minFilter=i.NearestFilter,n.texture.magFilter=i.NearestFilter,n.texture.generateMipmaps=!1,n.stencilBuffer=!1,n.depthTexture=new i.DepthTexture(r,a),n.depthTexture.type=i.UnsignedShortType,n.depthTexture.minFilter=i.NearestFilter,n.depthTexture.magFilter=i.NearestFilter,n}static createAOMaskDepthRenderTarget(e,t){const s=Math.max(1,t.clientWidth*e.getPixelRatio()),r=Math.max(1,t.clientHeight*e.getPixelRatio()),a=new i.DepthTexture(s,r);a.type=i.UnsignedInt248Type,a.minFilter=i.NearestFilter,a.magFilter=i.NearestFilter;const n=new i.WebGLRenderTarget(s,r,{type:i.HalfFloatType,depthTexture:a});return n.texture.minFilter=i.NearestFilter,n.texture.magFilter=i.NearestFilter,n.texture.generateMipmaps=!1,n.stencilBuffer=!1,n}createSceneColorRenderTarget(e,t){const s=this.gRenderTarget.width,r=this.gRenderTarget.height,a=new i.WebGLRenderTarget(s,r,{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return a.texture.minFilter=i.LinearFilter,a.texture.magFilter=i.LinearFilter,a.texture.generateMipmaps=!1,a.textures[1].minFilter=i.NearestFilter,a.textures[1].magFilter=i.NearestFilter,a}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose();const t=Math.max(1,e.clientWidth*this.renderer.getPixelRatio()),s=Math.max(1,e.clientHeight*this.renderer.getPixelRatio()),r=new i.DepthTexture(t,s);r.type=i.UnsignedIntType,r.minFilter=i.NearestFilter,r.magFilter=i.NearestFilter,this.gRenderTarget=new u(t,s,{count:3,minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat,depthTexture:r}),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(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren(),this.volumetricFogPass.dispose(),P.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){if(null!=this.scene.environment&&(e instanceof A&&(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:et(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 A||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)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],r=s[e].value;null!=t&&t.value!==r&&"receiveShadow"!==e&&!1===ht.includes(e)&&(t.value=r)}}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of ht){const t=i[e],r=s[e];null!=r&&null!=t&&(t.value=r.value)}}createGBufferMaterial(e,t){const s=t===je.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let r=s.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==r){let n=V.uv;if(e instanceof Ue&&null!=e.heightMap){const t=F("heightScale",e.heightScale??1);n=Fe(n,W(e.heightMap),t)}let o=_.normal;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.normalMap??_e,s=F("useNormalMap",null!=e.normalMap?1:0),i=F("normalScale",e.normalScale?.x??1),r=R(W(t).sample(n),i);o=X(_.normal,r,s)}else e instanceof A&&null!=e.outputNormal&&(o=e.outputNormal);!0!==e.userData.disableAO&&(o=z("DOUBLE_SIDED",o,e=>q(new k("gl_FrontFacing"),e,e.multiplyScalar(-1))));let l=e.userData?.reflective?C(0):C(1);if(e instanceof i.MeshStandardMaterial){const t=F("roughness",e.roughness??1),s=e.roughnessMap??Ge,i=F("useRoughnessMap",null!=e.roughnessMap?1:0),r=W(s).sample(n).g.multiply(t);l=X(t,r,i)}else e instanceof A&&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){const t=e.lightMap??Ve,s=F("useLightMap",null!=e.lightMap?1:0),i=F("lightMapIntensity",e.lightMapIntensity??1),r=W(t).sample(n).rgb.multiplyScalar(i);h=X(D(0),r,s)}let u=C(0);if(e instanceof i.MeshStandardMaterial){const t=F("metalness",e.metalness??0),s=e.metalnessMap??Ve,i=F("useMetalnessMap",null!=e.metalnessMap?1:0),r=W(s).sample(n).b.multiply(t);u=X(t,r,i)}else e instanceof A&&e.outputRoughness;let c=null,p=C(1);if(e instanceof i.MeshStandardMaterial){const t=e.aoMap??Ge,s=F("useAoMap",null!=e.aoMap?1:0);p=F("aoMapIntensity",e.aoMapIntensity??1);const i=W(t).sample(n).r;c=X(C(1),i,s)}else e instanceof A&&e.outputRoughness;const f=F("opacity",e.opacity??1);let g=C(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.alphaMap??Ge,s=F("useAlphaMap",null!=e.alphaMap?1:0),i=W(t).sample(n).r;g=X(C(1),i,s),g=g.multiply(f)}else e instanceof A&&null!=e.outputOpacity&&(g=e.outputOpacity);let M=L(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=B("color",(new i.Vector3).setFromColor(e.color));if(e.vertexColors){const e=G(z("USE_COLOR",Y(1,1,1),e=>new Q("color")));t=t.multiply(e)}const s=e.map??Ge,r=F("useAlbedoMap",null!=e.map?1:0),a=W(s).sample(n),o=a.multiply(L(t,1)),l=L(t,1);M=X(l,o,r);const h=X(C(1),a.w,r);g=g.multiply(h)}const v=!0===e.userData.hasBloom;let T=D(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=B("emissive",(new i.Vector3).setFromColor(e.emissive)),s=F("emissiveIntensity",e.emissiveIntensity),r=e.emissiveMap??Ve,a=F("useEmissiveMap",null!=e.emissiveMap?1:0),o=W(r).sample(n).rgb.multiply(t);T=X(t,o,a),T=T.multiplyScalar(s)}else e instanceof A&&null!=e.outputEmissive&&(T=e.outputEmissive);const y=e instanceof d&&null!=e.uniforms[re],b=e instanceof d&&null!=e.uniforms[pe],w=e instanceof d&&null!=e.uniforms[ce],x=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,P=F("alphaTest",e.alphaTest);let j,H=e.alphaTest>0?g.lt(P):x&&t===je.opaque?g.lt(.8):S(!1);!0===e.userData.isDecal&&(H=H.or(Ie)),j=x?N(0,0,0,0):(a=o,E(a).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?l:1);const $=e instanceof A?e.outputPosition:void 0,K=e instanceof A?e.outputTransform:void 0;let J,Z=L("black",1);if(e instanceof A&&null!=e.outputColor)Z=e.outputColor;else if(e instanceof i.MeshStandardMaterial)Z=U({color:M,metalness:u,roughness:l,emissive:T.rgb,normal:o,ambientOcclusion:c,ambientOcclusionIntensity:p,bakedLight:h});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)Z=I({color:M.rgb});else if(e instanceof i.MeshBasicMaterial){let e=M.rgb,t=h??D("white");null!=c&&(t=t.multiplyScalar(c.subtract(1).multiply(p).add(1))),e=e.add(t),Z=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(Z=O({color:M,emissive:T.rgb,normal:o,ambientOcclusion:c,ambientOcclusionIntensity:p,bakedLight:h}));(e instanceof A||e instanceof i.MeshStandardMaterial)&&(J=e.envMap);let ee=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(ee=e.fog);let te=L(Z.rgb,g);ee&&(te=new FogNode(te));let se=!0;if(t===je.opaque?(se&&(se=!y&&!b&&!w),se&&(se=!x)):t===je.transparent&&se&&(se=x||y||b||w),!se)return r=Ne,s.set(e,r),r;r=new A({transform:K,position:null==K?$:void 0,outputs:[te,T.rgba(t===je.opaque?P:v?1:0),j],opacity:g,outputEncoding:!1,fog:ee,transparent:e.transparent,lights:!0,envMap:J,discard:H}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=r.uniforms.envMapIntensity&&(r.uniforms.envMapIntensity.value=e.envMapIntensity),(e instanceof A||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(r),e instanceof A&&Object.assign(r.defines,e.defines),r.userData.mrtOutputs=3,r.forceSinglePass=e.forceSinglePass,r.side=e.side,r.blending=e.blending,x?(r.depthWrite=!e.transparent,r.depthTest=e.depthTest,r.colorWrite=t===je.transparent):(r.depthWrite=e.depthWrite,r.depthTest=e.depthTest),r.visible=e.visible,r.alphaTest=e.alphaTest,r.alphaHash=e.alphaHash,r.vertexColors=e.vertexColors,r.premultipliedAlpha=e.premultipliedAlpha,r.toneMapped=e.toneMapped,r.blendAlpha=e.blendAlpha,r.blendColor=e.blendColor,r.polygonOffset=e.polygonOffset,r.polygonOffsetFactor=e.polygonOffsetFactor,r.polygonOffsetUnits=e.polygonOffsetUnits,r.blending=e.blending,r.userData.isGBufferMaterial=!0,r.visible=se,Object.assign(r.userData,e.userData),r.visible&&(this.csm.setupMaterial(r),e instanceof d&&Object.assign(r.uniforms,e.uniforms)),s.set(e,r)}var a;return r.visible&&e instanceof d&&this.updateUniformValues(e,r),r}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;if(t-this.csmCascadeLastUpdate[s]>=i&&this.csm.lights[s].shadow){this.csm.lights[s].shadow.needsUpdate=!0,this.csmCascadeLastUpdate[s]=t;break}}}this.csm.update()}loop(e,t=!1){const s=this.stats,r=s.addPanel(new te.Panel("Calls","#83f","#002")),a=s.addPanel(new te.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new fe(this.renderer.getContext()),s.addPanel(l)),this.showStats=t;let h=10,d=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout(()=>h=10,5e3)),r.update(e,h);const t=this.renderer.info.render.triangles;t>d&&(d=t,setTimeout(()=>d=1e3,5e3)),a.update(t,d)};performance.now();i.Ray.prototype.intersectTriangle;this.resizeRender();const c=[],p=[],m=[];let f=0;const g=new n,M=new n;let v=0;let T=this.paused;const y=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return setTimeout(()=>y(t),500),void(T=!0);this.renderer.clear(),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,s.begin(),this.showStats&&l?.startQuery(),this.ssrPass.gpuPanel=l;let a=(t*=.001)-f;if(f=t,T&&(a=.016,T=!1),g.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(He),t-=He;e(t)}else e(a);this.onLoopCallbacks.forEach(e=>e(a)),this.camera?.updateMatrixWorld(),M.copy(this.camera.matrixWorld),t-v>.08&&!M.equals(g)&&(this.renderer.shadowMap.needsUpdate=!0,v=t),this.updateCsm();let n=!1;c.length=0,p.length=0,m.length=0;const h=Xe;Qe.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(Qe);let d=!1,b=!1,w=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Ae&&(d=!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),null!=this.scene.environment&&function(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(n=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[re])&&isObjectInFrustum(e,h)?(this.initDepthUniform(e.material),b=!0):e instanceof K&&(e.visible=!1,p.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[ce]&&isObjectInFrustum(e,h)&&e.material instanceof A&&this.initAoUniform(e.material),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[pe]&&isObjectInFrustum(e,h)&&(m.push(e),e.material.uniforms[pe].value=this.sceneColorRenderTarget.texture,w=!0),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[ue])e.material.uniforms[ue].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const s of e.material)s.uniforms&&null!=s.uniforms[ue]&&(s.uniforms[ue].value=t)}),this.bloomPass.enabled=n,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderScene(je.opaque),this.aoPass.output=se.OUTPUT.Off,(b||w)&&(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)),m.length,c.forEach(e=>e.visible=!0),p.forEach(e=>e.visible=!0),m.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=t),this.volumetricFogPass&&d&&this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene);try{!this.paused&&this.running&&(this.render(a),this.showStats&&l?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}s.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout(()=>{requestAnimationFrame(y)},1e3/this.fpsCap):requestAnimationFrame(y))};!0===this.options.enableXR?this.renderer.setAnimationLoop(y):requestAnimationFrame(y)}applyGBufferMaterials(e){it.clear(),rt.length=0;ve(this.scene,t=>{if(at(t))return rt.push(t),t.visible=!1,!1;if(t instanceof o){it.set(t,t.material);let s=!1;if(Array.isArray(t.material)){t.material=t.material.slice();for(let i=0;i<t.material.length;i++)t.material[i]=this.createGBufferMaterial(t.material[i],e),s||(s=t.material[i].visible),this.initShadowUniform(t,t.material[i])}else t.material=this.createGBufferMaterial(t.material,e),s||(s=t.material.visible),this.initShadowUniform(t,t.material);s?t.visible=!0:null!=t.children&&0!=t.children.length||(rt.push(t),t.visible=!1)}})}unapplyGBufferMaterials(){it.forEach((e,t)=>{t.material=e}),rt.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)})}async compileAsync(){this.compileInProgress||(this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0,this.applyGBufferMaterials(je.opaque),await this.renderer.compileAsync(this.scene,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials(je.transparent),await this.renderer.compileAsync(this.scene,this.camera),this.unapplyGBufferMaterials(),this.compileInProgress=!1,this.renderer.setRenderTarget(null))}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!==je.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===je.opaque&&it.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof d&&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,void(this.colorPass.enabled=!1);var e;(e=this.postProcessSettings).tonemapMapping=void 0,e.tonemapExposure=1,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=new i.Color("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.lut=void 0,e.lutIntensity=0;const t=this.postProcessSettings;let s,r=!1,a=!1,n=!1,o=!1;if(null==this.camera)return;const h=this.camera.getWorldPosition(Ke);let d=[];for(const e of this.postProcessVolumes){if(!$e(e.object))continue;let l=e.blendWeight??1;const u=e.distanceToPoint(h);u>e.blendRadius||(e.blendRadius>0&&(l*=Te(1-u/e.blendRadius,0,1)),l>1&&(l=1),l>0&&(d.push(e),void 0!==e.settings.tonemapMapping&&(t.tonemapMapping=e.settings.tonemapMapping),void 0!==e.settings.tonemapExposure&&(t.tonemapExposure=i.MathUtils.lerp(t.tonemapExposure,e.settings.tonemapExposure,l)),void 0!==e.settings.envTexture&&(t.envTexture=e.settings.envTexture),void 0!==e.settings.envIntensity&&(t.envIntensity=i.MathUtils.lerp(t.envIntensity,e.settings.envIntensity,l)),void 0!==e.settings.vignetteIntensity&&(t.vignetteIntensity=i.MathUtils.lerp(t.vignetteIntensity,e.settings.vignetteIntensity,l),a=!0),void 0!==e.settings.colorTint&&void 0!==e.settings.colorTintIntensity&&e.settings.colorTintIntensity>0&&(t.colorTint=t.colorTint.lerp(e.settings.colorTint,l),o=!0),void 0!==e.settings.colorTintIntensity&&(t.colorTintIntensity=i.MathUtils.lerp(t.colorTintIntensity,e.settings.colorTintIntensity,l)),void 0!==e.settings.depthFocus&&(r=!0,t.depthFocus=void 0!==t.depthFocus?i.MathUtils.lerp(t.depthFocus,e.settings.depthFocus,l):e.settings.depthFocus),void 0!==e.settings.depthAperture&&(r=!0,t.depthAperture=void 0!==t.depthAperture?i.MathUtils.lerp(t.depthAperture,e.settings.depthAperture,l):e.settings.depthAperture),void 0!==e.settings.depthMaxBlur&&(r=!0,t.depthMaxBlur=void 0!==t.depthMaxBlur?i.MathUtils.lerp(t.depthMaxBlur,e.settings.depthMaxBlur,l):e.settings.depthMaxBlur),void 0!==e.settings.temperature&&(t.temperature=i.MathUtils.lerp(t.temperature,e.settings.temperature,l)),void 0!==e.settings.temperatureTint&&(t.temperatureTint=i.MathUtils.lerp(t.temperatureTint,e.settings.temperatureTint,l)),void 0!==e.settings.lut&&(s=e.settings.lut,n=!0),void 0!==e.settings.lutIntensity&&(t.lutIntensity=i.MathUtils.lerp(t.lutIntensity,e.settings.lutIntensity,l),n=!0)))}this.renderer.toneMapping=t.tonemapMapping??i.NoToneMapping,this.renderer.toneMappingExposure=t.tonemapExposure,null!=t.envTexture&&(this.scene.environment=this.getEnvTexture(t.envTexture)),this.scene.environmentIntensity=t.envIntensity,this.colorPass.vignetteIntensity=t.vignetteIntensity,this.colorPass.vignetteEnabled=a,this.colorPass.colorTint=t.colorTint,this.colorPass.colorTintIntensity=t.colorTintIntensity,this.colorPass.enabled=a||o,r&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==t.depthFocus&&(this.dofPass.uniforms.focus.value=t.depthFocus),void 0!==t.depthAperture&&(this.dofPass.uniforms.aperture.value=t.depthAperture),void 0!==t.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=t.depthMaxBlur)):this.dofPass.enabled=!1,this.colorPass.temperature=t.temperature,this.colorPass.temperatureTint=t.temperatureTint,this.lutPass.enabled=n,n&&(null!=s&&(s.flipY=!0,s.generateMipmaps=!1),this.lutPass.lut=s,this.lutPass.intensity=t.lutIntensity)}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(!this.running)return;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,Xe)&&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!=Me(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===Le.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=Le:(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)}initDepthUniform(e){e instanceof d&&(e.uniforms[re].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 d&&null!=e.uniforms[le]&&(e.uniforms[le].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){var s;t instanceof A&&(t.uniforms.receiveShadow?(s=t.uniforms.receiveShadow).value||(s.value=e.receiveShadow):t.uniforms.receiveShadow={value:e.receiveShadow})}initResolutionUniform(e){e instanceof d&&null!=e.uniforms[oe]&&e.uniforms[oe].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 A&&!t.transparent&&t.depthWrite){let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Ce(Re);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new A({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}}};ze=e=t([ie(),s("design:paramtypes",[HTMLElement,Object])],ze);export{ze as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const He=.05;function $e(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}se.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 Xe=new i.Frustum,Ye=new i.Box3,Qe=new i.Matrix4;export function isObjectInFrustum(e,t){const s=Ye.setFromObject(e);return t.intersectsBox(s)}const Ke=new i.Vector3;const Je=new n,Ze=new p;function et(e,t,s=new i.Matrix3){return Ze.copy(e),Ze.x*=-1,Ze.y*=-1,Ze.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(Ze.y*=-1,Ze.z*=-1),s.setFromMatrix4(Je.makeRotationFromEuler(Ze))}const tt=new A({outputs:[N(0,0,0,0),N(0,0,0,0),L(D("white"),Oe(4))],transparent:!0}),st=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});tt.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),st);const it=new Map,rt=[];function at(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isLineSegments2||e.isTransformControls||e.isTransformControlsGizmo||e instanceof o&&nt(e,e.material)}function nt(e,t){return null==t||(Array.isArray(t)?t.some(t=>nt(e,t)):t instanceof i.RawShaderMaterial||t instanceof i.ShaderMaterial&&!(t instanceof A))}class ot extends Ee{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.needsSwap=!1}render(e,t,s,i,r){const a=e.autoClear;e.autoClear=!1;const n=this.scene.matrixWorldAutoUpdate,l=this.scene.matrixAutoUpdate,h=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const d=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),rt.length=0;let u=0;this.scene.traverseVisible(e=>{const t=at(e);e instanceof o&&!t?(rt.push(e),e.visible=!1):t&&u++}),u>0&&e.render(this.scene,this.camera),rt.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=a,s.depthTexture=d,this.scene.matrixWorldAutoUpdate=n,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class lt extends Ee{constructor(e){super(),this.fn=e}render(e,t,s,i,r){this.fn(e,t,s,i,r)}}const ht=["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"],dt=B("fogColor");export class FogNode extends ${constructor(e,t=dt){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),r=e.get(this.fogColor),a=e.get(F("fogFar")),n=e.get(F("fogNear")),o=e.get(F("fogDensity")),l=e.get(G(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( ${n}, ${a}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${r}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{attributes as t,
|
|
1
|
+
import{attributes as t,clamp as r,dot as e,float as o,ifDefApply as i,normalize as m,pow as n,saturate as p,transformed as a,uniforms as c,varying as f,varyingAttributes as l,vec4 as s}from"three-shader-graph";import{fragmentLinearEyeDepth as u,linearEyeDepth as d}from"./depth.js";import{oneMinus as h}from"./math.js";c.modelMatrix.multiplyVec(s(t.position,1));export function fresnelEffect(t=1){const r=i("FLIP_SIDED",a.normal,()=>a.normal.multiplyScalar(-1));return n(h(p(e(a.viewDir,r))),o(t))}const D=o(1).subtract(r(d.subtract(u).divide(d),0,1));export function edgeDepthEffect(t=1){return n(D,o(t))}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|