@hology/core 0.0.187 → 0.0.188
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/components/character/character-movement.d.ts +2 -0
- package/dist/gameplay/actors/builtin/components/character/character-movement.js +1 -1
- package/dist/gameplay/actors/builtin/index.d.ts +3 -0
- package/dist/gameplay/actors/builtin/index.js +1 -1
- package/dist/gameplay/actors/camera/third-person-camera-component.d.ts +6 -0
- package/dist/gameplay/actors/camera/third-person-camera-component.js +1 -1
- package/dist/gameplay/services/render.js +1 -1
- package/dist/rendering/light-probes/light-probe-volume-actor.d.ts +14 -0
- package/dist/rendering/light-probes/light-probe-volume-actor.js +4 -0
- package/dist/rendering/light-probes/light-volume-capture.d.ts +16 -0
- package/dist/rendering/light-probes/light-volume-capture.js +4 -0
- package/dist/rendering.d.ts +5 -1
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model.d.ts +1 -1
- package/dist/scene/runtime-backend-service.js +1 -1
- package/dist/scene/storage/storage.d.ts +3 -2
- package/dist/scene/storage/storage.js +1 -1
- package/dist/shader/builtin/index.js +1 -1
- package/dist/shader/color-layer.d.ts +6 -1
- package/dist/shader/color-layer.js +1 -1
- package/dist/shader/shader.d.ts +1 -0
- package/dist/shader/sprite-shader.d.ts +13 -3
- package/dist/shader/sprite-shader.js +1 -1
- package/dist/shader-nodes/dither.d.ts +8 -0
- package/dist/shader-nodes/dither.js +4 -0
- package/dist/shader-nodes/index.d.ts +1 -0
- package/dist/shader-nodes/index.js +1 -1
- package/package.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -61,6 +61,8 @@ export declare class CharacterMovementComponent extends ActorComponent {
|
|
|
61
61
|
rotateToMovementDirection: boolean;
|
|
62
62
|
/** Makes the character rotate smoothly to the desired direction */
|
|
63
63
|
smoothRotation: boolean;
|
|
64
|
+
rotationSpeed: number;
|
|
65
|
+
maxRotationSpeed: number;
|
|
64
66
|
private impulse;
|
|
65
67
|
/**
|
|
66
68
|
* The damping factor used to slow down impulses over time
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as t,__metadata as e}from"tslib";import i from"@dimforge/rapier3d-compat";import{takeUntil as o}from"rxjs";import*as s from"three";import{ArrowHelper as n,MathUtils as r,Vector3 as a}from"three";import{RootMotionClip as c}from"../../../../../gameplay/animation/root-motion.js";import{ActionInput as
|
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import i from"@dimforge/rapier3d-compat";import{takeUntil as o}from"rxjs";import*as s from"three";import{ArrowHelper as n,MathUtils as r,Vector3 as a}from"three";import{RootMotionClip as c}from"../../../../../gameplay/animation/root-motion.js";import{ActionInput as h,AxisInput as l,RotationInput as p}from"../../../../../gameplay/input/index.js";import{PhysicsSystem as m,RayTestResult as u}from"../../../../../gameplay/services/physics/physics-system.js";import{CapsuleCollisionShape as d}from"../../../../../scene/collision/collision-shape.js";import{PhysicsBodyType as y}from"../../../../services/physics/physics-system.js";import{ActorComponent as g,Component as f}from"../../../component.js";import{CharacterMovementMode as S}from"./modes.js";import{inject as M}from"../../../../../gameplay/inject.js";const v=new a,w=new a,x=1/30,I=131070;let T=class extends g{get autoStepMinWidth(){return this.cc.autostepMinWidth()}set autoStepMinWidth(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),t,this.cc.autostepIncludesDynamicBodies())}get autoStepDynamicObjects(){return this.cc.autostepIncludesDynamicBodies()}set autoStepDynamicObjects(t){this.cc.enableAutostep(this.cc.autostepMaxHeight(),this.cc.autostepMinWidth(),t)}get autoStepMaxHeight(){return this.cc.autostepMaxHeight()}set autoStepMaxHeight(t){this.cc.enableAutostep(t,this.cc.autostepMinWidth(),this.cc.autostepIncludesDynamicBodies())}get snapToGround(){return this.cc.snapToGroundDistance()}set snapToGround(t){this.cc.enableSnapToGround(t)}set offset(t){this.cc.setOffset(t)}get offset(){return this.cc.offset()}set normalNudgeFactor(t){this.cc.setNormalNudgeFactor(t)}get normalNudgeFactor(){return this.cc.normalNudgeFactor()}constructor(){super(),this.directionInput=new l,this.jumpInput=new h,this.sprintInput=new h,this.rotationInput=new p,this.horizontalSpeed=0,this.maxSpeed=8,this.maxSpeedBackwards=8,this.maxSpeedSprint=12,this.jumpVelocity=7,this.fallingMovementControl=.5,this.fallingReorientation=!1,this.gravityOverride=null,this.colliderHeight=2,this.colliderRadius=.5,this.jumpInAir=!1,this.mass=50,this.allowSliding=!0,this.minSlopeSlideAngle=r.degToRad(70),this.maxSlopeClimbAngle=r.degToRad(70),this.applyImpulsesToDynamicBodies=!0,this.characterCollision=!1,this.enabled=!0,this.velocity=new a,this.mode=S.walking,this.isSprinting=!1,this.pressedJump=!1,this.rayTestResult=new u,this.physicsSystem=M(m),this.resetRootMotion=!1,this.rotateToMovementDirection=!1,this.smoothRotation=!0,this.rotationSpeed=20,this.maxRotationSpeed=32,this.impulse=new a,this.impulseDamping=2;const t=this.cc=this.physicsSystem.getCharacterController(.1);t.enableSnapToGround(.1),t.enableAutostep(0,.1,!1)}onInit(){const t=this.cc;t.setApplyImpulsesToDynamicBodies(this.applyImpulsesToDynamicBodies),t.setMinSlopeSlideAngle(this.minSlopeSlideAngle),t.setMaxSlopeClimbAngle(this.maxSlopeClimbAngle),t.setCharacterMass(this.mass),t.setSlideEnabled(this.allowSliding),this.physicsSystem.addActor(this.actor,[this.createCollisionShape()],{mass:0,type:y.kinematic,continousCollisionDetection:!1,friction:0,restitution:.5,ignoreForNavMesh:!0}),this.rotationInput.rotation.copy(this.actor.rotation);let e=this.rotationInput.rotation.y;const i=new a,n=new a,h=new a,l=new a,p=new a,m=new a,u=new a;let d=0,g=null;const f=new a,M=new a,T=new a,j=new a,R=new a,C=this.characterCollision?null:I;let D=this.rotateToMovementDirection;this.physicsSystem.beforeStep.pipe(o(this.disposed)).subscribe(o=>{if(this.checkGrounded(o),!this.enabled)return;if(null!=this.rootMotionAction){if(this.rootMotionAction.getClip()instanceof c){const t=this.rootMotionInterpolant;this.resetRootMotion&&(f.fromArray(t.evaluate(0)),this.resetRootMotion=!1),j.fromArray(t.evaluate(this.rootMotionAction.time)),M.subVectors(j,f),f.copy(j),this.rootMotionAction.getRoot().getWorldScale(T),M.multiply(T)}}o>x&&(o=x);const y=null!=this.rootMotionAction&&this.rootMotionAction.enabled&&0!=M.length();this.pressedJump=this.jumpInput.activated,this.isSprinting=this.sprintInput.activated;const I=D!==this.rotateToMovementDirection;let q=r.euclideanModulo(this.rotationInput.rotation.y-e+Math.PI,2*Math.PI)-Math.PI;I&&(this.actor.object.quaternion.setFromEuler(F.set(0,this.rotationInput.rotation.y,0)),D?this.actor.object.quaternion.setFromEuler(F.set(0,this.rotationInput.rotation.y,0)):(q=0,e=this.rotationInput.rotation.y),D=this.rotateToMovementDirection),h.copy(this.actor.position),l.set(-this.directionInput.vector.x,0,this.directionInput.vector.y).normalize();const H=!this.rotateToMovementDirection&&l.z<0?this.maxSpeedBackwards:this.isSprinting?this.maxSpeedSprint:this.maxSpeed;if(u.set(0,0,0),this.rotateToMovementDirection){if(l.lengthSq()>0&&this.mode!=S.falling){const t=this.smoothRotation,i=F.setFromQuaternion(this.actor.object.quaternion,"YXZ").y,s=Math.atan2(l.x,l.z),n=.99*this.rotationInput.rotation.y+s;if(t){const t=1+4*(1-r.clamp(.5*l.dot(p)+.5,.001,1)),e=r.euclideanModulo(n-i+Math.PI,2*Math.PI)-Math.PI,s=r.clamp(e*this.rotationSpeed*o*t,-this.maxRotationSpeed*o,this.maxRotationSpeed*o);this.actor.object.quaternion.setFromEuler(F.set(0,i+s,0))}else this.actor.object.quaternion.setFromEuler(F.set(0,n,0));p.lerp(l,o*this.rotationSpeed),e+=q,u.copy(this.actor.object.getWorldDirection(E).normalize())}}else e+=q,this.actor.object.quaternion.multiply(z.setFromEuler(F.set(0,q,0))),l.lengthSq()>0&&u.copy(l).applyQuaternion(this.actor.object.quaternion).normalize();if(R.set(0,0,0),this.rayTestResult.hasHit&&null!=this.rayTestResult.actor&&this.physicsSystem.getLinearVelocity(this.rayTestResult.actor,R),this.mode===S.walking?(0!==u.lengthSq()?(d=Math.min(H,d),d=r.lerp(d,H,4*o)):d=0,m.copy(u).multiplyScalar(d),this.pressedJump&&(this.mode=S.falling,this.velocity.copy(m),this.velocity.y=this.jumpVelocity),m.y=o*this.getEffectiveGravity(),m.add(R)):this.mode===S.falling&&(this.pressedJump&&this.jumpInAir&&(this.mode=S.falling,this.velocity.copy(m),this.velocity.y=this.jumpVelocity),this.velocity.y+=o*this.getEffectiveGravity(),m.copy(this.velocity),m.addScaledVector(u,this.fallingMovementControl),this.fallingReorientation&&m.applyAxisAngle(new a(0,1,0),q)),this.impulse.lengthSq()>.1){const t=Math.min(1,this.impulse.length()/5);m.x=r.lerp(m.x,this.impulse.x,t),m.z=r.lerp(m.z,this.impulse.z,t),m.y+=this.impulse.y;const e=Math.exp(-this.impulseDamping*o);this.impulse.x*=e,this.impulse.y>0?this.impulse.y+=o*this.getEffectiveGravity():this.impulse.y*=e,this.impulse.z*=e}else this.impulse.set(0,0,0);if(n.copy(m).normalize(),i.copy(m),m.length()>0||!this.isGrounded||y){if(y?(M.applyQuaternion(this.actor.quaternion),M.y+=o*this.getEffectiveGravity(),v.copy(M)):v.copy(m).multiplyScalar(o),this.isGrounded&&this.mode===S.walking&&(this.rayTestResult.distance>t.offset()||(v.y=Math.max(0,R.y*o)),this.physicsSystem.getActorComputedMovement(this.actor,t,v,C),t.computedCollision(0,G),null!=G&&null!=G.normal1)){const e=(new s.Vector3).copy(G.normal1);Math.acos(e.dot(b))>t.maxSlopeClimbAngle()&&(v.y=.016*this.getEffectiveGravity()*.5)}w.copy(this.physicsSystem.getActorComputedMovement(this.actor,t,v,C))}else w.set(0,0,0);this.physicsSystem.setNextKinematicTranslation(this.actor,w);let k=function(t){if(t.numComputedCollisions()>0){const e=t.computedCollision(0);A.x=e.normal2.x,A.y=e.normal2.y,A.z=e.normal2.z;const i=A.angleTo(b);A.x=e.normal1.x,A.y=e.normal1.y,A.z=e.normal1.z;const o=A.angleTo(b);return!(i<100)&&o>t.minSlopeSlideAngle()}return!1}(t);y||this.isGrounded&&!k||this.mode!==S.falling&&(null==g?g=performance.now():performance.now()-g>100&&(this.mode=S.falling,this.velocity.copy(i))),this.isGrounded&&this.velocity.y<=0&&(this.mode,S.falling,this.mode=S.walking,this.velocity.y=0,g=null),this.mode,S.walking,this.horizontalSpeed=d})}applyImpulse(t){this.impulse.add(t)}debugDirection(){const t=new n(v,this.actor.position,1,65280);this.actor.object.parent.add(t),setTimeout(()=>{t.removeFromParent()},30);const e=new n(w,this.actor.position,1,16711680);this.actor.object.parent.add(e),setTimeout(()=>{e.removeFromParent()},30)}setRootMotionAction(t){const e=t?.getClip();if(e instanceof c){this.rootMotionAction=t,this.resetRootMotion=!0;const i=[];this.rootMotionInterpolant=e.motionTrack.InterpolantFactoryMethodSmooth(i)}}getWallDirection(t,e){const i=t.clone().negate().cross(b);return i.dot(e)<0?i.negate():i}moveTo(t){this.actor.position.copy(t),this.physicsSystem.updateActorTransform(this.actor)}getEffectiveGravity(){return this.gravityOverride??this.physicsSystem.getGravity().y}checkGrounded(t){this.colliderHeight,this.colliderRadius;D.y=-.05,this.physicsSystem.rayTest(j.addVectors(this.actor.position,C.set(0,this.offset,0)),R.addVectors(this.actor.position,D),this.rayTestResult,{excludeActor:this.actor,excludeTriggers:!0})}get isGrounded(){return this.rayTestResult.hasHit||this.cc.computedGrounded()}createCollisionShape(){const t=new d(this.colliderHeight,this.colliderRadius);return t.offset.y=this.colliderRadius+this.colliderHeight/2+this.offset,t.collisionGroup=I,t}step(t){}performMovement(t){}arrowHelper(t,e,i){const o=new n(t.clone().normalize(),e,1,i);this.actor.object.parent.add(o),setTimeout(()=>{o.removeFromParent()},30)}};T=t([f({inEditor:!1}),e("design:paramtypes",[])],T);export{T as CharacterMovementComponent};const b=new a(0,1,0),A=new a;const j=new a,R=new a,C=new a(0,1,0),D=new a(0,-.1,0),G=(new a(0,-1,0),new i.CharacterCollision),z=new s.Quaternion,F=new s.Euler,E=new s.Vector3;/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -5,6 +5,7 @@ import { PositionalAudioActor } from './positional-audio-actor.js';
|
|
|
5
5
|
import { SpawnPoint } from './spawn-point.js';
|
|
6
6
|
import { TriggerVolume } from './trigger-volume.js';
|
|
7
7
|
import { FogVolume } from '../../../rendering/fog/fog-volume-actor.js';
|
|
8
|
+
import { LightProbeVolume } from '../../../rendering/light-probes/light-probe-volume-actor.js';
|
|
8
9
|
export declare const builtInActors: {
|
|
9
10
|
Camera: typeof CameraActor;
|
|
10
11
|
SpawnPoint: typeof SpawnPoint;
|
|
@@ -13,6 +14,8 @@ export declare const builtInActors: {
|
|
|
13
14
|
NavMesh: typeof NavMeshActor;
|
|
14
15
|
PostProcessVolume: typeof PostProcessVolume;
|
|
15
16
|
FogVolume: typeof FogVolume;
|
|
17
|
+
LightProbeVolume: typeof LightProbeVolume;
|
|
16
18
|
};
|
|
17
19
|
export default builtInActors;
|
|
20
|
+
export declare const experimentalActors: string[];
|
|
18
21
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{PostProcessVolume as o}from"./post-process-volume-actor.js";import{CameraActor as r}from"./camera-actor.js";import t from"./navmesh-actor.js";import{PositionalAudioActor as
|
|
1
|
+
import{PostProcessVolume as o}from"./post-process-volume-actor.js";import{CameraActor as r}from"./camera-actor.js";import t from"./navmesh-actor.js";import{PositionalAudioActor as e}from"./positional-audio-actor.js";import{SpawnPoint as m}from"./spawn-point.js";import{TriggerVolume as i}from"./trigger-volume.js";import{FogVolume as s}from"../../../rendering/fog/fog-volume-actor.js";import{LightProbeVolume as p}from"../../../rendering/light-probes/light-probe-volume-actor.js";export const builtInActors={Camera:r,SpawnPoint:m,TriggerVolume:i,PositionalAudio:e,NavMesh:t,PostProcessVolume:o,FogVolume:s,LightProbeVolume:p};export default builtInActors;export const experimentalActors=["LightProbeVolume"];/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -14,6 +14,8 @@ export declare class ThirdPersonCameraComponent extends ActorComponent {
|
|
|
14
14
|
viewAngle: number;
|
|
15
15
|
collision: boolean;
|
|
16
16
|
collisionSphereRadius: number;
|
|
17
|
+
smoothCamera: boolean;
|
|
18
|
+
smoothSpeed: number;
|
|
17
19
|
camera: PerspectiveCamera;
|
|
18
20
|
distance: number;
|
|
19
21
|
minDistance: number;
|
|
@@ -51,6 +53,10 @@ export declare class ThirdPersonCameraComponent extends ActorComponent {
|
|
|
51
53
|
private getLookAtPosition;
|
|
52
54
|
private updateCameraPosition;
|
|
53
55
|
private prevLookAt;
|
|
56
|
+
private smoothedLookAt;
|
|
57
|
+
private smoothedRotX;
|
|
58
|
+
private smoothedRotY;
|
|
59
|
+
private smoothZoom;
|
|
54
60
|
}
|
|
55
61
|
/** @deprecated Use ThirdPersonCameraComponent. No difference just renamed */
|
|
56
62
|
export declare class ThirdPartyCameraComponent extends ThirdPersonCameraComponent {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as t,__metadata as e}from"tslib";import{ActorComponent as
|
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import{ActorComponent as o,Component as i}from"../component.js";import{Vector3 as s,MathUtils as h,PerspectiveCamera as n,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 m}from"../../services/physics/physics-system.js";import{Parameter as p}from"../../../shader/parameter.js";import{World as l}from"../../services/world.js";import{inject as u}from"../../inject.js";import{ease as f}from"@hology/nebula";const v=void 0!==window&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let k=class extends o{constructor(){super(),this.viewController=u(a),this.physicsSystem=u(m),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.smoothCamera=!1,this.smoothSpeed=10,this.camera=new n(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 s,this.lookAtOffset=new s(this.offsetX,0,this.offsetZ),this.fixedBehind=!0,this.world=u(l),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 s,this.smoothedLookAt=new s,this.smoothedRotX=0,this.smoothedRotY=0,this.smoothZoom=0}async onInit(){this.prevFixedBehind=this.fixedBehind,this.world.scene.add(this.camera),this.rotationInput.rotation.copy(this.actor.rotation),this.smoothedRotX=this.rotationInput.rotation.x,this.smoothedRotY=this.rotationInput.rotation.y,this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.smoothZoom=this.zoomInput.value,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.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);let e=this.zoomInput.value,o=this.rotationInput.rotation.x,i=this.rotationInput.rotation.y;if(this.smoothCamera){const s=1-Math.exp(-this.smoothSpeed*t*2);this.smoothedRotX=h.lerp(this.smoothedRotX,o,s),this.smoothedRotY=h.lerp(this.smoothedRotY,i,s),o=this.smoothedRotX,i=this.smoothedRotY,this.smoothZoom=h.lerp(this.smoothZoom,e,.4*s),e=this.smoothZoom}else this.smoothedRotX=o,this.smoothedRotY=i;const s=h.clamp(Math.min(this.restrictedDistance,this.distance),Math.min(this.minDistance,this.restrictedDistance),Math.max(this.distance*e,this.minDistance)),n=Math.cos(o)*s,r=this.fixedBehind?0:i;this.offset.x=Math.sin(-r)*n,this.offset.y=Math.sin(o)*s+2,this.offset.z=Math.cos(-r)*-n,this.fixedBehind&&this.offset.add(this.lookAtOffset),this.updateCameraPosition(t)}checkForCollision(t){const e=this.getLookAtPosition(),o=this.camera.getWorldPosition(A),i=x.subVectors(o,e),s=i.length();if(s<.001)return;i.divideScalar(s);const n=this.physicsSystem.sphereCast(e,this.collisionSphereRadius,i,this.distance,void 0,{excludeActor:this.actor,excludeTriggers:!0,collisionFilter:-2});if(n.hasHit){const e=Math.max(this.minDistance,n.distance-.05);e<this.restrictedDistance?this.restrictedDistance=e:this.restrictedDistance=h.lerp(this.restrictedDistance,e,h.clamp(this.bounceBackSpeed*t,0,1))}else this.restrictedDistance=h.lerp(this.restrictedDistance,this.distance,h.clamp(this.bounceBackSpeed*t,0,1))}getLookAtPosition(){const t=L;return t.set(0,0,0),t.y=this.height,this.fixedBehind&&t.add(this.lookAtOffset),t.applyMatrix4(this.actor.object.matrixWorld),t}updateCameraPosition(t){this.actor.object.updateWorldMatrix(!0,!1),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 e=f.easeInOutCubic(1-this.blendDurationLeft);if(this.blendDurationLeft>0){const t=this.getLookAtPosition();this.prevLookAt.lerp(t,e),this.camera.lookAt(this.prevLookAt),this.camera.position.lerp(y.position,e),this.smoothedLookAt.copy(this.prevLookAt)}else{const e=this.getLookAtPosition();if(this.smoothCamera){const o=1-Math.exp(-this.smoothSpeed*t);this.smoothedLookAt.distanceToSquared(e)>1?this.smoothedLookAt.copy(e):this.smoothedLookAt.lerp(e,o)}else this.smoothedLookAt.copy(e);w.subVectors(y.position,e),this.camera.position.copy(this.smoothedLookAt).add(w),this.camera.lookAt(this.smoothedLookAt),this.prevLookAt.copy(this.smoothedLookAt)}}};t([p(),e("design:type",Number)],k.prototype,"near",void 0),t([p(),e("design:type",Number)],k.prototype,"far",void 0),t([p(),e("design:type",Number)],k.prototype,"viewAngle",void 0),t([p(),e("design:type",Boolean)],k.prototype,"collision",void 0),t([p(),e("design:type",Number)],k.prototype,"collisionSphereRadius",void 0),t([p(),e("design:type",Boolean)],k.prototype,"smoothCamera",void 0),t([p(),e("design:type",Number)],k.prototype,"smoothSpeed",void 0),k=t([i(),e("design:paramtypes",[])],k);export{k as ThirdPersonCameraComponent};const y=new r,L=new s,w=new s,x=new s,A=(new s,new s);export class ThirdPartyCameraComponent extends k{}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{Service as i}from"typedi";import{Camera as s}from"three";import{RenderingView as n}from"../../rendering.js";import{BehaviorSubject as r,Observable as o,Subject as a,takeUntil as h}from"rxjs";import*as u from"three";let d=class{constructor(e){this.view=e,this.tick=new a,this.lateTick=new a,this.audioListener=new u.AudioListener,this.pausedChanged=new r(!1),this.mutedChanged=new r(!1),this._muted=!1,this.activeTimers=new Map,this.nextTimerId=0,this.outlined=[],e.onLoop(e=>{this.tick.next(e),this.lateTick.next(e)}),e.camera.add(this.audioListener),window.hology_view=this}set fpsCap(e){this.view.fpsCap=e}get fpsCap(){return this.view.fpsCap}set showStats(e){this.view.showStats=e}get showStats(){return this.view.showStats}addPostProcessVolume(e){this.view.addPostProcessVolume(e)}removePostProcessVolume(e){this.view.removePostProcessVolume(e)}onUpdate(e){return null!=e&&this.tick.pipe(h(e.disposed)),this.tick}onLateUpdate(e){return null!=e&&this.lateTick.pipe(h(e.disposed)),this.lateTick}setCamera(e){const t=e instanceof s?e:e.camera.instance;this.view.setCamera(t),t.add(this.audioListener)}getCamera(){return this.view.camera}setMuted(e){this._muted=e,this.audioListener.gain.gain.setValueAtTime(e?0:1,this.audioListener.context.currentTime),this.mutedChanged.next(e)}getMuted(){return this._muted}setOutlined(e){this.outlined.length=0;const t=this.outlined;for(let i=0;i<e.length;i++)t[i]=e[i];this.view.setSelectedObjects(t),this.view.setEnableOutlines(e.length>0)}getOutlined(){return this.outlined}addOutlined(e){this.outlined.includes(e)||(this.outlined.push(e),this.view.setSelectedObjects(this.outlined),this.view.setEnableOutlines(!0))}removeOutlined(e){const t=this.outlined.indexOf(e);-1!==t&&(this.outlined.splice(t,1),this.view.setSelectedObjects(this.outlined))}setOutlineColor(e){this.view.outlinePass?.visibleEdgeColor.copy(e)}getOutlineColor(){return this.view.outlinePass?.visibleEdgeColor}setOutlineThickness(e){this.view.outlinePass.edgeThickness=e}getOutlineThickness(){return this.view.outlinePass.edgeThickness}get htmlElement(){return this.view.container}get paused(){return this.view.paused}set paused(e){e!=this.paused&&(e?this.pauseRendering():this.unpauseRendering())}pauseRendering(){this.view.paused=!0,this.pausedChanged.next(this.view.paused);for(const[e,t]of this.activeTimers){clearTimeout(t.timeoutId);const e=Date.now()-t.startTime;t.remainingMs=Math.max(0,t.remainingMs-e)}}unpauseRendering(){this.view.paused=!1,this.pausedChanged.next(this.view.paused);for(const[e,t]of this.activeTimers)t.remainingMs>0&&(t.timeoutId=setTimeout(()=>{t.subscriber.next(),t.subscriber.complete(),this.activeTimers.delete(e)},t.remainingMs),t.startTime=Date.now())}dispose(){this.view.running&&this.view.stop(),this.audioListener.removeFromParent(),this.tick.complete(),this.lateTick.complete(),this.paused=!0}createTimer(e){const t=this.nextTimerId++;return new o(i=>{const s=Date.now(),n=setTimeout(()=>{i.next(),i.complete(),this.activeTimers.delete(t)},e);return this.activeTimers.set(t,{timeoutId:n,remainingMs:e,startTime:s,subscriber:i}),()=>{clearTimeout(n),this.activeTimers.delete(t)}})}getScreenPosition(e,t=
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{Service as i}from"typedi";import{Camera as s}from"three";import{RenderingView as n}from"../../rendering.js";import{BehaviorSubject as r,Observable as o,Subject as a,takeUntil as h}from"rxjs";import*as u from"three";let d=class{constructor(e){this.view=e,this.tick=new a,this.lateTick=new a,this.audioListener=new u.AudioListener,this.pausedChanged=new r(!1),this.mutedChanged=new r(!1),this._muted=!1,this.activeTimers=new Map,this.nextTimerId=0,this.outlined=[],e.onLoop(e=>{this.tick.next(e),this.lateTick.next(e)}),e.camera.add(this.audioListener),window.hology_view=this}set fpsCap(e){this.view.fpsCap=e}get fpsCap(){return this.view.fpsCap}set showStats(e){this.view.showStats=e}get showStats(){return this.view.showStats}setLightVolume(e){this.view.lightVolume=e}getLightVolume(){return this.view.lightVolume}addPostProcessVolume(e){this.view.addPostProcessVolume(e)}removePostProcessVolume(e){this.view.removePostProcessVolume(e)}onUpdate(e){return null!=e&&this.tick.pipe(h(e.disposed)),this.tick}onLateUpdate(e){return null!=e&&this.lateTick.pipe(h(e.disposed)),this.lateTick}setCamera(e){const t=e instanceof s?e:e.camera.instance;this.view.setCamera(t),t.add(this.audioListener)}getCamera(){return this.view.camera}setMuted(e){this._muted=e,this.audioListener.gain.gain.setValueAtTime(e?0:1,this.audioListener.context.currentTime),this.mutedChanged.next(e)}getMuted(){return this._muted}setOutlined(e){this.outlined.length=0;const t=this.outlined;for(let i=0;i<e.length;i++)t[i]=e[i];this.view.setSelectedObjects(t),this.view.setEnableOutlines(e.length>0)}getOutlined(){return this.outlined}addOutlined(e){this.outlined.includes(e)||(this.outlined.push(e),this.view.setSelectedObjects(this.outlined),this.view.setEnableOutlines(!0))}removeOutlined(e){const t=this.outlined.indexOf(e);-1!==t&&(this.outlined.splice(t,1),this.view.setSelectedObjects(this.outlined))}setOutlineColor(e){this.view.outlinePass?.visibleEdgeColor.copy(e)}getOutlineColor(){return this.view.outlinePass?.visibleEdgeColor}setOutlineThickness(e){this.view.outlinePass.edgeThickness=e}getOutlineThickness(){return this.view.outlinePass.edgeThickness}get htmlElement(){return this.view.container}get paused(){return this.view.paused}set paused(e){e!=this.paused&&(e?this.pauseRendering():this.unpauseRendering())}pauseRendering(){this.view.paused=!0,this.pausedChanged.next(this.view.paused);for(const[e,t]of this.activeTimers){clearTimeout(t.timeoutId);const e=Date.now()-t.startTime;t.remainingMs=Math.max(0,t.remainingMs-e)}}unpauseRendering(){this.view.paused=!1,this.pausedChanged.next(this.view.paused);for(const[e,t]of this.activeTimers)t.remainingMs>0&&(t.timeoutId=setTimeout(()=>{t.subscriber.next(),t.subscriber.complete(),this.activeTimers.delete(e)},t.remainingMs),t.startTime=Date.now())}dispose(){this.view.running&&this.view.stop(),this.audioListener.removeFromParent(),this.tick.complete(),this.lateTick.complete(),this.paused=!0}createTimer(e){const t=this.nextTimerId++;return new o(i=>{const s=Date.now(),n=setTimeout(()=>{i.next(),i.complete(),this.activeTimers.delete(t)},e);return this.activeTimers.set(t,{timeoutId:n,remainingMs:e,startTime:s,subscriber:i}),()=>{clearTimeout(n),this.activeTimers.delete(t)}})}getScreenPosition(e,t=m){const i=this.getCamera();return l.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),i instanceof u.PerspectiveCamera&&(c.setFromProjectionMatrix(l),!c.containsPoint(e))?null:(t.copy(e),t.project(i),t.x=(t.x+1)/2*this.htmlElement.clientWidth,t.y=(1-t.y)/2*this.htmlElement.clientHeight,t)}};d=e([i(),t("design:paramtypes",[n])],d);export{d as ViewController};const l=new u.Matrix4,m=new u.Vector3,c=new u.Frustum;/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { BaseActor } from "../../gameplay/actors/actor.js";
|
|
2
|
+
import { Vector3 } from "three";
|
|
3
|
+
export declare class LightProbeVolume extends BaseActor {
|
|
4
|
+
gridResolution: Vector3;
|
|
5
|
+
gridSize: Vector3;
|
|
6
|
+
private world;
|
|
7
|
+
private view;
|
|
8
|
+
private removed;
|
|
9
|
+
private lightVolume;
|
|
10
|
+
onInit(): void;
|
|
11
|
+
bake(): Promise<void>;
|
|
12
|
+
onEndPlay(): void;
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=light-probe-volume-actor.d.ts.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{__decorate as e,__metadata as i}from"tslib";import{inject as t}from"../../gameplay/inject.js";import{Actor as o,BaseActor as r}from"../../gameplay/actors/actor.js";import{Vector3 as s}from"three";import{captureSHGrid as l}from"./light-volume-capture.js";import{Parameter as n,ViewController as m,World as h}from"../../gameplay/index.js";import{sleepDelay as d}from"../../utils/async.js";let g=class extends r{constructor(){super(...arguments),this.gridResolution=new s(8,3,8),this.gridSize=new s(30,2,30),this.world=t(h),this.view=t(m),this.removed=!1}onInit(){this.bake()}async bake(){if(await d(5e3),this.removed)return;const e=window.renderer;if(null==e)return void console.error("No renderer found for light volume capture");const i=this.position;i.y+=this.gridSize.y/2+.5,console.time("capture light volume");const t=await l({gridOrigin:i,gridResolution:this.gridResolution,gridSize:this.gridSize,renderer:e,scene:this.world.scene});console.timeEnd("capture light volume"),this.removed||(this.view.setLightVolume(t),this.lightVolume=t)}onEndPlay(){this.removed=!0,this.view.getLightVolume()===this.lightVolume&&(this.lightVolume?.shTexture.dispose(),this.view.setLightVolume(null))}};e([n(),i("design:type",Object)],g.prototype,"gridResolution",void 0),e([n(),i("design:type",Object)],g.prototype,"gridSize",void 0),g=e([o()],g);export{g as LightProbeVolume};/*
|
|
2
|
+
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
|
+
* See the LICENSE.md file for details.
|
|
4
|
+
*/
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Data3DTexture, Object3D, Vector3, WebGLRenderer } from "three";
|
|
2
|
+
export declare class LightVolume {
|
|
3
|
+
shTexture: Data3DTexture;
|
|
4
|
+
gridResolution: Vector3;
|
|
5
|
+
gridSize: Vector3;
|
|
6
|
+
gridOrigin: Vector3;
|
|
7
|
+
constructor(shTexture: Data3DTexture, gridResolution: Vector3, gridSize: Vector3, gridOrigin: Vector3);
|
|
8
|
+
}
|
|
9
|
+
export declare function captureSHGrid({ gridResolution, gridSize, gridOrigin, renderer, scene, }: {
|
|
10
|
+
gridResolution: Vector3;
|
|
11
|
+
gridSize: Vector3;
|
|
12
|
+
gridOrigin: Vector3;
|
|
13
|
+
renderer: WebGLRenderer;
|
|
14
|
+
scene: Object3D;
|
|
15
|
+
}): Promise<LightVolume>;
|
|
16
|
+
//# sourceMappingURL=light-volume-capture.d.ts.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{LightProbeGenerator as e,LightProbeHelper as t}from"three/examples/jsm/Addons.js";import{CubeCamera as r,Data3DTexture as o,DataUtils as n,HalfFloatType as i,LinearFilter as s,RGBAFormat as a,Vector3 as c,WebGLCubeRenderTarget as l}from"three";export class LightVolume{constructor(e,t,r,o){this.shTexture=e,this.gridResolution=t,this.gridSize=r,this.gridOrigin=o}}export async function captureSHGrid({gridResolution:g,gridSize:d,gridOrigin:p,renderer:m,scene:f}){const h=g.x*g.y*g.z,u=Array.from({length:9},()=>new Float32Array(4*h)),y=Array.from({length:8},()=>{const e=new l(8);return{target:e,camera:new r(.2,100,e)}}),x=[];let w=0;for(let e=0;e<g.z;e++)for(let t=0;t<g.y;t++)for(let r=0;r<g.x;r++){const o=new c(p.x+r/(g.x-1)*d.x,p.y+t/(g.y-1)*d.y,p.z+e/(g.z-1)*d.z);x.push({position:o,index:w}),w++}const z=y.map(async(r,o)=>{for(let n=o;n<x.length;n+=8){const{position:o,index:i}=x[n];r.camera.position.copy(o),r.camera.update(m,f);const s=await e.fromCubeRenderTarget(m,r.target),a=s.sh;for(let e=0;e<9;e++){const t=a.coefficients[e];u[e][4*i+0]=t.x,u[e][4*i+1]=t.y,u[e][4*i+2]=t.z,u[e][4*i+3]=1}s.position.copy(o.clone());const c=new t(s,.05);f.add(c)}});await Promise.all(z),y.forEach(e=>e.target.dispose());const A=new Uint16Array(9*h*4);for(let e=0;e<9;e++){const t=u[e],r=e*h*4;for(let e=0;e<t.length;e++)A[r+e]=n.toHalfFloat(t[e])}const F=new o(A,g.x,g.y,9*g.z);return F.format=a,F.type=i,F.minFilter=s,F.magFilter=s,F.unpackAlignment=1,F.needsUpdate=!0,console.log("Captured SH grid into a single packed texture:",F),new LightVolume(F,g,d,p)}/*
|
|
2
|
+
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
|
+
* See the LICENSE.md file for details.
|
|
4
|
+
*/
|
package/dist/rendering.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { CSM } from "three/examples/jsm/csm/CSM.js";
|
|
|
6
6
|
import { GTAOPass } from "three/examples/jsm/postprocessing/GTAOPass.js";
|
|
7
7
|
import { OutlinePass } from './utils/three/outline-pass.js';
|
|
8
8
|
import { type PostProcessSettings, type PostProcessVolume } from "./gameplay/actors/builtin/post-process-volume-actor.js";
|
|
9
|
+
import { LightVolume } from "./rendering/light-probes/light-volume-capture.js";
|
|
9
10
|
export type RenderingViewOptions = {
|
|
10
11
|
enableOutlines?: boolean;
|
|
11
12
|
enableXR?: boolean;
|
|
@@ -64,6 +65,8 @@ export declare class RenderingView {
|
|
|
64
65
|
private volumetricFogPass;
|
|
65
66
|
private fquadCopy;
|
|
66
67
|
private fquadCopyOpaque;
|
|
68
|
+
lightVolume: LightVolume;
|
|
69
|
+
lightProbeIntensity: number;
|
|
67
70
|
/**
|
|
68
71
|
* This should be used to multiply the AO with the opaque color.
|
|
69
72
|
*
|
|
@@ -99,7 +102,7 @@ export declare class RenderingView {
|
|
|
99
102
|
private createSceneColorRenderTarget;
|
|
100
103
|
private createGRenderTarget;
|
|
101
104
|
private setupEventListeners;
|
|
102
|
-
stop(): void;
|
|
105
|
+
stop(dispose?: boolean): void;
|
|
103
106
|
private onLoopCallbacks;
|
|
104
107
|
onLoop(onFrame: (deltaTime: number) => any): void;
|
|
105
108
|
removeOnLoop(onFrame: (deltaTime: number) => any): void;
|
|
@@ -170,6 +173,7 @@ export declare class RenderingView {
|
|
|
170
173
|
private initDepthUniform;
|
|
171
174
|
private initNormalUniform;
|
|
172
175
|
private initShadowUniform;
|
|
176
|
+
private initLightVolumeUniform;
|
|
173
177
|
private initResolutionUniform;
|
|
174
178
|
private initAoUniform;
|
|
175
179
|
private initCustomDepthMaterial;
|
package/dist/rendering.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as a,Material as r,Matrix4 as n,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as u,WebGLRenderTarget as d,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 x}from"three-stdlib";import{CSMShader as w,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 D,rgb as E,rgba as L,transformed as W,varying as j,varyingAttributes as _,varyingTransformed as G,vec4 as V,BooleanExpression as q,select as k,ifDefApply as N,uniformSampler2d as z,RgbaNode as H,mix as $,attributes 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{RectAreaLightUniformsLib as Z}from"three/examples/jsm/lights/RectAreaLightUniformsLib.js";import ee from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as te}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as se}from"typedi";import{depthUniformName as ie,farUniformName as ae,nearUniformName as re,resolutionUniformName as ne,sceneNormalUniformName as oe,screenUV as le,supportsDepthTextureExtension as he}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as ue}from"./shader-nodes/time.js";import{aoMapUniformName as de,sceneMapUniformName as ce}from"./shader-nodes/scene-sample.js";import{DepthPass as pe}from"./utils/three/depth-pass.js";import{GPUStatsPanel as me}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as fe}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as ge,traverseVisibleStop as Me}from"./utils/three/traverse.js";import{clamp as ve}from"./utils/math.js";import{ColorPass as Te}from"./rendering/color-pass.js";import{SSRPass as ye}from"./rendering/ssr/SSRPass.js";import{SSRShader as be}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as xe}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as we}from"./rendering/outline-effect.js";import{UnrealBloomPass as Pe}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as Se}from"./shader-nodes/depth.js";import{packDepthToRGBA as Re}from"three-shader-graph";import{FogVolumeObject as Ce}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Ae}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Ue}from"./shader-nodes/pom.js";import{FullScreenQuad as Fe}from"three-stdlib";import{edgeDepthEffect as Be}from"./shader-nodes/effects";import{decalDiscard as Oe}from"./shader-nodes/decal.js";import{Pass as Ie}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 Ee=new i.MeshBasicMaterial({color:"black"}),Le=new i.MeshDepthMaterial;var We;Le.depthPacking=i.RGBADepthPacking,Le.blending=i.NoBlending,Le.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(We||(We={}));const je=(()=>{const e=new Uint8Array([255,255,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),_e=(()=>{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:V(C(0))});Ve.visible=!1;const qe=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let ke=0,Ne=null;const ze=new Map;function He(){return null==Ne&&(Ne=new IntersectionObserver(e=>{for(const t of e)if(t.isIntersecting){const e=ze.get(t.target);e&&e()}},{threshold:0})),Ne}let $e=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=ke++,this.fquadCopy=new Fe(new u(f)),this.fquadCopyOpaque=new Fe(new A({outputs:[z("tSceneColor",new c).sample(_.uv),V(z("tDepthTexture",new i.DepthTexture(1,1)).sample(_.uv).r)]})),this.fquadBlendAO=(()=>{const e=V(1),t=new A({outputs:[z("tAO",new c).sample(le),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Fe(t)})(),this.resolutionScale=1,this.maxPixelRatio=qe?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 ee,this._showStats=!0,this.gbufferMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.gBufferCachedMaterials=new Map,this.gBufferCachedVisibility=[],this._initiatedMaterialTextures=new Set,this._initiatedTextures=new Set,this.compileInProgress=!1,this.pmremGeneratorResults=new WeakMap,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new a,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,Z.init(),window.renderer=this.renderer=window.renderer??new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}.bind(this.scene),this.renderer.setPixelRatio(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(x.createButton(this.renderer));const r=new we(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=r,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=he(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 d=new Pe(l,1.5,.4,.85);d.threshold=1,d.strength=.9,d.radius=.5,this.bloomPass=d;const p=new te(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});p.normalRenderTarget?.dispose(),p.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),p.output=te.OUTPUT.Off,p.enabled=!1,this.aoPass=p,this.fquadBlendAO.material.uniforms.tAO.value=p.pdRenderTarget.texture,be.fragmentShader=be.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const m=new ye({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=ye.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 w=new lt((e,t,s,i,a)=>{this.aoPass.enabled&&(this.initResolutionUniform(this.fquadBlendAO.material),this.renderer.setRenderTarget(this.gRenderTarget),this.fquadBlendAO.render(this.renderer),this.renderer.setRenderTarget(null))});this.composer.addPass(w);const S=new lt((e,t,s,i,a)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(We.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(d),d.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 Q(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const R=new Te;this.composer.addPass(R),this.colorPass=R,R.vignetteEnabled=!1,this.outlinePass=new fe(new i.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const 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 K;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 fe?t.renderCamera=e:(t instanceof pe||t instanceof te)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),this.phasedRenderPass&&(this.phasedRenderPass.camera=e),null==this.csm){if(this.csm=new J({maxFar:100,lightFar:250,lightMargin:20,cascades:qe?2:4,shadowMapSize:2048*(qe?.5:1),lightDirection:new i.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"}),null!=this.csmUpdateInvervals){this.csmCascadeLastUpdate=new Array(this.csm.lights.length).fill(0);for(const e of this.csm.lights)e.shadow.autoUpdate=!1}this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,h.lights_fragment_begin=w.lights_fragment_begin}else this.csm.camera=this.camera,this.camera;this.csm.updateFrustums()}setSelectedObjects(e){if(null==this.outlinePass)return;const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t,s){const a=Math.max(1,Math.floor(t.clientWidth*s)),r=Math.max(1,Math.floor(t.clientHeight*s)),n=new i.WebGLRenderTarget(a,r);return n.texture.minFilter=i.NearestFilter,n.texture.magFilter=i.NearestFilter,n.texture.generateMipmaps=!1,n.stencilBuffer=!1,n.depthTexture=new i.DepthTexture(a,r),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()),a=Math.max(1,t.clientHeight*e.getPixelRatio()),r=new i.DepthTexture(s,a);r.type=i.UnsignedInt248Type,r.minFilter=i.NearestFilter,r.magFilter=i.NearestFilter;const n=new i.WebGLRenderTarget(s,a,{type:i.HalfFloatType,depthTexture:r});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,a=this.gRenderTarget.height,r=new i.WebGLRenderTarget(s,a,{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return r.texture.minFilter=i.LinearFilter,r.texture.magFilter=i.LinearFilter,r.texture.generateMipmaps=!1,r.textures[1].minFilter=i.NearestFilter,r.textures[1].magFilter=i.NearestFilter,r}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()),a=new i.DepthTexture(t,s);a.type=i.UnsignedIntType,a.minFilter=i.NearestFilter,a.magFilter=i.NearestFilter,this.gRenderTarget=new d(t,s,{count:3,minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat,depthTexture:a}),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();He().unobserve(this.container),ze.delete(this.container),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:st(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)}updateMaterialProperties(e,t){(e instanceof i.MeshBasicMaterial||e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(t.uniforms.color.value.setFromColor(e.color),t.uniforms.opacity.value=e.opacity,t.uniforms.map.value=e.map,null!=t.uniforms.alphaMap&&(t.uniforms.alphaMap.value=e.alphaMap),null!=t.uniforms.lightMap&&(t.uniforms.lightMap.value=e.lightMap,t.uniforms.lightMapIntensity.value=e.lightMapIntensity),null!=t.uniforms.aoMap&&(t.uniforms.aoMap.value=e.aoMap,t.uniforms.aoMapIntensity.value=e.aoMapIntensity),null!=t.uniforms.alphaTest&&(t.uniforms.alphaTest.value=e.alphaTest)),(e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(t.uniforms.normalMap&&(t.uniforms.normalMap.value=e.normalMap,t.uniforms.normalScale.value=e.normalScale.x),t.uniforms.emissiveMap&&(t.uniforms.emissiveMap.value=e.emissiveMap,t.uniforms.emissive.value.setFromColor(e.emissive),t.uniforms.emissiveIntensity.value=e.emissiveIntensity)),e instanceof m&&(t.uniforms.roughnessMap.value=e.roughnessMap,t.uniforms.metalnessMap.value=e.metalnessMap,t.uniforms.roughness.value=e.roughness,t.uniforms.metalness.value=e.metalness),e instanceof Ae&&(t.uniforms.heightMap.value=e.heightMap,t.uniforms.heightScale.value=e.heightScale),this.updateMaterialCommonProperties(e,t)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],a=s[e].value;null!=t&&t.value!==a&&"receiveShadow"!==e&&!1===ht.includes(e)&&(t.value=a)}this.updateMaterialCommonProperties(e,t)}updateMaterialCommonProperties(e,t){t.alphaTest=e.alphaTest,t.side=e.side,t.depthWrite=e.depthWrite,t.depthTest=e.depthTest,t.blending=e.blending,t.colorWrite=e.colorWrite,t.premultipliedAlpha=e.premultipliedAlpha}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of ht){const t=i[e],a=s[e];null!=a&&null!=t&&(t.value=a.value)}}createGBufferMaterial(e,t){const s=t===We.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let a=s.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==a){let n=_.uv;if(e instanceof Ae&&null!=e.heightMap){const t=F("heightScale",e.heightScale??1);n=Ue(n,z("heightMap",e.heightMap),t)}let o=G.normal;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.normalMap??Ge,s=F("useNormalMap",null!=e.normalMap?1:0),i=F("normalScale",e.normalScale?.x??1),a=R(z("normalMap",t).sample(n),i);o=$(G.normal,a,s)}else e instanceof A&&null!=e.outputNormal&&(o=e.outputNormal);!0!==e.userData.disableAO&&(o=N("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=F("roughness",e.roughness??1),s=e.roughnessMap??je,i=F("useRoughnessMap",null!=e.roughnessMap?1:0),a=z("roughnessMap",s).sample(n).g.multiply(t);l=$(t,a,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)&&null!=e.lightMap){const t=e.lightMap,s=F("useLightMap",null!=e.lightMap?1:0),i=F("lightMapIntensity",e.lightMapIntensity??1),a=z("lightMap",t).sample(n).rgb.multiplyScalar(i);h=$(E(0),a,s)}let d=C(0);if(e instanceof i.MeshStandardMaterial){const t=F("metalness",e.metalness??0),s=e.metalnessMap??_e,i=F("useMetalnessMap",null!=e.metalnessMap?1:0),a=z("metalnessMap",s).sample(n).b.multiply(t);d=$(t,a,i)}else e instanceof A&&e.outputRoughness;let c=null,p=C(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){const t=e.aoMap??je,s=F("useAoMap",null!=e.aoMap?1:0);p=F("aoMapIntensity",e.aoMapIntensity??1);const i=z("aoMap",t).sample(n).r;c=$(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){if(null!=e.alphaMap){const t=e.alphaMap;g=z("alphaMap",t).sample(n).r}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));const s=e.map??je,a=F("useAlbedoMap",null!=e.map?1:0),r=z("map",s).sample(n),o=r.multiply(L(t,1)),l=L(t,1);M=$(l,o,a),e.vertexColors&&(M=M.multiply(V(j(X.color.rgb),1)));const h=$(C(1),r.w,a);g=g.multiply(h)}const v=!0===e.userData.hasBloom;let T=E(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),a=e.emissiveMap??_e,r=F("useEmissiveMap",null!=e.emissiveMap?1:0),o=z("emissiveMap",a).sample(n).rgb.multiply(t);T=$(t,o,r),T=T.multiplyScalar(s)}else e instanceof A&&null!=e.outputEmissive&&(T=e.outputEmissive);const y=e instanceof u&&null!=e.uniforms[ie],b=e instanceof u&&null!=e.uniforms[ce],x=e instanceof u&&null!=e.uniforms[de],w=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,P=F("alphaTest",e.alphaTest);let W,H=e.alphaTest>0?g.lt(P):w&&t===We.opaque?g.lt(.8):S(!1);!0===e.userData.isDecal&&(H=H.or(Oe)),W=w?V(0,0,0,0):(r=o,D(r).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?l:1);const Y=e instanceof A?e.outputPosition:void 0,Q=e instanceof A?e.outputTransform:void 0;let K,J=L("black",1);if(e instanceof A&&null!=e.outputColor)J=e.outputColor;else if(e instanceof i.MeshStandardMaterial)J=U({color:M,metalness:d,roughness:l,emissive:T.rgb,normal:o,ambientOcclusion:c,ambientOcclusionIntensity:p,bakedLight:h});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)J=I({color:M.rgb,ambientOcclusion:c,ambientOcclusionIntensity:p});else if(e instanceof i.MeshBasicMaterial){let e=M.rgb,t=h??E("black");null!=c&&(t=t.multiplyScalar(c.subtract(1).multiply(p).add(1))),e=e.add(t),J=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(J=O({color:M,emissive:T.rgb,normal:o,ambientOcclusion:c,ambientOcclusionIntensity:p,bakedLight:h}));(e instanceof A||e instanceof i.MeshStandardMaterial)&&(K=e.envMap);let Z=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(Z=e.fog);let ee=L(J.rgb,g);Z&&(ee=new FogNode(ee));let te=!0;if(t===We.opaque?(te&&(te=!y&&!b&&!x),te&&(te=!w)):t===We.transparent&&te&&(te=w||y||b||x),!te)return a=Ve,s.set(e,a),a;a=new A({transform:Q,position:null==Q?Y:void 0,outputs:[ee,T.rgba(t===We.opaque?P:v?1:0),W],opacity:g,outputEncoding:!1,fog:Z,transparent:e.transparent,lights:!0,envMap:K,discard:H}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=a.uniforms.envMapIntensity&&(a.uniforms.envMapIntensity.value=e.envMapIntensity),(e instanceof A||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(a),e instanceof A&&(Object.assign(a.defines,e.defines),null!=a.uniforms[de]&&(a.uniforms[de].value=this.aoPass.pdRenderTarget.texture,a.defines.USE_SSAO_MAP="")),a.userData.mrtOutputs=3,a.forceSinglePass=e.forceSinglePass,a.side=e.side,a.blending=e.blending,w?(a.depthWrite=!e.transparent,a.depthTest=e.depthTest,a.colorWrite=t===We.transparent):(a.depthWrite=e.depthWrite,a.depthTest=e.depthTest),a.visible=e.visible,a.alphaTest=e.alphaTest,a.alphaHash=e.alphaHash,a.vertexColors=e.vertexColors,a.premultipliedAlpha=e.premultipliedAlpha,a.toneMapped=e.toneMapped,a.blendAlpha=e.blendAlpha,a.blendColor=e.blendColor,a.polygonOffset=e.polygonOffset,a.polygonOffsetFactor=e.polygonOffsetFactor,a.polygonOffsetUnits=e.polygonOffsetUnits,a.blending=e.blending,a.userData.isGBufferMaterial=!0,a.visible=te,Object.assign(a.userData,e.userData),a.visible&&(this.csm.setupMaterial(a),e instanceof u&&Object.assign(a.uniforms,e.uniforms)),s.set(e,a)}var r;return a.visible&&(e instanceof u?this.updateUniformValues(e,a):this.updateMaterialProperties(e,a)),a}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,a=s.addPanel(new ee.Panel("Calls","#83f","#002")),r=s.addPanel(new ee.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new me(this.renderer.getContext()),s.addPanel(l)),this.showStats=t;let h=10,u=1e3;const d=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout(()=>h=10,5e3)),a.update(e,h);const t=this.renderer.info.render.triangles;t>u&&(u=t,setTimeout(()=>u=1e3,5e3)),r.update(t,u)};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,y=!1,b=0;const x=He();ze.set(this.container,()=>{y&&(y=!1,requestAnimationFrame(()=>w(b)))}),x.observe(this.container);const w=t=>{y=!1;const a=this.renderer.getContext();if(this.paused&&this.running&&a.drawingBufferHeight>1)return y=!0,b=t,setTimeout(()=>{y&&w(t)},500),void(T=!0);if(this.renderer.clear(),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.clear(),null===this.container.offsetParent)return y=!0,b=t,void setTimeout(()=>{y&&w(t)},500);this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),s.begin(),this.showStats&&l?.startQuery(),this.ssrPass.gpuPanel=l;let r=(t*=.001)-f;if(f=t,T&&(r=.016,T=!1),g.copy(this.camera.matrixWorld),r>1){let t=r;for(;t>.05;)e(Xe),t-=Xe;e(t)}else e(r);this.onLoopCallbacks.forEach(e=>e(r)),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=Qe;Je.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(Je);let u=!1,x=!1,P=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Ce&&(u=!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[ie])&&isObjectInFrustum(e,h)?(this.initDepthUniform(e.material),x=!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[ce]&&isObjectInFrustum(e,h)&&(m.push(e),e.material.uniforms[ce].value=this.sceneColorRenderTarget.texture,P=!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(We.opaque),this.aoPass.output=te.OUTPUT.Off,(x||P)&&(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&&u&&this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene);try{!this.paused&&this.running&&(this.render(r),this.showStats&&l?.endQuery(),this.showStats&&d(),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(w)},1e3/this.fpsCap):requestAnimationFrame(w))};!0===this.options.enableXR?this.renderer.setAnimationLoop(w):requestAnimationFrame(w)}applyGBufferMaterials(e){const t=this.gBufferCachedMaterials,s=this.gBufferCachedVisibility;t.clear(),s.length=0;Me(this.scene,i=>{if(rt(i))return s.push(i),i.visible=!1,!1;if(i instanceof o){t.set(i,i.material);let a=!1;if(Array.isArray(i.material)){i.material=i.material.slice();for(let t=0;t<i.material.length;t++)i.material[t]=this.createGBufferMaterial(i.material[t],e),a||(a=i.material[t].visible),this.initShadowUniform(i,i.material[t])}else i.material=this.createGBufferMaterial(i.material,e),a||(a=i.material.visible),this.initShadowUniform(i,i.material);a?i.visible=!0:null!=i.children&&0!=i.children.length||(s.push(i),i.visible=!1)}})}unapplyGBufferMaterials(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e}),this.gBufferCachedVisibility.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)})}initTextures(e=this.scene){e.traverse(e=>{if(e instanceof o)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++)this._initMaterialTextures(e.material[t]);else this._initMaterialTextures(e.material)})}_initMaterialTextures(e){if(!this._initiatedMaterialTextures.has(e))if(this._initiatedMaterialTextures.add(e),e instanceof u){for(const[t,s]of Object.entries(e.uniforms))if(s.value instanceof c){if(this._initiatedTextures.has(s.value))continue;this.renderer.initTexture(s.value),this._initiatedTextures.add(s.value)}}else for(const[t,s]of Object.entries(e))if(s instanceof c){if(this._initiatedTextures.has(s))continue;this.renderer.initTexture(s),this._initiatedTextures.add(s)}}async compileAsync(e=this.scene){if(this.compileInProgress)return;this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0,this.applyGBufferMaterials(We.opaque),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials(We.transparent),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),e===this.scene&&(this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.compileAsync(this.fquadBlendAO.mesh,this.fquadBlendAO.camera),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.compileAsync(this.fquadCopyOpaque.mesh,this.fquadCopyOpaque.camera));const t=this.csm.lights[0]?.shadow.camera;null!=t&&(this.applyDepthMaterial(),await this.renderer.compileAsync(e,t),this.unapplyDepthMaterial()),this.compileInProgress=!1,this.renderer.setRenderTarget(null)}applyDepthMaterial(){const e=this.gBufferCachedMaterials;e.clear(),this.scene.traverse(t=>{(t.isMesh||t.isPoints||t.isLine||t.isSprite)&&(this.initCustomDepthMaterial(t),e.set(t,t.material),t.castShadow?null!=t.customDepthMaterial?t.material=t.customDepthMaterial:t.material=dt:t.material=null)})}unapplyDepthMaterial(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e})}renderScene(e){if(!this.running||this.paused)return;if(this.compileInProgress)return void console.error("Compile in progress, skipping render");this.applyGBufferMaterials(e);const t=this.scene.matrixWorldAutoUpdate,s=this.scene.matrixAutoUpdate,i=this.renderer.shadowMap.autoUpdate;e!==We.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===We.opaque&&this.gBufferCachedMaterials.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof u&&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,a=!1,r=!1,n=!1,o=!1;if(null==this.camera)return;const h=this.camera.getWorldPosition(Ze);let u=[];for(const e of this.postProcessVolumes){if(!Ye(e.object))continue;let l=e.blendWeight??1;const d=e.distanceToPoint(h);d>e.blendRadius||(e.blendRadius>0&&(l*=ve(1-d/e.blendRadius,0,1)),l>1&&(l=1),l>0&&(u.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),r=!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&&(a=!0,t.depthFocus=void 0!==t.depthFocus?i.MathUtils.lerp(t.depthFocus,e.settings.depthFocus,l):e.settings.depthFocus),void 0!==e.settings.depthAperture&&(a=!0,t.depthAperture=void 0!==t.depthAperture?i.MathUtils.lerp(t.depthAperture,e.settings.depthAperture,l):e.settings.depthAperture),void 0!==e.settings.depthMaxBlur&&(a=!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=r,this.colorPass.colorTint=t.colorTint,this.colorPass.colorTintIntensity=t.colorTintIntensity,this.colorPass.enabled=r||o,a&&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||null===this.container.offsetParent)return;if(this.renderer.domElement.parentElement!==this.container&&(this.container.replaceChildren(this.renderer.domElement),this.resizeRender()),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,Qe)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.options.bloom,this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=ge(this.scene,e=>e instanceof o&&!0===e.material?.userData?.hasBloom)}darkenNonBloomed(e){if((e instanceof o||e instanceof i.Sprite||e instanceof i.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)){if(e.material?.id===Ee.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=Ee:(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 u&&(e.uniforms[ie].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[re]&&(e.uniforms[re].value=this.camera.near),null!=e.uniforms[ae]&&(e.uniforms[ae].value=this.camera.far)))}initNormalUniform(e){e instanceof u&&null!=e.uniforms[oe]&&(e.uniforms[oe].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 u&&null!=e.uniforms[ne]&&e.uniforms[ne].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(Se);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}}};$e=e=t([se(),s("design:paramtypes",[HTMLElement,Object])],$e);export{$e as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const Xe=.05;function Ye(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}te.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse(function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls||e.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};const Qe=new i.Frustum,Ke=new i.Box3,Je=new i.Matrix4;export function isObjectInFrustum(e,t){const s=Ke.setFromObject(e);return t.intersectsBox(s)}const Ze=new i.Vector3;const et=new n,tt=new p;function st(e,t,s=new i.Matrix3){return tt.copy(e),tt.x*=-1,tt.y*=-1,tt.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(tt.y*=-1,tt.z*=-1),s.setFromMatrix4(et.makeRotationFromEuler(tt))}const it=new A({outputs:[V(0,0,0,0),V(0,0,0,0),L(E("white"),Be(4))],transparent:!0}),at=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});it.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),at);function rt(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 Ie{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.cachedVisibility=[],this.toRender=[],this.needsSwap=!1}render(e,t,s,i,a){const r=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 u=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),this.cachedVisibility.length=0;let d=0,c=this.toRender;if(c.length=0,this.scene.traverseVisible(e=>{const t=rt(e);e instanceof o&&!t?(this.cachedVisibility.push(e),e.visible=!1):t&&(d++,c.push(e))}),d>0)for(const t of c)e.render(t,this.camera);this.cachedVisibility.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=r,s.depthTexture=u,this.scene.matrixWorldAutoUpdate=n,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class lt extends Ie{constructor(e){super(),this.fn=e}render(e,t,s,i,a){this.fn(e,t,s,i,a)}}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"],ut=B("fogColor");export class FogNode extends H{constructor(e,t=ut){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),a=e.get(this.fogColor),r=e.get(F("fogFar")),n=e.get(F("fogNear")),o=e.get(F("fogDensity")),l=e.get(j(W.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}, ${r}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${a}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}const dt=new i.MeshDepthMaterial({depthPacking:i.RGBADepthPacking});/*
|
|
1
|
+
var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as a,Material as r,Matrix4 as n,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as u,WebGLRenderTarget as d,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 x}from"three-stdlib";import{CSMShader as P,CSMUtil as w}from"./csm.js";import{colorToNormal as S,float as R,NodeShaderMaterial as C,standardMaterial as A,uniformFloat as U,uniformVec3 as F,toonMaterial as B,lambertMaterial as I,normalize as O,rgb as E,rgba as D,transformed as L,varying as V,varyingAttributes as _,varyingTransformed as j,vec4 as G,BooleanExpression as W,select as q,ifDefApply as k,uniformSampler2d as N,RgbaNode as H,mix as z,attributes as $}from"three-shader-graph";import{Reflector as X}from"three-stdlib";import{BokehPass as Y,OutputPass as Q}from"three/examples/jsm/Addons.js";import{CSM as K}from"three/examples/jsm/csm/CSM.js";import{RectAreaLightUniformsLib as J}from"three/examples/jsm/lights/RectAreaLightUniformsLib.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 ae,resolutionUniformName as re,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 ue,sceneMapUniformName as de}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 ye}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as be}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as xe}from"./rendering/outline-effect.js";import{UnrealBloomPass as Pe}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as we}from"./shader-nodes/depth.js";import{packDepthToRGBA as Se}from"three-shader-graph";import{FogVolumeObject as Re}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 Ue}from"three-stdlib";import{edgeDepthEffect as Fe}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 Oe=document.createElement("div");Oe.style.position="absolute",Oe.style.left="50%",Oe.style.top="50%",Oe.style.color="black",Oe.style.zIndex="999";(new i.Layers).set(9);const Ee=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 Ve=(()=>{const e=new Uint8Array([255,255,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),_e=(()=>{const e=new Uint8Array([0,0,0,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),je=(()=>{const e=new Uint8Array([128,128,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Ge=new C({color:R(0),position:G(R(0))});Ge.visible=!1;const We=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let qe=0,ke=null;const Ne=new Map;function He(){return null==ke&&(ke=new IntersectionObserver(e=>{for(const t of e)if(t.isIntersecting){const e=Ne.get(t.target);e&&e()}},{threshold:0})),ke}let 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 Ue(new u(f)),this.fquadCopyOpaque=new Ue(new C({outputs:[N("tSceneColor",new c).sample(_.uv),G(N("tDepthTexture",new i.DepthTexture(1,1)).sample(_.uv).r)]})),this.lightProbeIntensity=2,this.fquadBlendAO=(()=>{const e=G(1),t=new C({outputs:[N("tAO",new c).sample(oe),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Ue(t)})(),this.resolutionScale=1,this.maxPixelRatio=We?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.gBufferCachedMaterials=new Map,this.gBufferCachedVisibility=[],this._initiatedMaterialTextures=new Set,this._initiatedTextures=new Set,this.compileInProgress=!1,this.pmremGeneratorResults=new WeakMap,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new a,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,J.init(),window.renderer=this.renderer=window.renderer??new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}.bind(this.scene),this.renderer.setPixelRatio(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(x.createButton(this.renderer));const r=new xe(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=r,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 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 d=new Pe(l,1.5,.4,.85);d.threshold=1,d.strength=.9,d.radius=.5,this.bloomPass=d;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,ye.fragmentShader=ye.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 P=new ot((e,t,s,i,a)=>{this.aoPass.enabled&&(this.initResolutionUniform(this.fquadBlendAO.material),this.renderer.setRenderTarget(this.gRenderTarget),this.fquadBlendAO.render(this.renderer),this.renderer.setRenderTarget(null))});this.composer.addPass(P);const S=new ot((e,t,s,i,a)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(Le.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(S),this.composer.addPass(h),this.composer.addPass(m),this.phasedRenderPass=new nt(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(d),d.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new be(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new Y(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const R=new ve;this.composer.addPass(R),this.colorPass=R,R.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 A=new b(M);A.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(A),this.fxaaPass=A,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 Q;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 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){if(this.csm=new K({maxFar:100,lightFar:250,lightMargin:20,cascades:We?2:4,shadowMapSize:2048*(We?.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=P.lights_fragment_begin}else this.csm.camera=this.camera,this.camera;this.csm.updateFrustums()}setSelectedObjects(e){if(null==this.outlinePass)return;const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t,s){const a=Math.max(1,Math.floor(t.clientWidth*s)),r=Math.max(1,Math.floor(t.clientHeight*s)),n=new i.WebGLRenderTarget(a,r);return n.texture.minFilter=i.NearestFilter,n.texture.magFilter=i.NearestFilter,n.texture.generateMipmaps=!1,n.stencilBuffer=!1,n.depthTexture=new i.DepthTexture(a,r),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()),a=Math.max(1,t.clientHeight*e.getPixelRatio()),r=new i.DepthTexture(s,a);r.type=i.UnsignedInt248Type,r.minFilter=i.NearestFilter,r.magFilter=i.NearestFilter;const n=new i.WebGLRenderTarget(s,a,{type:i.HalfFloatType,depthTexture:r});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,a=this.gRenderTarget.height,r=new i.WebGLRenderTarget(s,a,{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return r.texture.minFilter=i.LinearFilter,r.texture.magFilter=i.LinearFilter,r.texture.generateMipmaps=!1,r.textures[1].minFilter=i.NearestFilter,r.textures[1].magFilter=i.NearestFilter,r}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()),a=new i.DepthTexture(t,s);a.type=i.UnsignedIntType,a.minFilter=i.NearestFilter,a.magFilter=i.NearestFilter,this.gRenderTarget=new d(t,s,{count:3,minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat,depthTexture:a}),this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(e=!0){this.running=!1,this.lightVolume?.shTexture.dispose(),window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],e&&this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren();He().unobserve(this.container),Ne.delete(this.container),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 C&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0,e.uniforms.envMapRotation={value:tt(this.scene.environmentRotation,this.scene.environment,new i.Matrix3)}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment),e instanceof C||e instanceof i.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateMaterialProperties(e,t){(e instanceof i.MeshBasicMaterial||e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(t.uniforms.color.value.setFromColor(e.color),t.uniforms.opacity.value=e.opacity,t.uniforms.map.value=e.map,null!=t.uniforms.alphaMap&&(t.uniforms.alphaMap.value=e.alphaMap),null!=t.uniforms.lightMap&&(t.uniforms.lightMap.value=e.lightMap,t.uniforms.lightMapIntensity.value=e.lightMapIntensity),null!=t.uniforms.aoMap&&(t.uniforms.aoMap.value=e.aoMap,t.uniforms.aoMapIntensity.value=e.aoMapIntensity),null!=t.uniforms.alphaTest&&(t.uniforms.alphaTest.value=e.alphaTest)),(e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(t.uniforms.normalMap&&(t.uniforms.normalMap.value=e.normalMap,t.uniforms.normalScale.value=e.normalScale.x),t.uniforms.emissiveMap&&(t.uniforms.emissiveMap.value=e.emissiveMap,t.uniforms.emissive.value.setFromColor(e.emissive),t.uniforms.emissiveIntensity.value=e.emissiveIntensity)),e instanceof m&&(t.uniforms.roughnessMap.value=e.roughnessMap,t.uniforms.metalnessMap.value=e.metalnessMap,t.uniforms.roughness.value=e.roughness,t.uniforms.metalness.value=e.metalness),e instanceof Ce&&(t.uniforms.heightMap.value=e.heightMap,t.uniforms.heightScale.value=e.heightScale),this.updateMaterialCommonProperties(e,t)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],a=s[e].value;null!=t&&t.value!==a&&"receiveShadow"!==e&&!1===lt.includes(e)&&(t.value=a)}this.updateMaterialCommonProperties(e,t)}updateMaterialCommonProperties(e,t){t.alphaTest=e.alphaTest,t.side=e.side,t.depthTest=e.depthTest,t.blending=e.blending,t.colorWrite=e.colorWrite,t.premultipliedAlpha=e.premultipliedAlpha}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of lt){const t=i[e],a=s[e];null!=a&&null!=t&&(t.value=a.value)}}createGBufferMaterial(e,t){const s=t===Le.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let a=s.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==a){let n=_.uv;if(e instanceof Ce&&null!=e.heightMap){const t=U("heightScale",e.heightScale??1);n=Ae(n,N("heightMap",e.heightMap),t)}let o=j.normal;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.normalMap??je,s=U("useNormalMap",null!=e.normalMap?1:0),i=U("normalScale",e.normalScale?.x??1),a=S(N("normalMap",t).sample(n),i);o=z(j.normal,a,s)}else e instanceof C&&null!=e.outputNormal&&(o=e.outputNormal);!0!==e.userData.disableAO&&(o=k("DOUBLE_SIDED",o,e=>q(new W("gl_FrontFacing"),e,e.multiplyScalar(-1))));let l=e.userData?.reflective?R(0):R(1);if(e instanceof i.MeshStandardMaterial){const t=U("roughness",e.roughness??1),s=e.roughnessMap??Ve,i=U("useRoughnessMap",null!=e.roughnessMap?1:0),a=N("roughnessMap",s).sample(n).g.multiply(t);l=z(t,a,i)}else e instanceof C&&null!=e.outputRoughness&&(l=e.outputRoughness);let h=null;if((e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial)&&null!=e.lightMap){const t=e.lightMap,s=U("useLightMap",null!=e.lightMap?1:0),i=U("lightMapIntensity",e.lightMapIntensity??1),a=N("lightMap",t).sample(n).rgb.multiplyScalar(i);h=z(E(0),a,s)}let d=R(0);if(e instanceof i.MeshStandardMaterial){const t=U("metalness",e.metalness??0),s=e.metalnessMap??_e,i=U("useMetalnessMap",null!=e.metalnessMap?1:0),a=N("metalnessMap",s).sample(n).b.multiply(t);d=z(t,a,i)}else e instanceof C&&e.outputRoughness;let c=null,p=R(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){const t=e.aoMap??Ve,s=U("useAoMap",null!=e.aoMap?1:0);p=U("aoMapIntensity",e.aoMapIntensity??1);const i=N("aoMap",t).sample(n).r;c=z(R(1),i,s)}else e instanceof C&&e.outputRoughness;const f=U("opacity",e.opacity??1);let g=R(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){if(null!=e.alphaMap){const t=e.alphaMap;g=N("alphaMap",t).sample(n).r}g=g.multiply(f)}else e instanceof C&&null!=e.outputOpacity&&(g=e.outputOpacity);let M=D(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=F("color",(new i.Vector3).setFromColor(e.color));const s=e.map??Ve,a=U("useAlbedoMap",null!=e.map?1:0),r=N("map",s).sample(n),o=r.multiply(D(t,1)),l=D(t,1);M=z(l,o,a),e.vertexColors&&(M=M.multiply(G(V($.color.rgb),1)));const h=z(R(1),r.w,a);g=g.multiply(h)}const v=!0===e.userData.hasBloom;let T=E(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=F("emissive",(new i.Vector3).setFromColor(e.emissive)),s=U("emissiveIntensity",e.emissiveIntensity),a=e.emissiveMap??_e,r=U("useEmissiveMap",null!=e.emissiveMap?1:0),o=N("emissiveMap",a).sample(n).rgb.multiply(t);T=z(t,o,r),T=T.multiplyScalar(s)}else e instanceof C&&null!=e.outputEmissive&&(T=e.outputEmissive);const y=e instanceof u&&null!=e.uniforms[se],b=e instanceof u&&null!=e.uniforms[de],x=e instanceof u&&null!=e.uniforms[ue],P=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,w=U("alphaTest",e.alphaTest);let L,H=e.alphaTest>0?g.lt(w):P&&t===Le.opaque?g.lt(.8):null;!0===e.userData.isDecal&&(H=H?H.or(Be):Be),L=P?G(0,0,0,0):(r=o,O(r).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?l:1);const X=e instanceof C?e.outputPosition:void 0,Y=e instanceof C?e.outputTransform:void 0;let Q,K=D("black",1);if(e instanceof C&&null!=e.outputColor)K=e.outputColor;else if(e instanceof i.MeshStandardMaterial)K=A({color:M,metalness:d,roughness:l,emissive:T.rgb,normal:o,ambientOcclusion:c,ambientOcclusionIntensity:p,bakedLight:h});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)K=I({color:M.rgb,ambientOcclusion:c,ambientOcclusionIntensity:p});else if(e instanceof i.MeshBasicMaterial){let e=M.rgb,t=h??E("black");null!=c&&(t=t.multiplyScalar(c.subtract(1).multiply(p).add(1))),e=e.add(t),K=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(K=B({color:M,emissive:T.rgb,normal:o,ambientOcclusion:c,ambientOcclusionIntensity:p,bakedLight:h}));(e instanceof C||e instanceof i.MeshStandardMaterial)&&(Q=e.envMap);let J=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(J=e.fog);let Z=D(K.rgb,g);J&&(Z=new FogNode(Z));let ee=!0;if(t===Le.opaque?(ee&&(ee=!y&&!b&&!x),ee&&(ee=!P)):t===Le.transparent&&ee&&(ee=P||y||b||x),!ee)return a=Ge,s.set(e,a),a;a=new C({transform:Y,position:null==Y?X:void 0,outputs:[Z,T.rgba(t===Le.opaque?w:v?1:0),L],opacity:g,outputEncoding:!1,fog:J,transparent:e.transparent,lights:!0,envMap:Q,discard:H}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=a.uniforms.envMapIntensity&&(a.uniforms.envMapIntensity.value=e.envMapIntensity),"alphaMap"in e&&null!=e.alphaMap&&(a.alphaMap=e.alphaMap),(e instanceof C||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(a),e instanceof C&&(Object.assign(a.defines,e.defines),null!=a.uniforms[ue]&&(a.uniforms[ue].value=this.aoPass.pdRenderTarget.texture,a.defines.USE_SSAO_MAP="")),a.userData.mrtOutputs=3,a.forceSinglePass=e.forceSinglePass,a.side=e.side,a.blending=e.blending,P?(a.depthWrite=!e.transparent,a.depthTest=e.depthTest,a.colorWrite=t===Le.transparent):(a.depthWrite=e.depthWrite,a.depthTest=e.depthTest),a.visible=e.visible,a.alphaTest=e.alphaTest,a.alphaHash=e.alphaHash,a.vertexColors=e.vertexColors,a.premultipliedAlpha=e.premultipliedAlpha,a.toneMapped=e.toneMapped,a.blendAlpha=e.blendAlpha,a.blendColor=e.blendColor,a.polygonOffset=e.polygonOffset,a.polygonOffsetFactor=e.polygonOffsetFactor,a.polygonOffsetUnits=e.polygonOffsetUnits,a.blending=e.blending,a.userData.isGBufferMaterial=!0,a.visible=ee,Object.assign(a.userData,e.userData),a.visible&&(this.csm.setupMaterial(a),e instanceof u&&Object.assign(a.uniforms,e.uniforms)),s.set(e,a)}var r;return a.visible&&(e instanceof u?this.updateUniformValues(e,a):this.updateMaterialProperties(e,a)),this.initLightVolumeUniform(a),a}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,a=s.addPanel(new Z.Panel("Calls","#83f","#002")),r=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,u=1e3;const d=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout(()=>h=10,5e3)),a.update(e,h);const t=this.renderer.info.render.triangles;t>u&&(u=t,setTimeout(()=>u=1e3,5e3)),r.update(t,u)};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,y=!1,b=0;const x=He();Ne.set(this.container,()=>{y&&(y=!1,requestAnimationFrame(()=>P(b)))}),x.observe(this.container);const P=t=>{y=!1;const a=this.renderer.getContext();if(this.paused&&this.running&&a.drawingBufferHeight>1)return y=!0,b=t,setTimeout(()=>{y&&P(t)},500),void(T=!0);if(this.renderer.clear(),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.clear(),null===this.container.offsetParent)return y=!0,b=t,void setTimeout(()=>{y&&P(t)},500);this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),s.begin(),this.showStats&&l?.startQuery(),this.ssrPass.gpuPanel=l;let r=(t*=.001)-f;if(f=t,T&&(r=.016,T=!1),g.copy(this.camera.matrixWorld),r>1){let t=r;for(;t>.05;)e($e),t-=$e;e(t)}else e(r);this.onLoopCallbacks.forEach(e=>e(r)),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=Ye;Ke.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(Ke);let u=!1,x=!1,w=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Re&&(u=!0),e instanceof o&&this.initCustomDepthMaterial(e),(e instanceof o||e instanceof i.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),this.initShadowUniform(e,e.material),this.initLightVolumeUniform(e.material),null!=this.scene.environment&&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),x=!0):e instanceof X&&(e.visible=!1,p.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[ue]&&isObjectInFrustum(e,h)&&e.material instanceof C&&this.initAoUniform(e.material),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[de]&&isObjectInFrustum(e,h)&&(m.push(e),e.material.uniforms[de].value=this.sceneColorRenderTarget.texture,w=!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,(x||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&&u&&this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene);try{!this.paused&&this.running&&(this.render(r),this.showStats&&l?.endQuery(),this.showStats&&d(),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(P)},1e3/this.fpsCap):requestAnimationFrame(P))};!0===this.options.enableXR?this.renderer.setAnimationLoop(P):requestAnimationFrame(P)}applyGBufferMaterials(e){const t=this.gBufferCachedMaterials,s=this.gBufferCachedVisibility;t.clear(),s.length=0;ge(this.scene,i=>{if(at(i))return s.push(i),i.visible=!1,!1;if(i instanceof o){t.set(i,i.material);let a=!1;if(Array.isArray(i.material)){i.material=i.material.slice();for(let t=0;t<i.material.length;t++)i.material[t]=this.createGBufferMaterial(i.material[t],e),a||(a=i.material[t].visible),this.initShadowUniform(i,i.material[t])}else i.material=this.createGBufferMaterial(i.material,e),a||(a=i.material.visible),this.initShadowUniform(i,i.material);a?i.visible=!0:null!=i.children&&0!=i.children.length||(s.push(i),i.visible=!1)}})}unapplyGBufferMaterials(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e}),this.gBufferCachedVisibility.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)})}initTextures(e=this.scene){e.traverse(e=>{if(e instanceof o)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++)this._initMaterialTextures(e.material[t]);else this._initMaterialTextures(e.material)})}_initMaterialTextures(e){if(!this._initiatedMaterialTextures.has(e))if(this._initiatedMaterialTextures.add(e),e instanceof u){for(const[t,s]of Object.entries(e.uniforms))if(s.value instanceof c){if(this._initiatedTextures.has(s.value))continue;this.renderer.initTexture(s.value),this._initiatedTextures.add(s.value)}}else for(const[t,s]of Object.entries(e))if(s instanceof c){if(this._initiatedTextures.has(s))continue;this.renderer.initTexture(s),this._initiatedTextures.add(s)}}async compileAsync(e=this.scene){if(this.compileInProgress)return;this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0,this.applyGBufferMaterials(Le.opaque),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials(Le.transparent),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),e===this.scene&&(this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.compileAsync(this.fquadBlendAO.mesh,this.fquadBlendAO.camera),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.compileAsync(this.fquadCopyOpaque.mesh,this.fquadCopyOpaque.camera));const t=this.csm.lights[0]?.shadow.camera;null!=t&&(this.applyDepthMaterial(),await this.renderer.compileAsync(e,t),this.unapplyDepthMaterial()),this.compileInProgress=!1,this.renderer.setRenderTarget(null)}applyDepthMaterial(){const e=this.gBufferCachedMaterials;e.clear(),this.scene.traverse(t=>{(t.isMesh||t.isPoints||t.isLine||t.isSprite)&&(this.initCustomDepthMaterial(t),e.set(t,t.material),t.castShadow?null!=t.customDepthMaterial?t.material=t.customDepthMaterial:t.material=ut:t.material=null)})}unapplyDepthMaterial(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e})}renderScene(e){if(!this.running||this.paused)return;if(this.compileInProgress)return void console.error("Compile in progress, skipping render");this.applyGBufferMaterials(e);const t=this.scene.matrixWorldAutoUpdate,s=this.scene.matrixAutoUpdate,i=this.renderer.shadowMap.autoUpdate;e!==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&&this.gBufferCachedMaterials.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof u&&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,a=!1,r=!1,n=!1,o=!1;if(null==this.camera)return;const h=this.camera.getWorldPosition(Je);let u=[];for(const e of this.postProcessVolumes){if(!Xe(e.object))continue;let l=e.blendWeight??1;const d=e.distanceToPoint(h);d>e.blendRadius||(e.blendRadius>0&&(l*=Me(1-d/e.blendRadius,0,1)),l>1&&(l=1),l>0&&(u.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),r=!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&&(a=!0,t.depthFocus=void 0!==t.depthFocus?i.MathUtils.lerp(t.depthFocus,e.settings.depthFocus,l):e.settings.depthFocus),void 0!==e.settings.depthAperture&&(a=!0,t.depthAperture=void 0!==t.depthAperture?i.MathUtils.lerp(t.depthAperture,e.settings.depthAperture,l):e.settings.depthAperture),void 0!==e.settings.depthMaxBlur&&(a=!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=r,this.colorPass.colorTint=t.colorTint,this.colorPass.colorTintIntensity=t.colorTintIntensity,this.colorPass.enabled=r||o,a&&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||null===this.container.offsetParent)return;if(this.renderer.domElement.parentElement!==this.container&&(this.container.replaceChildren(this.renderer.domElement),this.resizeRender()),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,Ye)&&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===Ee.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=Ee:(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 u&&(e.uniforms[se].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[ae]&&(e.uniforms[ae].value=this.camera.near),null!=e.uniforms[ie]&&(e.uniforms[ie].value=this.camera.far)))}initNormalUniform(e){e instanceof u&&null!=e.uniforms[ne]&&(e.uniforms[ne].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){var s;t instanceof C&&(t.uniforms.receiveShadow?(s=t.uniforms.receiveShadow).value||(s.value=e.receiveShadow):t.uniforms.receiveShadow={value:e.receiveShadow})}initLightVolumeUniform(e){e instanceof C&&(null!=this.lightVolume?null==e.uniforms.uSH?(e.defines.USE_LIGHT_PROBE_VOLUME="",e.uniforms.gridOrigin={value:this.lightVolume.gridOrigin},e.uniforms.gridSize={value:this.lightVolume.gridSize},e.uniforms.gridRes={value:this.lightVolume.gridResolution},e.uniforms.giIntensity={value:this.lightProbeIntensity},e.uniforms.uSH={value:this.lightVolume.shTexture},e.uniformsNeedUpdate=!0,e.needsUpdate=!0):e.uniforms.giIntensity.value=this.lightProbeIntensity:null!=e.uniforms.uSH&&(delete e.defines.USE_LIGHT_PROBE_VOLUME,delete e.uniforms.gridOrigin,delete e.uniforms.gridSize,delete e.uniforms.gridRes,delete e.uniforms.giIntensity,delete e.uniforms.uSH,e.uniformsNeedUpdate=!0,e.needsUpdate=!0))}initResolutionUniform(e){e instanceof u&&null!=e.uniforms[re]&&e.uniforms[re].value.set(this.gRenderTarget.width,this.gRenderTarget.height)}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[ue].value=this.aoPass.pdRenderTarget.texture,null==e.defines.USE_SSAO_MAP&&(e.defines.USE_SSAO_MAP="",e.needsUpdate=!0),e.defines.USE_SSAO_MAP="";const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}else if(null!=e.defines.USE_SSAO_MAP){delete e.defines.USE_SSAO_MAP,e.needsUpdate=!0;const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}}initCustomDepthMaterial(e){if(null!=e.customDepthMaterial||!e.castShadow)return;const t=e.material;if(t instanceof C&&!t.transparent&&t.depthWrite){let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Se(we);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new C({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}}};ze=e=t([te(),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 $e=.05;function Xe(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 Ye=new i.Frustum,Qe=new i.Box3,Ke=new i.Matrix4;export function isObjectInFrustum(e,t){const s=Qe.setFromObject(e);return t.intersectsBox(s)}const Je=new i.Vector3;const Ze=new n,et=new p;function tt(e,t,s=new i.Matrix3){return et.copy(e),et.x*=-1,et.y*=-1,et.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(et.y*=-1,et.z*=-1),s.setFromMatrix4(Ze.makeRotationFromEuler(et))}const st=new C({outputs:[G(0,0,0,0),G(0,0,0,0),D(E("white"),Fe(4))],transparent:!0}),it=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});st.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),it);function at(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isLineSegments2||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 C))}class nt extends Ie{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.cachedVisibility=[],this.toRender=[],this.needsSwap=!1}render(e,t,s,i,a){const r=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 u=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),this.cachedVisibility.length=0;let d=0,c=this.toRender;if(c.length=0,this.scene.traverseVisible(e=>{const t=at(e);e instanceof o&&!t?(this.cachedVisibility.push(e),e.visible=!1):t&&(d++,c.push(e))}),d>0)for(const t of c)e.render(t,this.camera);this.cachedVisibility.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=r,s.depthTexture=u,this.scene.matrixWorldAutoUpdate=n,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class ot extends Ie{constructor(e){super(),this.fn=e}render(e,t,s,i,a){this.fn(e,t,s,i,a)}}const lt=["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"],ht=F("fogColor");export class FogNode extends H{constructor(e,t=ht){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),a=e.get(this.fogColor),r=e.get(U("fogFar")),n=e.get(U("fogNear")),o=e.get(U("fogDensity")),l=e.get(V(L.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}, ${r}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${a}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}const ut=new i.MeshDepthMaterial({depthPacking:i.RGBADepthPacking});/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as r,Mesh as i,Object3D as a,TextureLoader as n}from"three";import{GLTFLoader as o,MTLLoader as l,OBJLoader as h,DRACOLoader as c,LUTCubeLoader as u}from"three-stdlib";import{FBXLoader as d}from"three-stdlib";import{cloneMesh as m}from"../utils/mesh.js";import{pathJoin as f}from"../utils/files.js";import{Subject as p,firstValueFrom as g}from"rxjs";import{importCollisionShapes as w,isCollisionMesh as y}from"./collision/collision-shape-import.js";import*as x from"three";import{iterateMaterials as M}from"../utils/materials.js";import{BufferGeometryUtils as L,EXRLoader as b,KTX2Loader as A,TGALoader as v,UltraHDRLoader as _}from"three/examples/jsm/Addons.js";import{disposeScene as C}from"../utils/three/cleanup.js";const S=new c;S.setDecoderConfig({type:"js"}),S.setDecoderPath("/assets/draco/");const R=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new r,this.glbLoader=new o(this.loadingManager).setDRACOLoader(S),this.fbxLoader=new d(this.loadingManager),this.objLoader=new h(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new v(this.loadingManager),this.exrLoader=new b(this.loadingManager),this.cubeLoader=new u(this.loadingManager),this.hdrLoader=new _(this.loadingManager),this.ktx2Loader=new A(this.loadingManager),this._textureLoader=new x.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this._retrievedMeshes=[],this._retrievedTextures=[],this.makeReady=new p,this.ready=g(this.makeReady),this._texturePromises=new Map,this._animationPromises=new Map,this._animationCache=new Map,this.asyncMeshResults=new Map,this.asyncAudioResults=new Map,this.collisionShapeCache=new Map,this.optimizedMeshes=new Set}initKtx2(e){this.initialisedKtx2=!0;null!=getElectronArg("windowId")||import.meta.url.includes(".vite")||import.meta.url.includes("hology/packages/core")?this.ktx2Loader.setTranscoderPath("/assets/basis/"):this.ktx2Loader.setTranscoderPath(new URL("../assets/basis/",import.meta.url).href),this.ktx2Loader.detectSupport(e)}setDataDir(e){this.basePath=f(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){const t=function(e){return T.get(e)}(e),s=getElectronArg("windowId");return null!=s||import.meta.url.includes(".vite")||import.meta.url.includes("hology/packages/core")?f(this.basePath,e)+(null!=s?`?windowId=${s}&v=${t}`:""):new URL(f("..",this.basePath,e),import.meta.url).href}async getTexture(e){if(!e||!e.fileKey)return null;if(this._texturePromises.has(e.id))return this._texturePromises.get(e.id);const t=this._getTexture(e).finally(()=>{this._texturePromises.delete(e.id)});return this._texturePromises.set(e.id,t),t}async _getTexture(e){if(null==e||null==e.fileKey)return null;if(await this.ready,this.textureCache.has(e.id)){const t=this.textureCache.get(e.id);t.dispose(),null!=e.texture&&(t.flipY!==e.texture?.flipY?(t.needsUpdate=!0,t.flipY=e.texture?.flipY??!0):t.wrapS!==K(e.texture?.wrapS)?(t.needsUpdate=!0,t.wrapS=K(e.texture?.wrapS)):t.wrapT!==K(e.texture?.wrapT)&&(t.wrapT=K(e.texture?.wrapT),t.needsUpdate=!0))}else try{await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then(t=>(t.texture3D?t=t.texture3D:(t.wrapS=K(e.texture?.wrapS),t.wrapT=K(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0),this.textureCache.set(e.id,t),this._retrievedTextures.push(t),t))}catch(t){return console.warn("Failed to load texture "+e.name,t),null}const t=this.textureCache.get(e.id);return null!=t&&(t.userData.assetId=e.id),t}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:e?.toLowerCase().endsWith(".cube")?this.cubeLoader:this.textureLoader}clearCache(e){"mesh"===e.type?(Array.from(this.cache.keys()).forEach(t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)}),P(e.fileKey)):"texture"===e.type&&(this.textureCache.delete(e.id),P(e.fileKey))}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!R.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new s,animations:[]};const r=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(r))try{this.asyncMeshResults.has(r)||this.asyncMeshResults.set(r,this.loadMesh(e).finally(()=>this.asyncMeshResults.delete(r))),this.cache.set(r,await this.asyncMeshResults.get(r))}catch(e){return this.onError(e),{scene:new s,animations:[]}}const a=this.cache.get(r).scene,n=this.computeCollisionShapes(e,a);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(a);const o=m(a),l=this.cache.get(r).animations;o.traverse(e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())});const h=new AssetMeshInstance;h.add(o),h.collisionShapes=n,h.animations=l;const c=e.receiveShadow??!0,u=e.castShadow??!1;return o.traverse(e=>{e.castShadow=u,e.receiveShadow=c}),{scene:h,animations:l}}async getAudio(e){await this.ready;const t=e.fileKey;if(this.asyncAudioResults.has(t))return await this.asyncAudioResults.get(t);const s=this.audioLoader.loadAsync(this.getUri(e.fileKey)).finally(()=>{setTimeout(()=>{this.asyncAudioResults.delete(t)},1e3)});return this.asyncAudioResults.set(t,s),s}async getAnimationClip(e){if(null==e||null==e.fileKey||null==!e.anim?.clip)return console.warn("Asset or animation clip name is not defined",e),null;const t=e.anim.clip,s=e.fileKey+"|"+t;if(this._animationCache.has(s))return this._animationCache.get(s);if(this._animationPromises.has(s))return this._animationPromises.get(s);const r=(async()=>{try{const r=await this.getMesh(e),i=r.animations.find(e=>e.name===t);return null!=i&&this._animationCache.set(s,i),i}catch(e){return this.onError(e),null}finally{setTimeout(()=>this._animationPromises.delete(s),1e3)}})();return this._animationPromises.set(s,r),r}computeCollisionShapes(e,t){const s=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(s)||this.collisionShapeCache.set(s,w(t,e)),this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then(e=>(e.scene.traverse(e=>{e instanceof i&&e.material,y(e)?e.visible=!1:e instanceof i&&e.geometry instanceof t&&(e.geometry.hasAttribute("normal")||e.geometry.computeVertexNormals())}),this._retrievedMeshes.push(e.scene),e.scene=function(e,t){let s=!1;if(t.traverseVisible(e=>{k.test(e.name)&&(s=!0)}),!s)return t;const r=new x.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(k);if(null!=t){const s=parseInt(t[1]);0===s?r.addLevel(e,0):console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`)}else i.push(...e.children)}return r}(0,e.scene),e))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid);let s=!0,r=0,a=0;if(e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){r++;const t=Object.keys(e.geometry.attributes).length;t!==a&&0!==a&&(s=!1),a=t}else(e instanceof x.SkinnedMesh||e instanceof x.Bone)&&(s=!1)}),r>1&&s){const s=new Map;e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){if(Array.isArray(e.material))return;e.updateWorldMatrix(!0,!0);const t=e.material?.uuid||"default";s.has(t)||s.set(t,{material:e.material,geometries:[],objects:[]});const r=s.get(t);r.geometries.push(e.geometry.clone().applyMatrix4(e.matrixWorld)),r.objects.push(e)}});for(const e of s.values())for(const t of e.objects)t.removeFromParent();for(const t of s.values()){let s;s=1===t.geometries.length?t.geometries[0]:L.mergeGeometries(t.geometries,!0),s.groups.length>1&&L.mergeGroups(s),e.add(new i(s,t.material))}}const n=[];e.traverse(e=>{e instanceof i&&e.geometry instanceof t&&Array.isArray(e.material)&&!y(e)&&n.push({mesh:e,geometry:e.geometry,materialArray:e.material,parent:e.parent})});for(const{mesh:t,geometry:s,materialArray:r,parent:a}of n){t.removeFromParent();for(let t=0;t<r.length;t++){const n=r[t],o=s.groups.filter(e=>e.materialIndex===t);if(0===o.length)continue;const l=this.extractGeometryGroups(s,o);l.groups.length>1&&L.mergeGroups(l);const h=new i(l,n);a?a.add(h):e.add(h)}s.dispose()}e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){const t=e.geometry;!Array.isArray(e.material)&&t.groups.length>1&&L.mergeGroups(t)}})}extractGeometryGroups(e,s){const r=e.index;if(!r){const r=new t;let i=0;for(const e of s)i+=e.count;if(0===i)return r;for(const t in e.attributes){const a=e.attributes[t],n=a.itemSize,o=a.array,l=new(0,o.constructor)(i*n);let h=0;for(const e of s){const t=e.start*n,s=e.count*n;for(let e=0;e<s;e++)l[h+e]=o[t+e];h+=s}const c=new x.BufferAttribute(l,n,a.normalized);r.setAttribute(t,c)}return r.groups=[{start:0,count:i,materialIndex:0}],r}const i=[];for(const e of s)for(let t=0;t<e.count;t++){const s=r.getX(e.start+t);i.push(s)}if(0===i.length)return new t;const a=new Map,n=[];let o=0;for(const e of i)a.has(e)||(a.set(e,o),o++),n.push(a.get(e));if(0===n.length||0===a.size)return new t;const l=new t;for(const t in e.attributes){const s=e.attributes[t],r=s.itemSize,i=s.array,n=new(0,i.constructor)(a.size*r);for(const[e,t]of a)for(let s=0;s<r;s++)n[t*r+s]=i[e*r+s];const o=new x.BufferAttribute(n,r,s.normalized);l.setAttribute(t,o)}const h=new((n.length>0?Math.max(...n):0)>65535?Uint32Array:Uint16Array)(n.length);for(let e=0;e<n.length;e++)h[e]=n[e];return l.setIndex(new x.BufferAttribute(h,1)),l.groups=[{start:0,count:n.length,materialIndex:0}],l}async loadByAsset(e){this.fbxLoader;const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then(e=>({scene:e.scene,animations:e.animations}));case"fbx":return this.fbxLoader.loadAsync(t).then(e=>({scene:e,animations:e.animations}));case"obj":if(null!=e.materialLib){const t=new l;t.materialOptions={normalizeRGB:!1};const s=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(s)}return this.objLoader.loadAsync(t).then(e=>(j(e),e)).then(e=>({scene:e,animations:e.animations}))}}disposeAll(){this.cache.clear(),this._retrievedMeshes.forEach(e=>C(e)),this._retrievedTextures.forEach(e=>e.dispose()),this._retrievedMeshes.length=0,this._retrievedTextures.length=0}}const T=new Map;function P(e){T.set(e,T.get(e)??1)}function j(e){if(e instanceof i)for(const t of M(e.material))t instanceof x.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(j)}export class AssetMeshInstance extends a{}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find(e=>e.startsWith(t));return s?.substring(t.length)}function K(e){switch(e){case"clamp":return x.ClampToEdgeWrapping;case"repeat":return x.RepeatWrapping;case"mirror":return x.MirroredRepeatWrapping}return x.RepeatWrapping}new x.Matrix4;const k=/_LOD(\d+)$/;/*
|
|
1
|
+
import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as r,Mesh as i,Object3D as a,TextureLoader as n}from"three";import{GLTFLoader as o,MTLLoader as h,OBJLoader as l,DRACOLoader as c,LUTCubeLoader as u}from"three-stdlib";import{FBXLoader as d}from"three-stdlib";import{cloneMesh as m}from"../utils/mesh.js";import{pathJoin as f}from"../utils/files.js";import{Subject as p,firstValueFrom as g}from"rxjs";import{importCollisionShapes as w,isCollisionMesh as y}from"./collision/collision-shape-import.js";import*as x from"three";import{iterateMaterials as M}from"../utils/materials.js";import{BufferGeometryUtils as L,EXRLoader as b,KTX2Loader as A,TGALoader as v,UltraHDRLoader as _}from"three/examples/jsm/Addons.js";import{disposeScene as C}from"../utils/three/cleanup.js";const S=new c;S.setDecoderConfig({type:"js"}),S.setDecoderPath("/assets/draco/");const R=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new r,this.glbLoader=new o(this.loadingManager).setDRACOLoader(S),this.fbxLoader=new d(this.loadingManager),this.objLoader=new l(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new v(this.loadingManager),this.exrLoader=new b(this.loadingManager),this.cubeLoader=new u(this.loadingManager),this.hdrLoader=new _(this.loadingManager),this.ktx2Loader=new A(this.loadingManager),this._textureLoader=new x.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this._retrievedMeshes=[],this._retrievedTextures=[],this.makeReady=new p,this.ready=g(this.makeReady),this._texturePromises=new Map,this._animationPromises=new Map,this._animationCache=new Map,this.asyncMeshResults=new Map,this.asyncAudioResults=new Map,this.collisionShapeCache=new Map,this.optimizedMeshes=new Set}initKtx2(e){this.initialisedKtx2=!0;null!=getElectronArg("windowId")||import.meta.url.includes(".vite")||import.meta.url.includes("hology/packages/core")?this.ktx2Loader.setTranscoderPath("/assets/basis/"):this.ktx2Loader.setTranscoderPath(new URL("../assets/basis/",import.meta.url).href),this.ktx2Loader.detectSupport(e)}setDataDir(e){this.basePath=f(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){const t=function(e){return T.get(e)}(e),s=getElectronArg("windowId");return null!=s||import.meta.url.includes(".vite")||import.meta.url.includes("hology/packages/core")?f(this.basePath,e)+(null!=s?`?windowId=${s}&v=${t}`:""):new URL(f("..",this.basePath,e),import.meta.url).href}async getTexture(e){if(!e||!e.fileKey)return null;if(this._texturePromises.has(e.id))return this._texturePromises.get(e.id);const t=this._getTexture(e).finally(()=>{this._texturePromises.delete(e.id)});return this._texturePromises.set(e.id,t),t}async _getTexture(e){if(null==e||null==e.fileKey)return null;if(await this.ready,this.textureCache.has(e.id)){const t=this.textureCache.get(e.id);t.dispose(),null!=e.texture&&(t.flipY!==e.texture?.flipY?(t.needsUpdate=!0,t.flipY=e.texture?.flipY??!0):t.wrapS!==K(e.texture?.wrapS)?(t.needsUpdate=!0,t.wrapS=K(e.texture?.wrapS)):t.wrapT!==K(e.texture?.wrapT)&&(t.wrapT=K(e.texture?.wrapT),t.needsUpdate=!0))}else try{await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then(t=>(t.texture3D?t=t.texture3D:(t.wrapS=K(e.texture?.wrapS),t.wrapT=K(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0),this.textureCache.set(e.id,t),this._retrievedTextures.push(t),t))}catch(t){return console.warn("Failed to load texture "+e.name,t),null}const t=this.textureCache.get(e.id);return null!=t&&(t.userData.assetId=e.id),t}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:e?.toLowerCase().endsWith(".cube")?this.cubeLoader:this.textureLoader}clearCache(e){"mesh"===e.type?(Array.from(this.cache.keys()).forEach(t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)}),P(e.fileKey)):"texture"===e.type&&(this.textureCache.delete(e.id),P(e.fileKey))}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!R.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new s,animations:[]};const r=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(r))try{this.asyncMeshResults.has(r)||this.asyncMeshResults.set(r,this.loadMesh(e).finally(()=>this.asyncMeshResults.delete(r))),this.cache.set(r,await this.asyncMeshResults.get(r))}catch(e){return this.onError(e),{scene:new s,animations:[]}}const a=this.cache.get(r).scene,n=this.computeCollisionShapes(e,a);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(a);const o=m(a),h=this.cache.get(r).animations;o.traverse(e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())});const l=new AssetMeshInstance;l.add(o),l.collisionShapes=n,l.animations=h;const c=e.receiveShadow??!0,u=e.castShadow??!1;return o.traverse(e=>{e.castShadow=u,e.receiveShadow=c}),{scene:l,animations:h}}async getAudio(e){await this.ready;const t=e.fileKey;if(this.asyncAudioResults.has(t))return await this.asyncAudioResults.get(t);const s=this.audioLoader.loadAsync(this.getUri(e.fileKey)).finally(()=>{setTimeout(()=>{this.asyncAudioResults.delete(t)},1e3)});return this.asyncAudioResults.set(t,s),s}async getAnimationClip(e){if(null==e||null==e.fileKey||null==!e.anim?.clip)return console.warn("Asset or animation clip name is not defined",e),null;const t=e.anim.clip,s=e.fileKey+"|"+t;if(this._animationCache.has(s))return this._animationCache.get(s);if(this._animationPromises.has(s))return this._animationPromises.get(s);const r=(async()=>{try{const r=await this.getMesh(e),i=r.animations.find(e=>e.name===t);return null!=i&&this._animationCache.set(s,i),i}catch(e){return this.onError(e),null}finally{setTimeout(()=>this._animationPromises.delete(s),1e3)}})();return this._animationPromises.set(s,r),r}computeCollisionShapes(e,t){const s=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(s)||this.collisionShapeCache.set(s,w(t,e)),this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then(e=>(e.scene.traverse(e=>{e instanceof i&&e.material,y(e)?e.visible=!1:e instanceof i&&e.geometry instanceof t&&(e.geometry.hasAttribute("normal")||e.geometry.computeVertexNormals())}),this._retrievedMeshes.push(e.scene),e.scene=function(e,t){let s=!1;if(t.traverseVisible(e=>{D.test(e.name)&&(s=!0)}),!s)return t;const r=new x.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(D);if(null!=t){const s=parseInt(t[1]);0===s?r.addLevel(e,0):console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`)}else i.push(...e.children)}return r}(0,e.scene),function(e){const t=k;k.length=0,e.traverse(e=>{(e instanceof x.Camera||e instanceof x.Light)&&t.push(e)}),t.forEach(e=>e.removeFromParent())}(e.scene),e))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid);let s=!0,r=0,a=0;if(e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){r++;const t=Object.keys(e.geometry.attributes).length;t!==a&&0!==a&&(s=!1),a=t}else(e instanceof x.SkinnedMesh||e instanceof x.Bone)&&(s=!1)}),r>1&&s){const s=new Map;e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){if(Array.isArray(e.material))return;e.updateWorldMatrix(!0,!0);const t=e.material?.uuid||"default";s.has(t)||s.set(t,{material:e.material,geometries:[],objects:[]});const r=s.get(t);r.geometries.push(e.geometry.clone().applyMatrix4(e.matrixWorld)),r.objects.push(e)}});for(const e of s.values())for(const t of e.objects)t.removeFromParent();for(const t of s.values()){let s;s=1===t.geometries.length?t.geometries[0]:L.mergeGeometries(t.geometries,!0),s.groups.length>1&&L.mergeGroups(s),e.add(new i(s,t.material))}}const n=[];e.traverse(e=>{e instanceof i&&e.geometry instanceof t&&Array.isArray(e.material)&&!y(e)&&n.push({mesh:e,geometry:e.geometry,materialArray:e.material,parent:e.parent})});for(const{mesh:t,geometry:s,materialArray:r,parent:a}of n){t.removeFromParent();for(let t=0;t<r.length;t++){const n=r[t],o=s.groups.filter(e=>e.materialIndex===t);if(0===o.length)continue;const h=this.extractGeometryGroups(s,o);h.groups.length>1&&L.mergeGroups(h);const l=new i(h,n);a?a.add(l):e.add(l)}s.dispose()}e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){const t=e.geometry;!Array.isArray(e.material)&&t.groups.length>1&&L.mergeGroups(t)}})}extractGeometryGroups(e,s){const r=e.index;if(!r){const r=new t;let i=0;for(const e of s)i+=e.count;if(0===i)return r;for(const t in e.attributes){const a=e.attributes[t],n=a.itemSize,o=a.array,h=new(0,o.constructor)(i*n);let l=0;for(const e of s){const t=e.start*n,s=e.count*n;for(let e=0;e<s;e++)h[l+e]=o[t+e];l+=s}const c=new x.BufferAttribute(h,n,a.normalized);r.setAttribute(t,c)}return r.groups=[{start:0,count:i,materialIndex:0}],r}const i=[];for(const e of s)for(let t=0;t<e.count;t++){const s=r.getX(e.start+t);i.push(s)}if(0===i.length)return new t;const a=new Map,n=[];let o=0;for(const e of i)a.has(e)||(a.set(e,o),o++),n.push(a.get(e));if(0===n.length||0===a.size)return new t;const h=new t;for(const t in e.attributes){const s=e.attributes[t],r=s.itemSize,i=s.array,n=new(0,i.constructor)(a.size*r);for(const[e,t]of a)for(let s=0;s<r;s++)n[t*r+s]=i[e*r+s];const o=new x.BufferAttribute(n,r,s.normalized);h.setAttribute(t,o)}const l=new((n.length>0?Math.max(...n):0)>65535?Uint32Array:Uint16Array)(n.length);for(let e=0;e<n.length;e++)l[e]=n[e];return h.setIndex(new x.BufferAttribute(l,1)),h.groups=[{start:0,count:n.length,materialIndex:0}],h}async loadByAsset(e){this.fbxLoader;const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then(e=>({scene:e.scene,animations:e.animations}));case"fbx":return this.fbxLoader.loadAsync(t).then(e=>({scene:e,animations:e.animations}));case"obj":if(null!=e.materialLib){const t=new h;t.materialOptions={normalizeRGB:!1};const s=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(s)}return this.objLoader.loadAsync(t).then(e=>(j(e),e)).then(e=>({scene:e,animations:e.animations}))}}disposeAll(){this.cache.clear(),this._retrievedMeshes.forEach(e=>C(e)),this._retrievedTextures.forEach(e=>e.dispose()),this._retrievedMeshes.length=0,this._retrievedTextures.length=0}}const T=new Map;function P(e){T.set(e,T.get(e)??1)}function j(e){if(e instanceof i)for(const t of M(e.material))t instanceof x.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(j)}export class AssetMeshInstance extends a{}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find(e=>e.startsWith(t));return s?.substring(t.length)}function K(e){switch(e){case"clamp":return x.ClampToEdgeWrapping;case"repeat":return x.RepeatWrapping;case"mirror":return x.MirroredRepeatWrapping}return x.RepeatWrapping}new x.Matrix4;const k=[];const D=/_LOD(\d+)$/;/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|