@hology/core 0.0.202 → 0.0.204
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/effects/vfx/vfx-actor.d.ts +2 -0
- package/dist/effects/vfx/vfx-actor.js +1 -1
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/gameplay/inject.js +1 -1
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/landscape/utils.d.ts +8 -0
- package/dist/scene/landscape/utils.js +1 -1
- package/dist/scene/materializer.d.ts +7 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model.d.ts +5 -0
- package/dist/shader/graph/compiler.d.ts +2 -0
- package/dist/shader/graph/compiler.js +1 -1
- package/dist/shader/graph/model.d.ts +1 -1
- package/dist/shader/graph/registry.js +1 -1
- package/dist/test/landscape-expansion.test.d.ts +2 -0
- package/dist/test/landscape-expansion.test.js +4 -0
- package/dist/test/material-assignment.test.d.ts +2 -0
- package/dist/test/material-assignment.test.js +4 -0
- package/dist/test/materializer-prefetch.test.d.ts +2 -0
- package/dist/test/materializer-prefetch.test.js +4 -0
- package/dist/test/shader-graph.test.js +1 -1
- package/package.json +3 -3
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -31,6 +31,8 @@ export declare class VfxActor extends BaseActor {
|
|
|
31
31
|
stop(): void;
|
|
32
32
|
applyClipEndBehavior(behavior: VfxClipEndBehavior | undefined, remainingLifeSeconds?: number): void;
|
|
33
33
|
restart(): void;
|
|
34
|
+
private restartEmitter;
|
|
35
|
+
private removeEmitterParticlesRecursive;
|
|
34
36
|
private _worldPos;
|
|
35
37
|
private _worldRot;
|
|
36
38
|
private _worldEul;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as t}from"tslib";import*as s from"three";import{Rate as e}from"@hology/nebula";import{Actor as i,BaseActor as r}from"../../gameplay/actors/actor.js";import{inject as o}from"../../gameplay/inject.js";import{AssetLoader as a}from"../../gameplay/services/asset-loader.js";import{ViewController as n}from"../../gameplay/services/render.js";import{World as
|
|
1
|
+
import{__decorate as t}from"tslib";import*as s from"three";import{Rate as e}from"@hology/nebula";import{Actor as i,BaseActor as r}from"../../gameplay/actors/actor.js";import{inject as o}from"../../gameplay/inject.js";import{AssetLoader as a}from"../../gameplay/services/asset-loader.js";import{ViewController as n}from"../../gameplay/services/render.js";import{World as m}from"../../gameplay/services/world.js";import{DelayRate as h}from"./rates.js";import{materializeVfx as l}from"./vfx-materializer.js";import{PhysicsSystem as p}from"../../gameplay/services/physics/physics-system.js";import{ShaderProvider as c}from"../../gameplay/services/shader-provider.js";import{AssetResourceLoader as d}from"../../scene/asset-resource-loader.js";import{AssetsProvider as u}from"../../scene/assets-provider.js";import{VfxInputRuntime as y}from"./vfx-input-runtime.js";let f=class extends r{constructor(){super(...arguments),this.timescale=1,this.paused=!0,this.assetLoader=o(a),this.assetManagerService=o(d),this.assetService=o(u),this.world=o(m),this.view=o(n),this.physics=o(p),this.shaderProvider=o(c),this.inputRuntime=new y,this.inputOverrides=new Map,this._worldPos=new s.Vector3,this._worldRot=new s.Quaternion,this._worldEul=new s.Euler,this.max=0}async fromAsset(t,s){if("vfx"!==t.type)throw"Asset must be a VFX asset but is "+t.type;null!=this.system&&(this.system.destroy(),this.system.emitters.forEach(t=>t.reset())),this.sourceAsset=t,this.disposeSystem&&this.disposeSystem(),this.world.scene.add(this.object),this.inputRuntime.setDefinitions(this.sourceAsset.vfx.inputs??[]);for(const[t,s]of this.inputOverrides)this.inputRuntime.setInput(t,s);null!=s&&this.setInputs(s);const{system:e,dispose:i,container:r}=await l(this.sourceAsset,this.object,{getAsset:t=>this.assetLoader.getAsset(t),getMaterial:t=>this.assetLoader.getMaterialByAssetId(t),getTexture:t=>this.assetLoader.getTextureByAssetId(t),getMesh:t=>this.assetLoader.getModelByAssetId(t).then(t=>t.scene)},this.view,this.physics,this.shaderProvider,this.assetService,this.assetManagerService,this.inputRuntime);this.system=e,this.disposeSystem=i,this.particleSystemContainer=r,this.object.visible=!1,this.object.matrixAutoUpdate=!1,this.object.matrixWorldAutoUpdate=!1,this.particleSystemContainer.matrixAutoUpdate=!1,this.particleSystemContainer.matrixWorldAutoUpdate=!1}setInput(t,e){this.inputOverrides.set(t,function(t){if(t instanceof s.Vector3||t instanceof s.Color)return t.clone();if(Array.isArray(t))return[...t];return t}(e)),this.inputRuntime.setInput(t,e)}setInputs(t){for(const[s,e]of Object.entries(t))this.setInput(s,e)}play(){null==this.particleSystemContainer.parent&&this.world.scene.add(this.particleSystemContainer),this.object.matrixAutoUpdate=!0,this.object.matrixWorldAutoUpdate=!0,this.particleSystemContainer.matrixAutoUpdate=!0,this.particleSystemContainer.matrixWorldAutoUpdate=!0,this.object.visible=!0,this.paused=!1;this.system.emitters.every(t=>t.dead)&&this.restart()}pause(){this.paused=!0}stop(){this.system.emitters.forEach(t=>{this.stopEmitterEmission(t)})}applyClipEndBehavior(t,s){const e=t??"finish";if("finish"!==e){if(null!=this.system&&null!=this.system.emitters)for(const t of this.system.emitters)this.applyEmitterClipEndBehavior(t,e,s)}else this.stop()}restart(){if(null!=this.system&&null!=this.system.emitters)for(const t of this.system.emitters)this.restartEmitter(t)}restartEmitter(t){const s=t.rate;s instanceof h?s.restart():s instanceof e&&(s.nextTime=0),null==t.clearParticlesRecursive?this.removeEmitterParticlesRecursive(t):t.clearParticlesRecursive()}removeEmitterParticlesRecursive(t){const s=t.childEmitters??[];for(const t of s)this.removeEmitterParticlesRecursive(t);t.removeAllParticles?.()}onUpdate(t){this.paused||(this.object.getWorldPosition(this._worldPos),this.object.getWorldQuaternion(this._worldRot),this._worldEul.setFromQuaternion(this._worldRot),this.system?.emitters.forEach(t=>{"world"===t._space&&(t.setPosition(this._worldPos),t.setRotation(this._worldEul))}),this.updateSystem(t*this.timescale))}getParticleCount(){return this.system?.getCount()??0}onEndPlay(){this.stop(),null!=this.disposeSystem&&this.disposeSystem()}updateSystem(t){this.system?.update(t)}applyEmitterClipEndBehavior(t,s,e,i=!1){this.stopEmitterEmission(t,i);const r=t.particles??[];if("kill"===s)t.removeAllParticles?.();else{const t=Math.max(0,e??0);for(const s of r)s.life=Math.min(s.life,s.age+t)}const o=t.childEmitters??[];for(const t of o)this.applyEmitterClipEndBehavior(t,s,e,!0)}stopEmitterEmission(t,s=!1){const i=t.rate;i instanceof e&&(i.nextTime=1/0),s&&t.stopEmit?.()}};f=t([i()],f);export{f as VfxActor};/*
|
|
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 e,{Behaviour as t,Body as a,Emitter as r,Rate as s}from"@hology/nebula";import*as n from"three";import{Object3D as i}from"three";import{AttributeVec3Node as o,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as u,UniformFloatNode as p,UniformVec3Node as d,Vec3ExpressionNode as h,Vec4Node as m,attributeFloat as f,attributeVec3 as y,attributeVec4 as w,attributes as g,clamp as b,float as v,glslFunction as A,lambertMaterial as E,log as M,pow as x,rgb as I,rgba as S,smoothstep as T,standardMaterial as P,textureSampler2d as B,uniformFloat as C,uniforms as R,varying as k,varyingAttributes as j,varyingVec3 as G,varyingVec4 as V}from"three-shader-graph";import{prepareClassParameters as D,prepareShaderGraphParameters as F,prepareShapeParameters as z}from"../../scene/materializer.js";import{SerializedParamType as O}from"../../scene/model.js";import{ShapeLibrary as L}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as Q,linearEyeDepth as W}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as H,particleTimeUniformName as U,particleUniforms as q,particleVelcoityUniformName as J}from"../../shader-nodes/particle.js";import{sampleFlipbook as N}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as X}from"./initializsers.js";import{DelayRate as K,OnceRate as Y}from"./rates.js";import{StretchedSprite as _}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as $,VfxInitializserLibrary as ee}from"./vfx-defs.js";import{MultiRenderer as te}from"./vfx-renderers.js";import{WorldCollisionBehaviour as ae}from"./vfx-collision-behaviour.js";import{getSpritePosition as re,SpriteNodeShaderMaterial as se}from"../../shader/sprite-shader.js";import{DecalUnlitShader as ne}from"../../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as ie}from"../../shader/builtin/decal-standard-shader.js";import{createBoundBehaviour as oe,createBoundInitializer as le}from"./vfx-binding-runtime.js";import{buildShaderGraphMaterial as ce}from"../../shader/graph/index.js";export async function materializeVfx(t,a,r,s,o,l,c,u,p){let d=a;for(;null!=d.parent;)d=d.parent;const h=new i;h.name="particle system local",a.add(h);const m=new i;m.name="particle system world";const f=new te(m,h,n,s),y=new e;return(await Promise.all(t.vfx.emitters.slice().sort((e,t)=>(t.output.renderOrder??0)-(e.output.renderOrder??0)).map(async e=>{const t=await ue(e,r,c,u,y,o,l,p);return t.setParentRecursive(y),t.emit()}))).forEach(e=>y.addEmitter(e)),y.addRenderer(f).emit({onEnd:()=>{}}),{container:m,system:y,dispose:()=>{m.removeFromParent(),h.removeFromParent(),f.dispose()}}}async function ue(e,t,r,u,v,x,I,P){const G=function(e){let t;switch(e.rate.type){case"continuous":t=new K(e.rate.delay??0,e.rate.count,e.rate.time,e.rate.duration);break;case"once":t=new Y(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new s(0,1/0)}return t}(e);let D;switch(e.output.type){case"decal":D=new a(await async function(e,t,a,r,s){if("shaderGraph"===me(e)){const t=await he(e,"decal",a,r,s);if(null!=t){const a=new n.Mesh(new n.BoxGeometry(1,1,1),t);return null!=e.renderOrder&&(a.renderOrder=e.renderOrder),a}}const i=!1!==e.unlit?new ne:new ie;i.color=new n.Color(e.color),i instanceof ne?i.intensity=e.intensity??1:i.emissiveIntensity=e.intensity??1;if(e.colorMap){const a=await t.getTexture(e.colorMap);i.colorMap=a}if(e.alphaMap){const a=await t.getTexture(e.alphaMap);i.alphaMap=a}const o=i.build();o.blending=Z[e.blendingMode]??n.NormalBlending,o.transparent=!0,o.side=n.BackSide,o.depthTest=!1,null!=o&&!0===e.bloom&&(o.userData.hasBloom=!0);o.defines.IS_PARTICLE="";const l=new n.BoxGeometry(1,1,1),c=new n.Mesh(l,o);null!=e.renderOrder&&(c.renderOrder=e.renderOrder);return c}(e.output,t,r,u,I));break;case"sprite":D=new a(await async function(e,t,a,r,s){let i=null;const o=me(e);"shaderGraph"===o&&(i=await he(e,"sprite",a,r,s));null==i&&"shader"===o&&null!=e.shader&&(i=await de(e,t,s));null==i&&(i=await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):pe,r=B(a);let s=r.sample(j.uv);e.flipbook?.enabled&&(s=N(r,g.uv,e.flipbook.columns,e.flipbook.rows,q.time,e.flipbook.fps,e.flipbook.mode));const i=new p("rotation",0),o=new d("color").rgb,l=C("opacity",1),c=W.subtract(Q).divide(W);let u=l;switch(e.opacityChannel??"red"){case"none":break;case"red":u=u.multiply(s.r);break;case"alpha":u=u.multiply(s.a)}if("number"==typeof e.softness&&e.softness>0){const t=b(c,0,1e3);u=u.multiply(T(0,.2*e.softness,t))}const h=re(i),m=S(o.multiply(s.rgb).multiplyScalar(e.intensity??1),u);var f=new se({color:m,emissive:m.rgb.multiplyScalar(u),transparent:!0,position:h,alphaTest:1e-4,uniforms:{color:{value:new n.Color(e.color)}}});f.alphaHash=!0,null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??n.NormalBlending,f}(e,t));fe(i,e);const l=new n.Mesh(new n.PlaneGeometry(1,1),i);return l.name="sprite",l}(e.output,t,r,u,I));break;case"stretchedSprite":D=new a(await async function(e,t){"shaderGraph"===me(e)&&console.warn("Shader graph materials are not supported for stretched sprite VFX outputs yet. Falling back to the default stretched sprite material.");const a=null!=e.texture?await t.getTexture(e.texture):pe,r=B(a).sample(j.uv),s=V(new l("color")),i=s.rgb.multiply(r.rgb);let o=s.w;switch(e.opacityChannel??"red"){case"none":break;case"red":o=o.multiply(r.r);break;case"alpha":o=o.multiply(r.a)}if("number"==typeof e.softness&&e.softness>0){const t=W.subtract(Q).divide(M(W)),a=b(t,0,1e3);o=o.multiply(T(0,.2*e.softness,a))}const c=A(m,{position:g.position,offset:y("offset"),modelViewMatrix:R.modelViewMatrix,velocity:w("velocity"),size:y("size"),rotation:f("rotation")},"\n float lengthFactor = velocity.w;\n float avgSize = (size.x + size.y) * 0.5;\n\n vec4 mvPosition = modelViewMatrix * vec4( offset , 1.0 );\n vec3 viewVelocity = normalMatrix * velocity.xyz;\n float vlength = length(viewVelocity); \n mvPosition.xyz += position.y * normalize(cross(mvPosition.xyz, viewVelocity)) * avgSize; \n mvPosition.xyz -= (position.x + 0.5) * viewVelocity * (1.0 + lengthFactor / vlength) * avgSize;\n return projectionMatrix * mvPosition;\n ");var u=new se({color:S(i.multiplyScalar(e.intensity??1),o),alphaTest:.1,transparent:!0,position:c,uniforms:{color:{value:new n.Color(e.color)}}});null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);u.blending=Z[e.blendingMode]??n.NormalBlending;const p=new _(new n.PlaneGeometry(1,1),u);return p.scaleFactor=e.scale,p}(e.output,t));break;case"shape":D=new a(await async function(e,t,a,r,s){if(null==e.shape)return console.log("Shape is null"),new i;const l=L[e.shape];if(null==l)return console.error(`No shape with type ${e.shape}`),new i;const u=z(e.params??{}),p=l.geometry(u);let d=null;const m=me(e);"shaderGraph"===m&&(d=await he(e,"surface",a,r,s));null==d&&"shader"===m&&null!=e.shader&&(d=await de(e,t,s));null==d&&(d="material"===m&&null!=e.material?ye(await t.getMaterial(e.material)):function(){const e=k(new h("instanceColor")).rgb,t=k(new o("particleData")).x;return new c({color:E({color:e}).rgb.rgba(t),opacity:t,transparent:!0})}());return fe(d,e),new n.Mesh(p,d)}(e.output,t,r,u,I));break;case"mesh":D=new a(await async function(e,t,a,r,s){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new i;const o=await t.getMesh(e.assetId),l=await t.getAsset(e.assetId),c=me(e);if("shaderGraph"===c||"shader"===c||"material"===c){let i;"shaderGraph"===c?i=await he(e,"surface",a,r,s):"shader"===c&&null!=e.shader?i=await de(e,t,s):"material"===c&&null!=e.material&&(i=ye(await t.getMaterial(e.material))),fe(i,e),o.traverse(e=>{e instanceof n.Mesh&&null!=i&&(e.material=i)})}else{const e=[];if(null!=l.materialAssignments)for(const a of l.materialAssignments)o.traverse(r=>{r instanceof n.Mesh&&r.material instanceof n.Material&&r.material.color instanceof n.Color&&(r.material.name!=a.name&&null!=a.name||"#"+r.material.color.getHexString()!==a.color||e.push(t.getMaterial(a.materialId).then(e=>r.material=e)))});await Promise.all(e)}const u=[];if(o.traverse(e=>{e instanceof n.Mesh&&u.push(e)}),1===u.length){const e=u[0];return e.updateWorldMatrix(!0,!0),e.updateMatrixWorld(),e.matrix.copy(e.matrixWorld),e.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.removeFromParent(),e}return o}(e.output,t,r,u,I));break;case"trail":{const s="shaderGraph"===me(e.output)?await he(e.output,"trail",r,u,I,{trailBillboard:e.output.billboard??!1}):null;D=new a({type:"trail",taper:e.output.taper,headGeometry:null,material:s instanceof n.ShaderMaterial?s:void 0,dragTexture:!1,texture:null!=e.output.texture?await t.getTexture(e.output.texture):null,opacityChannel:e.output.opacityChannel,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,intensityEnd:e.output.intensityEnd??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom,scrollSpeed:e.output.scrollSpeed,width:e.output.width,billboard:e.output.billboard??!1});break}default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const F=new ge;F.parent=v,F.setRate(G),F._space=e.output.space;const H=await Promise.all(e.initializers.filter(e=>!1!==e.enabled).filter(e=>null!=ee[e.type]).map(async e=>{const t=ee[e.type],a=await z(e.params??{});return le(t,e.params??{},a,P)}));H.push(D,new X),F.addInitializers(H);const U=await Promise.all(e.behaviours.filter(e=>!1!==e.enabled).filter(e=>null!=$[e.type]).map(async e=>{const t=$[e.type];for(const[a,r]of Object.entries(e.params))t.parameters&&null!=t.parameters[a]&&"curve"===t.parameters[a].type&&r.type!==O.Curve&&(r.type=O.Curve);const a=await z(e.params??{},r,u);return oe(t,e.params??{},a,P)}).sort((e,t)=>e instanceof ae?1:0));U.push(new we);for(const e of U)e instanceof ae&&(e.physics=x);F.addBehaviours(U);for(const a of e.children){const e=await ue(a,t,r,u,v,x,I,P),s=new EmitterPool(()=>{const t=e.clone();return t.onExpired=()=>{const e=F.childEmitters.findIndex(e=>e.id===t.id);-1!=e&&F.childEmitters.splice(e,1),s.release(t)},t}),n=F.eventDispatcher,i=new Map;F.bindEmitterEvent=!0,n.addEventListener("PARTICLE_DEAD",e=>{const t=i.get(e.id);if(null!=t){const e=F.childEmitters.findIndex(e=>e.id===t.id);null!=e&&(t.stopEmit(),F.childEmitters.splice(e,1))}});let o="PARTICLE_CREATED";if("spawnEvent"in a)switch(a.spawnEvent){case"collision":o="PARTICLE_COLLISION";break;case"start":o="PARTICLE_CREATED"}n.addEventListener(o,e=>{const t=s.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),F.childEmitters.push(t),i.set(e.id,t),t.parentParticle=e,t.system=F.system,t.emit()})}return F}const pe=(new n.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");async function de(e,t,a){const r=a.get(e.shader);if(null==r)return console.error("No shader exists with name "+e.shader),new n.Material;const s=new r.type,i=await D(e.shaderParams??{},r.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0,void 0,s);return Object.assign(s,i),s.build()}async function he(e,t,a,r,s,n={}){const i=e.shaderGraph;if("asset"!==i?.source||null==i.assetId)return console.warn(`Missing shader graph asset reference for ${e.type} VFX output`),null;const o=await a.getAsset(i.assetId),l=o?.shaderGraph;if(null==l)return console.warn(`Missing shader graph asset "${i.assetId}" for ${e.type} VFX output`),null;if(l.target!==t)return console.warn(`Shader graph "${o.name}" targets "${l.target}" but ${e.type} VFX output expects "${t}"`),null;try{const t=await F(e.shaderGraphParams??{},l,a,r,void 0,s.shaders),o=ce(l,{parameters:t,trailBillboard:n.trailBillboard});return o.userData.customShaderName=`shaderGraph:${i.assetId}`,fe(o,e),o}catch(e){return console.log("Shader graph VFX runtime error: "+e,e),null}}function me(e){return null!=e.materialSource?e.materialSource:"asset"===e.shaderGraph?.source?"shaderGraph":"shader"in e&&null!=e.shader?"shader":"mesh"!==e.type&&"shape"!==e.type||null==e.material?"default":"material"}function fe(e,t){null!=e&&("bloom"in t&&!0===t.bloom&&(e.userData.hasBloom=!0),"sprite"===t.type?(e.blending=Z[t.blendingMode]??n.NormalBlending,!0===t.lockY&&e instanceof n.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.LOCK_Y_AXIS="")):"decal"===t.type&&(e.blending=Z[t.blendingMode]??n.NormalBlending,e.transparent=!0,e.side=n.BackSide,e.depthTest=!1,e instanceof n.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.IS_PARTICLE="")))}function ye(e){const t=k(new h("instanceColor")).rgb;let a,r=k(new o("particleData")).x;if(e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshBasicMaterial){let s=t.multiply(I(e.color));null!=e.map&&(s=s.multiply(B(e.map).sample(j.uv).rgb)),null!=e.alphaMap&&(r=r.multiply(B(e.alphaMap).sample(j.uv).r)),e instanceof n.MeshStandardMaterial?a=new c({color:P({color:s,emissive:I(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(r),emissive:I(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}):e instanceof n.MeshLambertMaterial?a=new c({color:E({color:s}).rgb.rgba(r),emissive:I(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}):e instanceof n.MeshBasicMaterial&&(a=new c({color:s.rgb.rgba(r),emissive:s.rgb,transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}))}else e instanceof c&&(a=e.clone(),a.defines.IS_PARTICLE="");return null!=a&&(!0===e.userData?.hasBloom&&null!=a&&(a.userData.hasBloom=!0),a.side=e.side,a.transparent=e.transparent),a??e}class we extends t{initialize(e){e.body instanceof n.Object3D&&e.body.traverse(e=>{if(e instanceof n.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[H]||null!=t.uniforms[U]||t.uniforms[J])}})}mutate(e,t,a){this.energize(e,t),e.target instanceof i&&e.target.traverse(t=>{if(t instanceof n.Mesh){const a=t.material;a instanceof c&&(null!=a.uniforms[H]&&(a.uniforms[H].value=this.energy),null!=a.uniforms[U]&&(a.uniforms[U].value=e.age),null!=a.uniforms[J]&&(a.uniforms[J].value=e.velocity))}})}}class ge extends r{constructor(){super(...arguments),this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}update(e){if(!this.isEmitting&&0===this.particles.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle?t.position.copy(t.parentParticle.position):t.setPosition(this.position),t.update(e)}clone(){const e=new ge;return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach(t=>t.setParentRecursive(e))}}export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
|
|
1
|
+
import e,{Behaviour as t,Body as a,Emitter as r,Rate as s}from"@hology/nebula";import*as i from"three";import{Object3D as n}from"three";import{AttributeVec3Node as o,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as p,UniformFloatNode as u,UniformVec3Node as h,Vec3ExpressionNode as d,Vec4Node as m,attributeFloat as f,attributeVec3 as y,attributeVec4 as g,attributes as w,clamp as b,float as v,glslFunction as E,lambertMaterial as A,log as M,pow as x,rgb as P,rgba as S,smoothstep as I,standardMaterial as T,textureSampler2d as C,uniformFloat as R,uniforms as B,varying as k,varyingAttributes as j,varyingVec3 as D,varyingVec4 as G}from"three-shader-graph";import{prepareClassParameters as V,prepareShaderGraphParameters as F,prepareShapeParameters as z}from"../../scene/materializer.js";import{SerializedParamType as L}from"../../scene/model.js";import{ShapeLibrary as O}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as W,linearEyeDepth as Q}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as H,particleTimeUniformName as U,particleUniforms as q,particleVelcoityUniformName as J}from"../../shader-nodes/particle.js";import{sampleFlipbook as N}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as X}from"./initializsers.js";import{DelayRate as _,OnceRate as K}from"./rates.js";import{StretchedSprite as Y}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as $,VfxInitializserLibrary as ee}from"./vfx-defs.js";import{MultiRenderer as te}from"./vfx-renderers.js";import{WorldCollisionBehaviour as ae}from"./vfx-collision-behaviour.js";import{getSpritePosition as re,SpriteNodeShaderMaterial as se}from"../../shader/sprite-shader.js";import{DecalUnlitShader as ie}from"../../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as ne}from"../../shader/builtin/decal-standard-shader.js";import{createBoundBehaviour as oe,createBoundInitializer as le}from"./vfx-binding-runtime.js";import{buildShaderGraphMaterial as ce}from"../../shader/graph/index.js";export async function materializeVfx(t,a,r,s,o,l,c,p,u){let h=a;for(;null!=h.parent;)h=h.parent;const d=new n;d.name="particle system local",a.add(d);const m=new n;m.name="particle system world";const f=new te(m,d,i,s),y=new e;return(await Promise.all(t.vfx.emitters.slice().sort((e,t)=>(t.output.renderOrder??0)-(e.output.renderOrder??0)).map(async e=>{const t=await pe(e,r,c,p,y,o,l,u,a);return t.setParentRecursive(y),t.emit()}))).forEach(e=>y.addEmitter(e)),y.addRenderer(f).emit({onEnd:()=>{}}),{container:m,system:y,dispose:()=>{m.removeFromParent(),d.removeFromParent(),f.dispose()}}}async function pe(e,t,r,p,v,x,P,T,D){const V=function(e){let t;switch(e.rate.type){case"continuous":t=new _(e.rate.delay??0,e.rate.count,e.rate.time,e.rate.duration);break;case"once":t=new K(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new s(0,1/0)}return t}(e);let F;switch(e.output.type){case"decal":F=new a(await async function(e,t,a,r,s){if("shaderGraph"===me(e)){const t=await de(e,"decal",a,r,s);if(null!=t){const a=new i.Mesh(new i.BoxGeometry(1,1,1),t);return null!=e.renderOrder&&(a.renderOrder=e.renderOrder),a}}const n=!1!==e.unlit?new ie:new ne;n.color=new i.Color(e.color),n instanceof ie?n.intensity=e.intensity??1:n.emissiveIntensity=e.intensity??1;if(e.colorMap){const a=await t.getTexture(e.colorMap);n.colorMap=a}if(e.alphaMap){const a=await t.getTexture(e.alphaMap);n.alphaMap=a}const o=n.build();o.blending=Z[e.blendingMode]??i.NormalBlending,o.transparent=!0,o.side=i.BackSide,o.depthTest=!1,null!=o&&!0===e.bloom&&(o.userData.hasBloom=!0);o.defines.IS_PARTICLE="";const l=new i.BoxGeometry(1,1,1),c=new i.Mesh(l,o);null!=e.renderOrder&&(c.renderOrder=e.renderOrder);return c}(e.output,t,r,p,P));break;case"sprite":F=new a(await async function(e,t,a,r,s){let n=null;const o=me(e);"shaderGraph"===o&&(n=await de(e,"sprite",a,r,s));null==n&&"shader"===o&&null!=e.shader&&(n=await he(e,t,s));null==n&&(n=await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):ue,r=C(a);let s=r.sample(j.uv);e.flipbook?.enabled&&(s=N(r,w.uv,e.flipbook.columns,e.flipbook.rows,q.time,e.flipbook.fps,e.flipbook.mode));const n=new u("rotation",0),o=new h("color").rgb,l=R("opacity",1),c=Q.subtract(W).divide(Q);let p=l;switch(e.opacityChannel??"red"){case"none":break;case"red":p=p.multiply(s.r);break;case"alpha":p=p.multiply(s.a)}if("number"==typeof e.softness&&e.softness>0){const t=b(c,0,1e3);p=p.multiply(I(0,.2*e.softness,t))}const d=re(n),m=S(o.multiply(s.rgb).multiplyScalar(e.intensity??1),p);var f=new se({color:m,emissive:m.rgb.multiplyScalar(p),transparent:!0,position:d,alphaTest:1e-4,uniforms:{color:{value:new i.Color(e.color)}}});f.alphaHash=!0,null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??i.NormalBlending,f}(e,t));fe(n,e);const l=new i.Mesh(new i.PlaneGeometry(1,1),n);return l.name="sprite",l}(e.output,t,r,p,P));break;case"stretchedSprite":F=new a(await async function(e,t){"shaderGraph"===me(e)&&console.warn("Shader graph materials are not supported for stretched sprite VFX outputs yet. Falling back to the default stretched sprite material.");const a=null!=e.texture?await t.getTexture(e.texture):ue,r=C(a).sample(j.uv),s=G(new l("color")),n=s.rgb.multiply(r.rgb);let o=s.w;switch(e.opacityChannel??"red"){case"none":break;case"red":o=o.multiply(r.r);break;case"alpha":o=o.multiply(r.a)}if("number"==typeof e.softness&&e.softness>0){const t=Q.subtract(W).divide(M(Q)),a=b(t,0,1e3);o=o.multiply(I(0,.2*e.softness,a))}const c=E(m,{position:w.position,offset:y("offset"),modelViewMatrix:B.modelViewMatrix,velocity:g("velocity"),size:y("size"),rotation:f("rotation")},"\n float lengthFactor = velocity.w;\n float avgSize = (size.x + size.y) * 0.5;\n\n vec4 mvPosition = modelViewMatrix * vec4( offset , 1.0 );\n vec3 viewVelocity = normalMatrix * velocity.xyz;\n float vlength = length(viewVelocity); \n mvPosition.xyz += position.y * normalize(cross(mvPosition.xyz, viewVelocity)) * avgSize; \n mvPosition.xyz -= (position.x + 0.5) * viewVelocity * (1.0 + lengthFactor / vlength) * avgSize;\n return projectionMatrix * mvPosition;\n ");var p=new se({color:S(n.multiplyScalar(e.intensity??1),o),alphaTest:.1,transparent:!0,position:c,uniforms:{color:{value:new i.Color(e.color)}}});null!=p&&!0===e.bloom&&(p.userData.hasBloom=!0);p.blending=Z[e.blendingMode]??i.NormalBlending;const u=new Y(new i.PlaneGeometry(1,1),p);return u.scaleFactor=e.scale,u}(e.output,t));break;case"shape":F=new a(await async function(e,t,a,r,s){if(null==e.shape)return console.log("Shape is null"),new n;const l=O[e.shape];if(null==l)return console.error(`No shape with type ${e.shape}`),new n;const p=z(e.params??{}),u=l.geometry(p);let h=null;const m=me(e);"shaderGraph"===m&&(h=await de(e,"surface",a,r,s));null==h&&"shader"===m&&null!=e.shader&&(h=await he(e,t,s));null==h&&(h="material"===m&&null!=e.material?ye(await t.getMaterial(e.material)):function(){const e=k(new d("instanceColor")).rgb,t=k(new o("particleData")).x;return new c({color:A({color:e}).rgb.rgba(t),opacity:t,transparent:!0})}());return fe(h,e),new i.Mesh(u,h)}(e.output,t,r,p,P));break;case"mesh":F=new a(await async function(e,t,a,r,s){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new n;const o=await t.getMesh(e.assetId),l=await t.getAsset(e.assetId),c=me(e);if("shaderGraph"===c||"shader"===c||"material"===c){let n;"shaderGraph"===c?n=await de(e,"surface",a,r,s):"shader"===c&&null!=e.shader?n=await he(e,t,s):"material"===c&&null!=e.material&&(n=ye(await t.getMaterial(e.material))),fe(n,e),o.traverse(e=>{e instanceof i.Mesh&&null!=n&&(e.material=n)})}else{const e=[];if(null!=l.materialAssignments)for(const a of l.materialAssignments)o.traverse(r=>{r instanceof i.Mesh&&r.material instanceof i.Material&&r.material.color instanceof i.Color&&(r.material.name!=a.name&&null!=a.name||"#"+r.material.color.getHexString()!==a.color||e.push(t.getMaterial(a.materialId).then(e=>r.material=e)))});await Promise.all(e)}const p=[];if(o.traverse(e=>{e instanceof i.Mesh&&p.push(e)}),1===p.length){const e=p[0];return e.updateWorldMatrix(!0,!0),e.updateMatrixWorld(),e.matrix.copy(e.matrixWorld),e.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.removeFromParent(),e}return o}(e.output,t,r,p,P));break;case"trail":{const s="shaderGraph"===me(e.output)?await de(e.output,"trail",r,p,P,{trailBillboard:e.output.billboard??!1}):null;F=new a({type:"trail",taper:e.output.taper,headGeometry:null,material:s instanceof i.ShaderMaterial?s:void 0,dragTexture:!1,texture:null!=e.output.texture?await t.getTexture(e.output.texture):null,opacityChannel:e.output.opacityChannel,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,intensityEnd:e.output.intensityEnd??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom,scrollSpeed:e.output.scrollSpeed,width:e.output.width,billboard:e.output.billboard??!1});break}default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const H=new we(D);H.parent=v,H.setRate(V),H._space=e.output.space;const U=await Promise.all(e.initializers.filter(e=>!1!==e.enabled).filter(e=>null!=ee[e.type]).map(async e=>{const t=ee[e.type],a=await z(e.params??{});return le(t,e.params??{},a,T)}));U.push(F,new X),H.addInitializers(U);const J=await Promise.all(e.behaviours.filter(e=>!1!==e.enabled).filter(e=>null!=$[e.type]).map(async e=>{const t=$[e.type];for(const[a,r]of Object.entries(e.params))t.parameters&&null!=t.parameters[a]&&"curve"===t.parameters[a].type&&r.type!==L.Curve&&(r.type=L.Curve);const a=await z(e.params??{},r,p);return oe(t,e.params??{},a,T)}).sort((e,t)=>e instanceof ae?1:0));J.push(new ge);for(const e of J)e instanceof ae&&(e.physics=x);H.addBehaviours(J);for(const a of e.children??[]){const e=await pe(a,t,r,p,v,x,P,T,D),s=new EmitterPool(()=>{const t=e.clone();return t.onExpired=()=>{const e=H.childEmitters.findIndex(e=>e.id===t.id);-1!=e&&H.childEmitters.splice(e,1),null!=t.parentParticle&&(n.delete(t.parentParticle.id),t.parentParticle=null),s.release(t)},t}),i=H.eventDispatcher,n=new Map;H.bindEmitterEvent=!0,i.addEventListener("PARTICLE_DEAD",e=>{const t=n.get(e.id);null!=t&&(H.detachChildEmitterFromParticle(t,e),n.delete(e.id))});let o="PARTICLE_CREATED";if("spawnEvent"in a)switch(a.spawnEvent){case"collision":o="PARTICLE_COLLISION";break;case"start":o="PARTICLE_CREATED"}i.addEventListener(o,e=>{const t=s.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),H.childEmitters.push(t),n.set(e.id,t),t.parentParticle=e,t.system=H.system,t.emit()})}return H}const ue=(new i.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");async function he(e,t,a){const r=a.get(e.shader);if(null==r)return console.error("No shader exists with name "+e.shader),new i.Material;const s=new r.type,n=await V(e.shaderParams??{},r.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0,void 0,s);return Object.assign(s,n),s.build()}async function de(e,t,a,r,s,i={}){const n=e.shaderGraph;if("asset"!==n?.source||null==n.assetId)return console.warn(`Missing shader graph asset reference for ${e.type} VFX output`),null;const o=await a.getAsset(n.assetId),l=o?.shaderGraph;if(null==l)return console.warn(`Missing shader graph asset "${n.assetId}" for ${e.type} VFX output`),null;if(l.target!==t)return console.warn(`Shader graph "${o.name}" targets "${l.target}" but ${e.type} VFX output expects "${t}"`),null;try{const t=await F(e.shaderGraphParams??{},l,a,r,void 0,s.shaders),o=ce(l,{parameters:t,trailBillboard:i.trailBillboard});return o.userData.customShaderName=`shaderGraph:${n.assetId}`,fe(o,e),o}catch(e){return console.log("Shader graph VFX runtime error: "+e,e),null}}function me(e){return null!=e.materialSource?e.materialSource:"asset"===e.shaderGraph?.source?"shaderGraph":"shader"in e&&null!=e.shader?"shader":"mesh"!==e.type&&"shape"!==e.type||null==e.material?"default":"material"}function fe(e,t){null!=e&&("bloom"in t&&!0===t.bloom&&(e.userData.hasBloom=!0),"sprite"===t.type?(e.blending=Z[t.blendingMode]??i.NormalBlending,!0===t.lockY&&e instanceof i.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.LOCK_Y_AXIS="")):"decal"===t.type&&(e.blending=Z[t.blendingMode]??i.NormalBlending,e.transparent=!0,e.side=i.BackSide,e.depthTest=!1,e instanceof i.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.IS_PARTICLE="")))}function ye(e){const t=k(new d("instanceColor")).rgb;let a,r=k(new o("particleData")).x;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial){let s=t.multiply(P(e.color));null!=e.map&&(s=s.multiply(C(e.map).sample(j.uv).rgb)),null!=e.alphaMap&&(r=r.multiply(C(e.alphaMap).sample(j.uv).r)),e instanceof i.MeshStandardMaterial?a=new c({color:T({color:s,emissive:P(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(r),emissive:P(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}):e instanceof i.MeshLambertMaterial?a=new c({color:A({color:s}).rgb.rgba(r),emissive:P(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}):e instanceof i.MeshBasicMaterial&&(a=new c({color:s.rgb.rgba(r),emissive:s.rgb,transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}))}else e instanceof c&&(a=e.clone(),a.defines.IS_PARTICLE="");return null!=a&&(!0===e.userData?.hasBloom&&null!=a&&(a.userData.hasBloom=!0),a.side=e.side,a.transparent=e.transparent),a??e}class ge extends t{initialize(e){e.body instanceof i.Object3D&&e.body.traverse(e=>{if(e instanceof i.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[H]||null!=t.uniforms[U]||t.uniforms[J])}})}mutate(e,t,a){this.energize(e,t),e.target instanceof n&&e.target.traverse(t=>{if(t instanceof i.Mesh){const a=t.material;a instanceof c&&(null!=a.uniforms[H]&&(a.uniforms[H].value=this.energy),null!=a.uniforms[U]&&(a.uniforms[U].value=e.age),null!=a.uniforms[J]&&(a.uniforms[J].value=e.velocity))}})}}class we extends r{constructor(e){super(),this.transformRoot=e,this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}clearParticlesRecursive(){let e=this.childEmitters.length;for(;e--;){const t=this.childEmitters[e];t.stopEmit(),t.clearParticlesRecursive(),t.onExpired()}this.childEmitters.length=0;let t=this.particles.length;for(;t--;){const e=this.particles[t];this.system?.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),null!=this.system?this.system.pool.expire(e.reset()):e.reset()}this.particles.length=0}detachChildEmitterFromParticle(e,t){this.copyPositionToChildSpace(e,t.position),e.parentParticle=null,e.stopEmit()}update(e){if(!this.isEmitting&&0===this.particles.length&&0===this.childEmitters.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.isEmitting&&this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||0!==this.childEmitters.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle&&this.copyPositionToChildSpace(t,t.parentParticle.position),t.update(e)}copyPositionToChildSpace(e,t){const a=this._space??"world",r=e._space??"world";a!==r&&null!=this.transformRoot?(be.copy(t),"local"===a&&"world"===r?be.applyMatrix4(this.transformRoot.matrixWorld):"world"===a&&"local"===r&&(ve.copy(this.transformRoot.matrixWorld).invert(),be.applyMatrix4(ve)),e.position.copy(be)):e.position.copy(t)}clone(){const e=new we(this.transformRoot);return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach(t=>t.setParentRecursive(e))}}const be=new i.Vector3,ve=new i.Matrix4;export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
package/dist/gameplay/inject.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import t from"typedi";import{activeContainerInstance as e}from"./actors/internal/container-map.js";export function inject(n){return e.value?.get(n)??t.get(n)}export function withInjectionContext(t,n){const
|
|
1
|
+
import t from"typedi";import{activeContainerInstance as e}from"./actors/internal/container-map.js";export function inject(n){return e.value?.get(n)??t.get(n)}export function withInjectionContext(t,n){const r=e.value;e.value=t;try{return n(t)}finally{e.value=r}}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
package/dist/rendering.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as a,Material as n,Matrix4 as r,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as p,WebGLRenderTarget as u,Texture as d,Euler as c,MeshStandardMaterial as m}from"three";import{CopyShader as f,EffectComposer as g,FXAAShader as M,GammaCorrectionShader as v,LUTPass as P,RenderPass as b,ShaderPass as y,VRButton as T}from"three-stdlib";import{CSMShader as w,CSMUtil as x}from"./csm.js";import{colorToNormal as S,float as C,NodeShaderMaterial as R,standardMaterial as O,uniformFloat as U,uniformVec3 as E,toonMaterial as A,lambertMaterial as G,normalize as F,rgb as D,rgba as B,transformed as I,varying as L,varyingAttributes as V,varyingTransformed as _,vec4 as W,BooleanExpression as j,select as N,ifDefApply as q,uniformSampler2d as k,RgbaNode as z,mix as H,attributes as $,uniformVec2 as X}from"three-shader-graph";import{Reflector as Y}from"three-stdlib";import{BokehPass as K,OutputPass as Q}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 ne,resolutionUniformName as re,sceneNormalUniformName as oe,screenUV as le,supportsDepthTextureExtension as he}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as pe}from"./shader-nodes/time.js";import{aoMapUniformName as ue,sceneMapUniformName as de}from"./shader-nodes/scene-sample.js";import{DepthPass as ce}from"./utils/three/depth-pass.js";import{GPUStatsPanel as me}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as fe}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as ge,traverseVisibleStop as Me}from"./utils/three/traverse.js";import{clamp as ve}from"./utils/math.js";import{ColorPass as Pe}from"./rendering/color-pass.js";import{PostProcessEffectPass as be,PostProcessEffectRegistration as ye,postProcessEffectStages as Te,sanitizePostProcessEffectPriority as we,sanitizePostProcessEffectStage as xe}from"./rendering/post-process-effect.js";import{SSRPass as Se}from"./rendering/ssr/SSRPass.js";import{SSRShader as Ce}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as Re}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as Oe}from"./rendering/outline-effect.js";import{UnrealBloomPass as Ue}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as Ee}from"./shader-nodes/depth.js";import{packDepthToRGBA as Ae}from"three-shader-graph";import{FogVolumeObject as Ge}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Fe}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as De}from"./shader-nodes/pom.js";import{FullScreenQuad as Be}from"three-stdlib";import{edgeDepthEffect as Ie}from"./shader-nodes/effects";import{decalDiscard as Le}from"./shader-nodes/decal.js";import{Pass as Ve}from"three/examples/jsm/Addons.js";import{BatchedMesh2 as _e}from"./scene/batched-mesh-2.js";import{applyUvTiling as We}from"./shader/uv-nodes.js";x.patchSetupMaterial();const je=document.createElement("div");je.style.position="absolute",je.style.left="50%",je.style.top="50%",je.style.color="black",je.style.zIndex="999";(new i.Layers).set(9);const Ne=new i.MeshBasicMaterial({color:"black"}),qe=new i.MeshDepthMaterial;var ke;qe.depthPacking=i.RGBADepthPacking,qe.blending=i.NoBlending,qe.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(ke||(ke={}));const ze=(()=>{const e=new Uint8Array([255,255,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),He=(()=>{const e=new Uint8Array([0,0,0,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),$e=(()=>{const e=new Uint8Array([128,128,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Xe=new R({color:C(0),position:W(C(0))});Xe.visible=!1;const Ye=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let Ke=0,Qe=null;const Je=new Map;function Ze(){return null==Qe&&(Qe=new IntersectionObserver(e=>{for(const t of e){const e=Je.get(t.target);e&&e(t.isIntersecting)}},{threshold:0})),Qe}let et=e=class{get fpsCap(){return this._fpsCap}set fpsCap(e){const t=null!=e&&Number.isFinite(e)&&e>0?e:null;t!==this._fpsCap&&(this._fpsCap=t,this.fpsCapRevision++)}setPaused(e){this.paused=e}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)}addPostProcessEffect(e,t={}){const s={id:++this.postProcessEffectId,pass:new be(e),priority:we(t.priority),stage:xe(t.stage)};return s.pass.enabled=t.enabled??!0,this.postProcessEffects.push(s),this.refreshPostProcessEffectPassOrder(),new ye(this,s)}removePostProcessEffectEntry(e){const t=e,s=this.postProcessEffects.indexOf(t);-1!==s&&(this.postProcessEffects.splice(s,1),this.composer.removePass(t.pass),t.pass.dispose())}refreshPostProcessEffectPassOrder(){for(const e of this.postProcessEffects)this.composer.removePass(e.pass);for(const e of Te){const t=this.getPostProcessEffectStageAnchorPass(e),s=null!=t?this.composer.passes.indexOf(t):this.composer.passes.length,i=this.postProcessEffects.filter(t=>t.stage===e).sort(it);for(let e=0;e<i.length;e++)this.composer.insertPass(i[e].pass,s+e)}}getPostProcessEffectStageAnchorPass(e){switch(e){case"beforeFog":return this.volumetricFogPass;case"beforeDepthOfField":return this.dofPass;case"beforeColorAdjustment":return this.colorPass;case"beforeOutline":return this.outlinePass;case"beforeAntiAliasing":return this.fxaaPass;case"beforeLut":return this.lutPass;case"beforeOutput":return this.outputPass}}constructor(t,s={}){this.container=t,this.options=s,this.isIntersecting=!1,this.windowVisible=!0,this.running=!0,this.paused=!1,this._fpsCap=null,this.fpsCapRevision=0,this.postProcessVolumes=[],this.postProcessSettings={},this.baseToneMapping=i.NoToneMapping,this.baseToneMappingExposure=1,this.csmUpdateInvervals=this.options.shadows?.cascadeUpdateIntervals,this._id=Ke++,this.postProcessEffectId=0,this.postProcessEffects=[],this.postProcessEffectResolution=new i.Vector2(1,1),this.postProcessEffectUniformState={aoEnabled:!1,aoTexture:null,cameraFar:void 0,cameraNear:void 0,depthTexture:new d,normalTexture:new d,resolution:this.postProcessEffectResolution,simulationTime:0},this.fquadCopy=new Be(new p(f)),this.fquadCopyOpaque=new Be(new R({outputs:[k("tSceneColor",new d).sample(V.uv),W(k("tDepthTexture",new i.DepthTexture(1,1)).sample(V.uv).r)]})),this.simulationTime=0,this.simulationTimeScale=1,this.lightProbeIntensity=2,this.fquadBlendAO=(()=>{const e=W(1),t=new R({outputs:[k("tAO",new d).sample(le),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Be(t)})(),this.resolutionScale=1,this.maxPixelRatio=Ye?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.gbufferDepthPrepassMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.depthPrepassMaterialCache=new WeakMap,this.depthPrepassCachedMaterials=new Map,this.depthPrepassCachedVisibility=[],this.gBufferCachedMaterials=new Map,this.gBufferCachedVisibility=[],this._initiatedMaterialTextures=new Set,this._initiatedTextures=new Set,this.compileInProgress=!1,this.pmremGeneratorResults=new WeakMap,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new a,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,this.fpsCap=s.fpsCap,e.activeView=this,Z.init(),window.renderer=this.renderer=window.renderer??new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}.bind(this.scene),this.renderer.setPixelRatio(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(T.createButton(this.renderer));const n=new Oe(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=n,this.createGRenderTarget(),this.composer=new g(this.renderer),this.composer.setSize(t.clientWidth,t.clientHeight);var r=(t.clientWidth||1)/(t.clientHeight||1);const o=new i.PerspectiveCamera(45,r,.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.baseToneMapping=this.renderer.toneMapping,this.baseToneMappingExposure=this.renderer.toneMappingExposure,this.renderer.gammaFactor=1.4,x.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 b(this.scene,this.camera),new y(f,"prevtexture"));h.enabled=!0,h.needsSwap=!0,h.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=h;const u=new Ue(l,1.5,.4,.85);u.threshold=1,u.strength=.9,u.radius=.5,this.bloomPass=u;const c=new te(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});c.normalRenderTarget?.dispose(),c.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),c.output=te.OUTPUT.Off,c.enabled=!1,this.aoPass=c,this.fquadBlendAO.material.uniforms.tAO.value=c.pdRenderTarget.texture,Ce.fragmentShader=Ce.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const m=new Se({renderer:this.renderer,scene:this.scene,camera:this.camera,width:this.gRenderTarget.width,height:this.gRenderTarget.height,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[2],depthTexture:this.gRenderTarget.depthTexture});m.output=Se.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(c);const w=new Tt((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 Tt((e,t,s,i,a)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(ke.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(S),this.composer.addPass(h),this.composer.addPass(m),this.phasedRenderPass=new yt(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(u),u.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new Re(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new K(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const C=new Pe;this.composer.addPass(C),this.colorPass=C,C.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 O=new y(M);O.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(O),this.fxaaPass=O,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new y(v).clear=!1,this.fixStatsStyle(),this.lutPass=new P({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const U=new y(f,"prevtexture");U.enabled=!0,U.needsSwap=!1,U.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],U.renderToScreen=!0;const E=new Q;this.outputPass=E,this.composer.addPass(E)}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 b?t.camera=e:t instanceof fe?t.renderCamera=e:(t instanceof ce||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:80,lightFar:250,lightMargin:20,cascades:Ye?2:3,shadowMapSize:2048*(Ye?.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)),n=Math.max(1,Math.floor(t.clientHeight*s)),r=new i.WebGLRenderTarget(a,n);return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new i.DepthTexture(a,n),r.depthTexture.type=i.UnsignedShortType,r.depthTexture.minFilter=i.NearestFilter,r.depthTexture.magFilter=i.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t){const s=Math.max(1,t.clientWidth*e.getPixelRatio()),a=Math.max(1,t.clientHeight*e.getPixelRatio()),n=new i.DepthTexture(s,a);n.type=i.UnsignedInt248Type,n.minFilter=i.NearestFilter,n.magFilter=i.NearestFilter;const r=new i.WebGLRenderTarget(s,a,{type:i.HalfFloatType,depthTexture:n});return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r}createSceneColorRenderTarget(e,t){const s=this.gRenderTarget.width,a=this.gRenderTarget.height,n=new i.WebGLRenderTarget(s,a,{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return n.texture.minFilter=i.LinearFilter,n.texture.magFilter=i.LinearFilter,n.texture.generateMipmaps=!1,n.textures[1].minFilter=i.NearestFilter,n.textures[1].magFilter=i.NearestFilter,n}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose();const t=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 u(t,s,{count:3,samples:this.options?.msaa??(Ye?void 0:2),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();for(const e of this.postProcessEffects)this.composer.removePass(e.pass),e.pass.dispose();this.postProcessEffects.length=0,this.container.replaceChildren();Ze().unobserve(this.container),Je.delete(this.container),this.volumetricFogPass.dispose(),x.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.findIndex(t=>t===e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.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 R&&(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:gt(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 R||e instanceof i.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateMaterialProperties(e,t){(e instanceof i.MeshBasicMaterial||e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(null!=t.uniforms.color&&t.uniforms.color.value.setFromColor(e.color),null!=t.uniforms.opacity&&(t.uniforms.opacity.value=e.opacity),null!=t.uniforms.map&&(t.uniforms.map.value=e.map),null!=t.uniforms.alphaMap&&(t.uniforms.alphaMap.value=e.alphaMap),null!=t.uniforms.lightMap&&(t.uniforms.lightMap.value=e.lightMap,t.uniforms.lightMapIntensity.value=e.lightMapIntensity),null!=t.uniforms.aoMap&&(t.uniforms.aoMap.value=e.aoMap,t.uniforms.aoMapIntensity.value=e.aoMapIntensity),null!=t.uniforms.alphaTest&&(t.uniforms.alphaTest.value=e.alphaTest)),(e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(t.uniforms.normalMap&&(t.uniforms.normalMap.value=e.normalMap,t.uniforms.normalScale.value=e.normalScale.x),t.uniforms.emissiveMap&&(t.uniforms.emissiveMap.value=e.emissiveMap,t.uniforms.emissive.value.setFromColor(e.emissive),t.uniforms.emissiveIntensity.value=e.emissiveIntensity)),e instanceof m&&(null!=t.uniforms.roughnessMap&&(t.uniforms.roughnessMap.value=e.roughnessMap),null!=t.uniforms.metalnessMap&&(t.uniforms.metalnessMap.value=e.metalnessMap),null!=t.uniforms.roughness&&(t.uniforms.roughness.value=e.roughness),null!=t.uniforms.metalness&&(t.uniforms.metalness.value=e.metalness)),e instanceof i.MeshPhysicalMaterial&&(t.uniforms.sheenColor&&t.uniforms.sheenColor.value.setFromColor(e.sheenColor).multiplyScalar(e.sheen),t.uniforms.sheenColorMap&&(t.uniforms.sheenColorMap.value=e.sheenColorMap),t.uniforms.sheenRoughness&&(t.uniforms.sheenRoughness.value=e.sheenRoughness),t.uniforms.sheenRoughnessMap&&(t.uniforms.sheenRoughnessMap.value=e.sheenRoughnessMap)),e instanceof Fe&&(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===wt.includes(e)&&(t.value=a)}this.updateMaterialCommonProperties(e,t)}inheritCustomUniformBindings(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s)null==i[e]&&("receiveShadow"===e||wt.includes(e)||xt.includes(e)||(i[e]={value:s[e].value}))}updateMaterialCommonProperties(e,t){t.alphaTest=e.alphaTest,t.side=e.side,t.depthTest=e.depthTest,t.blending=e.blending,t.colorWrite=e.colorWrite,t.premultipliedAlpha=e.premultipliedAlpha,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.visible=e.visible}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of wt){const t=i[e],a=s[e];null!=a&&null!=t&&(t.value=a.value)}}createGBufferMaterial(e,t,s=!1){const a=t===ke.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let n=a.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==n){let s=V.uv;if(e instanceof Fe&&null!=e.heightMap){const t=U("heightScale",e.heightScale??1);s=De(s,k("heightMap",e.heightMap),t)}let o=_.normal;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.normalMap??$e,i=U("useNormalMap",null!=e.normalMap?1:0),a=U("normalScale",e.normalScale?.x??1),n=S(k("normalMap",t).sample(We(s,e.normalMap)),a);o=H(_.normal,n,i)}else e instanceof R&&null!=e.outputNormal&&(o=e.outputNormal);!0!==e.userData.disableAO&&(o=q("DOUBLE_SIDED",o,e=>N(new j("gl_FrontFacing"),e,e.multiplyScalar(-1))));let l=e.userData?.reflective?C(0):C(1);if(e instanceof i.MeshStandardMaterial){const t=U("roughness",e.roughness??1),i=e.roughnessMap??ze,a=U("useRoughnessMap",null!=e.roughnessMap?1:0),n=k("roughnessMap",i).sample(We(s,e.roughnessMap)).g.multiply(t);l=H(t,n,a)}else e instanceof R&&null!=e.outputRoughness&&(l=e.outputRoughness);let h=null;if((e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial)&&null!=e.lightMap){const t=e.lightMap,i=U("useLightMap",null!=e.lightMap?1:0),a=U("lightMapIntensity",e.lightMapIntensity??1),n=k("lightMap",t).sample(s).rgb.multiplyScalar(a);h=H(D(0),n,i)}let u=C(0);if(e instanceof i.MeshStandardMaterial){const t=U("metalness",e.metalness??0),i=e.metalnessMap??He,a=U("useMetalnessMap",null!=e.metalnessMap?1:0),n=k("metalnessMap",i).sample(We(s,e.metalnessMap)).b.multiply(t);u=H(t,n,a)}else e instanceof R&&e.outputRoughness;let d=null,c=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??ze,i=U("useAoMap",null!=e.aoMap?1:0);c=U("aoMapIntensity",e.aoMapIntensity??1);const a=k("aoMap",t).sample(We(s,e.aoMap)).r;d=H(C(1),a,i)}else e instanceof R&&e.outputRoughness;const f=U("opacity",e.opacity??1);let g=C(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){if(null!=e.alphaMap){const t=e.alphaMap;g=k("alphaMap",t).sample(We(s,e.alphaMap)).r}g=g.multiply(f)}else e instanceof R&&null!=e.outputOpacity&&(g=e.outputOpacity);let M=B(0,1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){let t=E("color",(new i.Vector3).setFromColor(e.color));const a=e.map??ze,n=U("useAlbedoMap",null!=e.map?1:0),r=k("map",a).sample(We(s,e.map)),o=r.multiply(B(t,1)),l=B(t,1);M=H(l,o,n),e.vertexColors&&(M=M.multiply(W(L($.color.rgb),1)));const h=H(C(1),r.w,n);g=g.multiply(h)}const v=!0===e.userData.hasBloom;let P=D(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=E("emissive",(new i.Vector3).setFromColor(e.emissive)),a=U("emissiveIntensity",e.emissiveIntensity),n=e.emissiveMap??He,r=U("useEmissiveMap",null!=e.emissiveMap?1:0),o=k("emissiveMap",n).sample(We(s,e.emissiveMap)).rgb.multiply(t);P=H(t,o,r),P=P.multiplyScalar(a)}else e instanceof R&&null!=e.outputEmissive&&(P=e.outputEmissive);let b=null;if(e instanceof i.MeshPhysicalMaterial&&e.sheen>0&&(b=E("sheenColor",(new i.Vector3).setFromColor(e.sheenColor).multiplyScalar(e.sheen)),e.sheen>0&&null!=e.sheenColorMap)){const t=k("sheenColorMap",e.sheenColorMap).sample(s).rgb;b=b.multiply(t)}let y=null;if(e instanceof i.MeshPhysicalMaterial&&e.sheen>0&&(y=U("sheenRoughness",e.sheenRoughness),e.sheen>0&&null!=e.sheenRoughnessMap)){const t=k("sheenRoughnessMap",e.sheenRoughnessMap).sample(s).r;y=y.multiply(t)}let T=null;if(e instanceof i.MeshPhysicalMaterial&&e.anisotropy>0&&(T=U("anisotropy",e.anisotropy),e.anisotropy>0&&null!=e.anisotropyMap)){const t=k("anisotropyMap",e.anisotropyMap).sample(s).r;T=T.multiply(t)}let w=null;if(e instanceof i.MeshPhysicalMaterial&&e.anisotropy>0){const t=e.anisotropyRotation??0;w=X("anisotropyDirection",new i.Vector2(Math.cos(t),Math.sin(t)))}const x=e instanceof p&&null!=e.uniforms[ie],I=e instanceof p&&null!=e.uniforms[de],z=e instanceof p&&null!=e.uniforms[ue],Y=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,K=U("alphaTest",e.alphaTest);let Q,J=e.alphaTest>0?g.lt(K):Y&&t===ke.opaque?g.lt(.8):null;!0===e.userData.isDecal&&(J=J?J.or(Le):Le),Q=Y?W(0,0,0,0):(r=o,F(r).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?l:1);const Z=e instanceof R?e.outputPosition:void 0,ee=e instanceof R?e.outputTransform:void 0;let te,se=B("black",1);if(e instanceof R&&null!=e.outputColor)se=e.outputColor;else if(e instanceof i.MeshStandardMaterial)se=O({color:M,metalness:u,roughness:l,emissive:P.rgb,normal:o,ambientOcclusion:d,ambientOcclusionIntensity:c,bakedLight:h,sheenColor:b,sheenRoughness:y,anisotropy:T,anisotropyDirection:w});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)se=G({color:M.rgb,ambientOcclusion:d,ambientOcclusionIntensity:c});else if(e instanceof i.MeshBasicMaterial){let e=M.rgb,t=h??D("black");null!=d&&(t=t.multiplyScalar(d.subtract(1).multiply(c).add(1))),e=e.add(t),se=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(se=A({color:M,emissive:P.rgb,normal:o,ambientOcclusion:d,ambientOcclusionIntensity:c,bakedLight:h}));(e instanceof R||e instanceof i.MeshStandardMaterial)&&(te=e.envMap);let ae=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(ae=e.fog);let ne=B(se.rgb,g);ae&&(ne=new FogNode(ne));let re=!0;if(t===ke.opaque?(re&&(re=!x&&!I&&!z),re&&(re=!Y)):t===ke.transparent&&re&&(re=Y||x||I||z),!re)return n=Xe,a.set(e,n),n;n=new R({transform:ee,position:null==ee?Z:void 0,outputs:[ne,P.rgba(t===ke.opaque?K:v?1:0),Q],opacity:g,outputEncoding:!1,fog:ae,transparent:e.transparent,lights:!0,envMap:te,alphaTest:e.alphaTest,discard:J}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=n.uniforms.envMapIntensity&&(n.uniforms.envMapIntensity.value=e.envMapIntensity),"alphaMap"in e&&null!=e.alphaMap&&(n.alphaMap=e.alphaMap),(e instanceof R||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(n),e instanceof R&&(Object.assign(n.defines,e.defines),null!=n.uniforms[ue]&&(n.uniforms[ue].value=this.aoPass.pdRenderTarget.texture,n.defines.USE_SSAO_MAP="")),n.userData.mrtOutputs=3,n.forceSinglePass=e.forceSinglePass,n.side=e.side,n.blending=e.blending,Y?(n.depthWrite=!e.transparent,n.depthTest=e.depthTest,n.colorWrite=t===ke.transparent):(n.depthWrite=e.depthWrite,n.depthTest=e.depthTest),n.visible=e.visible,n.alphaTest=e.alphaTest,n.alphaHash=e.alphaHash,n.vertexColors=e.vertexColors,n.premultipliedAlpha=e.premultipliedAlpha,n.toneMapped=e.toneMapped,n.blendAlpha=e.blendAlpha,n.blendColor=e.blendColor,n.polygonOffset=e.polygonOffset,n.polygonOffsetFactor=e.polygonOffsetFactor,n.polygonOffsetUnits=e.polygonOffsetUnits,n.blending=e.blending,n.wireframe=e.wireframe??!1,n.userData.isGBufferMaterial=!0,n.visible=re,Object.assign(n.userData,e.userData),n.visible&&(this.csm.setupMaterial(n),e instanceof p&&this.inheritCustomUniformBindings(e,n)),a.set(e,n)}var r;return n.visible&&(e instanceof p?this.updateUniformValues(e,n):this.updateMaterialProperties(e,n)),this.initLightVolumeUniform(n),n}isDepthPrepassEnabled(){return!0===this.options.depthPrepass?.enabled}usesSceneFeedbackUniforms(e){return e instanceof p&&(null!=e.uniforms[ie]||null!=e.uniforms[de]||null!=e.uniforms[ue])}isDepthPrepassEligibleMaterial(e){return null!=e&&(!1!==e.visible&&!1!==e.depthTest&&!1!==e.depthWrite&&(!e.transparent&&e.blending!==i.AdditiveBlending&&(!this.usesSceneFeedbackUniforms(e)&&(e instanceof R||e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshBasicMaterial))))}isDepthPrepassEligibleMesh(e){return!!this.isDepthPrepassEnabled()&&((e instanceof i.InstancedMesh||e instanceof _e)&&(!Array.isArray(e.material)&&this.isDepthPrepassEligibleMaterial(e.material)))}createDepthPrepassMaterial(e){if(!this.isDepthPrepassEligibleMaterial(e))return null;let t=this.depthPrepassMaterialCache.get(e);if(null==t){let s,a=C(1);e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(a=U("opacity",e.opacity??1),null!=e.map&&(a=a.multiply(k("map",e.map).sample(V.uv).a)),null!=e.alphaMap&&(a=a.multiply(k("alphaMap",e.alphaMap).sample(V.uv).r))):e instanceof R&&(a=e.outputOpacity??C(1)),null!=e.alphaTest&&e.alphaTest>0&&(s=a.lt(e.alphaTest));const n=e instanceof R?e.outputPosition:void 0,r=e instanceof R?e.outputTransform:void 0;t=new R({outputs:[B(0,0),B(0,0),B(0,0)],opacity:a,transform:r,position:null==r?n:void 0,discard:s,lights:!1,fog:!1,outputEncoding:!1,transparent:!1,alphaTest:e.alphaTest}),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=i.NoBlending,t.lights=!1,t.fog=!1,t.toneMapped=!1,t.side=e.side,t.alphaTest=e.alphaTest,t.visible=e.visible,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.onBeforeCompile=()=>{},t.customProgramCacheKey=()=>`depth-prepass:${e.id}:${e.version}:${e.alphaTest}:${e.side}`;for(const e of wt)delete t.uniforms[e];for(const e of xt)delete t.uniforms[e];delete t.uniforms.receiveShadow,this.depthPrepassMaterialCache.set(e,t)}return e instanceof R?this.updateUniformValues(e,t):this.updateMaterialProperties(e,t),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=i.NoBlending,t.visible=e.visible,t.alphaTest=e.alphaTest,t.side=e.side,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t}applyDepthPrepassMaterials(){const e=this.depthPrepassCachedMaterials,t=this.depthPrepassCachedVisibility;e.clear(),t.length=0,Me(this.scene,s=>{if(Pt(s))return t.push(s),s.visible=!1,!1;if(!(s instanceof o))return;if(e.set(s,s.material),!this.isDepthPrepassEligibleMesh(s))return t.push(s),void(s.visible=!1);const i=this.createDepthPrepassMaterial(s.material);if(null==i)return t.push(s),void(s.visible=!1);s.material=i,s.visible=!0})}unapplyDepthPrepassMaterials(){this.depthPrepassCachedMaterials.forEach((e,t)=>{t.material=e}),this.depthPrepassCachedVisibility.forEach(e=>{e.visible=!0})}renderDepthPrepass(){if(!this.isDepthPrepassEnabled())return;this.applyDepthPrepassMaterials();const e=this.scene.matrixWorldAutoUpdate,t=this.scene.matrixAutoUpdate,s=this.renderer.shadowMap.autoUpdate;this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clearDepth();try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Depth prepass render failed",e)}this.unapplyDepthPrepassMaterials(),this.renderer.shadowMap.autoUpdate=s,this.scene.matrixWorldAutoUpdate=e,this.scene.matrixAutoUpdate=t}updateCsm(){const e=this.csmUpdateInvervals;if(this.renderer.shadowMap.autoUpdate&&null!=this.csmCascadeLastUpdate&&Array.isArray(e)){const t=performance.now();for(let s=0;s<this.csm.lights.length;++s){const i=e[s]??e[e.length-1]??16;(t-this.csmCascadeLastUpdate[s]>=i||0===s)&&this.csm.lights[s].shadow&&(this.csm.lights[s].shadow.needsUpdate=!0,this.csmCascadeLastUpdate[s]=t)}}this.csm.update()}loop(t,s=!1){const a=this.stats,n=a.addPanel(new ee.Panel("Calls","#83f","#002")),l=a.addPanel(new ee.Panel("Triangles","#c32","#002"));let h;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(h=new me(this.renderer.getContext()),a.addPanel(h)),this.showStats=s;let p=10,u=1e3;const d=()=>{const e=this.renderer.info.render.calls;e>p&&(p=e,setTimeout(()=>p=10,5e3)),n.update(e,p);const t=this.renderer.info.render.triangles;t>u&&(u=t,setTimeout(()=>u=1e3,5e3)),l.update(t,u)};performance.now();i.Ray.prototype.intersectTriangle;this.resizeRender();const c=[],m=[],f=[];let g=0;const M=new r,v=new r;let P=0;let b=this.paused,y=!1,T=0,w=null,x=this.fpsCapRevision;const S=()=>{this.running&&!0!==this.options.enableXR&&requestAnimationFrame(U)},C=()=>{e.activeView=this,y&&(y=!1,requestAnimationFrame(()=>U(T)))},O=Ze();Je.set(this.container,e=>{this.isIntersecting=e,e&&C()}),O.observe(this.container),this.container.addEventListener("pointerdown",()=>{C()},{capture:!0});const U=s=>{y=!1;const n=this.renderer.getContext();if(!this.running||null===this.container.offsetParent||this.paused&&n.drawingBufferHeight>1)return y=!0,T=s,setTimeout(()=>{y&&U(s)},500),void(this.paused&&(b=!0));if(this.renderer.domElement.parentElement!==this.container){if(e.activeView!==this&&null!==e.activeView)return y=!0,void(T=s);this.container.replaceChildren(this.renderer.domElement),this.resizeRender()}if(!0!==this.options.enableXR){x!==this.fpsCapRevision&&(x=this.fpsCapRevision,w=null);const e=this.fpsCap;if(null!=e){const t=1e3/e;if(null!=w){const e=s-w;if(e<t)return void S();w=s-e%t}else w=s}else w=s}this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),a.begin(),this.showStats&&h?.startQuery(),this.ssrPass.gpuPanel=h;let r=(s*=.001)-g;if(g=s,b&&(r=.016,b=!1),M.copy(this.camera.matrixWorld),r>1){let e=r;for(;e>.05;)t(tt),e-=tt;t(e)}else t(r);this.onLoopCallbacks.forEach(e=>e(r)),this.paused||(this.simulationTime+=r*this.simulationTimeScale);const l=this.simulationTime;this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),s-P>.08&&!v.equals(M)&&(this.renderer.shadowMap.needsUpdate=!0,P=s),this.updateCsm();let p=!1;c.length=0,m.length=0,f.length=0;const u=at;rt.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),u.setFromProjectionMatrix(rt);let C=!1,O=!1,E=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Ge&&(C=!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&&(p=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[ie])&&isObjectInFrustum(e,u)?(this.initDepthUniform(e.material),O=!0):e instanceof Y&&(e.visible=!1,m.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[ue]&&isObjectInFrustum(e,u)&&e.material instanceof R&&this.initAoUniform(e.material),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[de]&&isObjectInFrustum(e,u)&&(f.push(e),e.material.uniforms[de].value=this.sceneColorRenderTarget.texture,E=!0),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[pe])e.material.uniforms[pe].value=l;else if(e instanceof o&&Array.isArray(e.material))for(const t of e.material)t.uniforms&&null!=t.uniforms[pe]&&(t.uniforms[pe].value=l)}),this.bloomPass.enabled=p,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderDepthPrepass(),this.renderScene(ke.opaque),this.aoPass.output=te.OUTPUT.Off,(O||E)&&(this.fquadCopyOpaque.material.uniforms.tSceneColor.value=this.gRenderTarget.textures[0],this.fquadCopyOpaque.material.uniforms.tDepthTexture.value=this.gRenderTarget.depthTexture,this.initResolutionUniform(this.fquadCopyOpaque.material),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.clear(),this.fquadCopyOpaque.render(this.renderer),this.renderer.setRenderTarget(this.gRenderTarget)),f.length,c.forEach(e=>e.visible=!0),m.forEach(e=>e.visible=!0),f.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=s),this.volumetricFogPass&&C?(this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene),this.volumetricFogPass.enabled=!0):this.volumetricFogPass&&(this.volumetricFogPass.enabled=!1),this.updatePostProcessEffectUniforms(l);try{!this.paused&&this.running&&(this.render(r),this.showStats&&h?.endQuery(),this.showStats&&d(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}a.end(),this.csm?.update(),S()};!0===this.options.enableXR?this.renderer.setAnimationLoop(U):requestAnimationFrame(U)}applyGBufferMaterials(e){const t=this.gBufferCachedMaterials,s=this.gBufferCachedVisibility;t.clear(),s.length=0;Me(this.scene,i=>{if(Pt(i))return s.push(i),i.visible=!1,!1;if(i instanceof o){t.set(i,i.material);let a=!1;if(Array.isArray(i.material)){i.material=i.material.slice();for(let t=0;t<i.material.length;t++)i.material[t]=this.createGBufferMaterial(i.material[t],e,e===ke.opaque&&this.isDepthPrepassEligibleMesh(i)),a||(a=i.material[t].visible),this.initShadowUniform(i,i.material[t])}else i.material=this.createGBufferMaterial(i.material,e,e===ke.opaque&&this.isDepthPrepassEligibleMesh(i)),a||(a=i.material.visible),this.initShadowUniform(i,i.material);a?i.visible=!0:null!=i.children&&0!=i.children.length||(s.push(i),i.visible=!1)}})}unapplyGBufferMaterials(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e}),this.gBufferCachedVisibility.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)})}initTextures(e=this.scene){e.traverse(e=>{if(e instanceof o)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++)this._initMaterialTextures(e.material[t]);else this._initMaterialTextures(e.material)})}_initMaterialTextures(e){if(!this._initiatedMaterialTextures.has(e))if(this._initiatedMaterialTextures.add(e),e instanceof p){for(const[t,s]of Object.entries(e.uniforms))if(s.value instanceof d){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 d){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(ke.opaque),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials(ke.transparent),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.isDepthPrepassEnabled()&&(this.renderer.setRenderTarget(this.gRenderTarget),this.applyDepthPrepassMaterials(),await this.renderer.compileAsync(e,this.camera),this.unapplyDepthPrepassMaterials()),e===this.scene&&(this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.compileAsync(this.fquadBlendAO.mesh,this.fquadBlendAO.camera),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.compileAsync(this.fquadCopyOpaque.mesh,this.fquadCopyOpaque.camera));const t=this.csm.lights[0]?.shadow.camera;null!=t&&(this.applyDepthMaterial(),await this.renderer.compileAsync(e,t),this.unapplyDepthMaterial()),this.compileInProgress=!1,this.renderer.setRenderTarget(null)}applyDepthMaterial(){const e=this.gBufferCachedMaterials;e.clear(),this.scene.traverse(t=>{(t.isMesh||t.isPoints||t.isLine||t.isSprite)&&(this.initCustomDepthMaterial(t),e.set(t,t.material),t.castShadow?null!=t.customDepthMaterial?t.material=t.customDepthMaterial:t.material=Ct: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!==ke.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===ke.opaque&&this.gBufferCachedMaterials.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof p&&this.updateLightUniformValues(t.material,e)}),this.unapplyGBufferMaterials(),this.renderer.shadowMap.autoUpdate=i,this.scene.matrixWorldAutoUpdate=t,this.scene.matrixAutoUpdate=s}getEnvTexture(e){null==this.pmremGenerator&&(this.pmremGenerator=new i.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader());let t=this.pmremGeneratorResults.get(e);return null==t&&(t=this.pmremGenerator.fromEquirectangular(e).texture,this.pmremGeneratorResults.set(e,t)),t.colorSpace=i.SRGBColorSpace,t}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure);!function(e,t=i.NoToneMapping,s=1){e.tonemapMapping=t,e.tonemapExposure=s,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=e.colorTint??new i.Color("white"),e.colorTint.set("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.globalSaturation=ot(e.globalSaturation,1,1,1),e.globalContrast=ot(e.globalContrast,1,1,1),e.globalGamma=ot(e.globalGamma,1,1,1),e.globalGain=ot(e.globalGain,1,1,1),e.globalOffset=ot(e.globalOffset,0,0,0),e.shadowsSaturation=ot(e.shadowsSaturation,1,1,1),e.shadowsContrast=ot(e.shadowsContrast,1,1,1),e.shadowsGamma=ot(e.shadowsGamma,1,1,1),e.shadowsGain=ot(e.shadowsGain,1,1,1),e.shadowsOffset=ot(e.shadowsOffset,0,0,0),e.shadowsMax=.09,e.midtonesSaturation=ot(e.midtonesSaturation,1,1,1),e.midtonesContrast=ot(e.midtonesContrast,1,1,1),e.midtonesGamma=ot(e.midtonesGamma,1,1,1),e.midtonesGain=ot(e.midtonesGain,1,1,1),e.midtonesOffset=ot(e.midtonesOffset,0,0,0),e.highlightsSaturation=ot(e.highlightsSaturation,1,1,1),e.highlightsContrast=ot(e.highlightsContrast,1,1,1),e.highlightsGamma=ot(e.highlightsGamma,1,1,1),e.highlightsGain=ot(e.highlightsGain,1,1,1),e.highlightsOffset=ot(e.highlightsOffset,0,0,0),e.highlightsMin=.5,e.lut=void 0,e.lutIntensity=0}(this.postProcessSettings,this.baseToneMapping,this.baseToneMappingExposure);const e=this.postProcessSettings;let t,s=!1;if(null==this.camera)return;const a=this.camera.getWorldPosition(ut);let n=[];for(const r of this.postProcessVolumes){if(!st(r.object))continue;let o=r.blendWeight??1;const l=r.distanceToPoint(a);l>r.blendRadius||(r.blendRadius>0&&(o*=ve(1-l/r.blendRadius,0,1)),o>1&&(o=1),o>0&&(n.push(r),void 0!==r.settings.tonemapMapping&&(e.tonemapMapping=r.settings.tonemapMapping),void 0!==r.settings.tonemapExposure&&(e.tonemapExposure=i.MathUtils.lerp(e.tonemapExposure,r.settings.tonemapExposure,o)),void 0!==r.settings.envTexture&&(e.envTexture=r.settings.envTexture),void 0!==r.settings.envIntensity&&(e.envIntensity=i.MathUtils.lerp(e.envIntensity,r.settings.envIntensity,o)),void 0!==r.settings.vignetteIntensity&&(e.vignetteIntensity=i.MathUtils.lerp(e.vignetteIntensity,r.settings.vignetteIntensity,o)),void 0!==r.settings.colorTint&&void 0!==r.settings.colorTintIntensity&&r.settings.colorTintIntensity>0&&(e.colorTint=e.colorTint.lerp(r.settings.colorTint,o)),void 0!==r.settings.colorTintIntensity&&(e.colorTintIntensity=i.MathUtils.lerp(e.colorTintIntensity,r.settings.colorTintIntensity,o)),void 0!==r.settings.depthFocus&&(s=!0,e.depthFocus=void 0!==e.depthFocus?i.MathUtils.lerp(e.depthFocus,r.settings.depthFocus,o):r.settings.depthFocus),void 0!==r.settings.depthAperture&&(s=!0,e.depthAperture=void 0!==e.depthAperture?i.MathUtils.lerp(e.depthAperture,r.settings.depthAperture,o):r.settings.depthAperture),void 0!==r.settings.depthMaxBlur&&(s=!0,e.depthMaxBlur=void 0!==e.depthMaxBlur?i.MathUtils.lerp(e.depthMaxBlur,r.settings.depthMaxBlur,o):r.settings.depthMaxBlur),void 0!==r.settings.temperature&&(e.temperature=i.MathUtils.lerp(e.temperature,r.settings.temperature,o)),void 0!==r.settings.temperatureTint&&(e.temperatureTint=i.MathUtils.lerp(e.temperatureTint,r.settings.temperatureTint,o)),void 0!==r.settings.globalSaturation&&e.globalSaturation.lerp(r.settings.globalSaturation,o),void 0!==r.settings.globalContrast&&e.globalContrast.lerp(r.settings.globalContrast,o),void 0!==r.settings.globalGamma&&e.globalGamma.lerp(r.settings.globalGamma,o),void 0!==r.settings.globalGain&&e.globalGain.lerp(r.settings.globalGain,o),void 0!==r.settings.globalOffset&&e.globalOffset.lerp(r.settings.globalOffset,o),void 0!==r.settings.shadowsSaturation&&e.shadowsSaturation.lerp(r.settings.shadowsSaturation,o),void 0!==r.settings.shadowsContrast&&e.shadowsContrast.lerp(r.settings.shadowsContrast,o),void 0!==r.settings.shadowsGamma&&e.shadowsGamma.lerp(r.settings.shadowsGamma,o),void 0!==r.settings.shadowsGain&&e.shadowsGain.lerp(r.settings.shadowsGain,o),void 0!==r.settings.shadowsOffset&&e.shadowsOffset.lerp(r.settings.shadowsOffset,o),void 0!==r.settings.shadowsMax&&(e.shadowsMax=i.MathUtils.lerp(e.shadowsMax,r.settings.shadowsMax,o)),void 0!==r.settings.midtonesSaturation&&e.midtonesSaturation.lerp(r.settings.midtonesSaturation,o),void 0!==r.settings.midtonesContrast&&e.midtonesContrast.lerp(r.settings.midtonesContrast,o),void 0!==r.settings.midtonesGamma&&e.midtonesGamma.lerp(r.settings.midtonesGamma,o),void 0!==r.settings.midtonesGain&&e.midtonesGain.lerp(r.settings.midtonesGain,o),void 0!==r.settings.midtonesOffset&&e.midtonesOffset.lerp(r.settings.midtonesOffset,o),void 0!==r.settings.highlightsSaturation&&e.highlightsSaturation.lerp(r.settings.highlightsSaturation,o),void 0!==r.settings.highlightsContrast&&e.highlightsContrast.lerp(r.settings.highlightsContrast,o),void 0!==r.settings.highlightsGamma&&e.highlightsGamma.lerp(r.settings.highlightsGamma,o),void 0!==r.settings.highlightsGain&&e.highlightsGain.lerp(r.settings.highlightsGain,o),void 0!==r.settings.highlightsOffset&&e.highlightsOffset.lerp(r.settings.highlightsOffset,o),void 0!==r.settings.highlightsMin&&(e.highlightsMin=i.MathUtils.lerp(e.highlightsMin,r.settings.highlightsMin,o)),void 0!==r.settings.lut&&(t=r.settings.lut),void 0!==r.settings.lutIntensity&&(e.lutIntensity=i.MathUtils.lerp(e.lutIntensity,r.settings.lutIntensity,o))))}if(0===n.length)return this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure);const r=e.vignetteIntensity>pt,o=(h=e.temperature,p=e.temperatureTint,!ht(h,6500)||!ht(p,0));var h,p;const u=(d=e.colorTint,e.colorTintIntensity>pt&&(!ht(d.r,1)||!ht(d.g,1)||!ht(d.b,1)));var d;const c=!(lt((m=e).globalSaturation,1,1,1)&<(m.globalContrast,1,1,1)&<(m.globalGamma,1,1,1)&<(m.globalGain,1,1,1)&<(m.globalOffset,0,0,0)&<(m.shadowsSaturation,1,1,1)&<(m.shadowsContrast,1,1,1)&<(m.shadowsGamma,1,1,1)&<(m.shadowsGain,1,1,1)&<(m.shadowsOffset,0,0,0)&<(m.midtonesSaturation,1,1,1)&<(m.midtonesContrast,1,1,1)&<(m.midtonesGamma,1,1,1)&<(m.midtonesGain,1,1,1)&<(m.midtonesOffset,0,0,0)&<(m.highlightsSaturation,1,1,1)&<(m.highlightsContrast,1,1,1)&<(m.highlightsGamma,1,1,1)&<(m.highlightsGain,1,1,1)&<(m.highlightsOffset,0,0,0));var m;const f=o||u||c||r,g=f&&e.tonemapMapping!==i.NoToneMapping,M=null!=t&&e.lutIntensity>pt;f?(this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1):(this.renderer.toneMapping=e.tonemapMapping,this.renderer.toneMappingExposure=e.tonemapExposure),null!=e.envTexture&&(this.scene.environment=this.getEnvTexture(e.envTexture)),this.scene.environmentIntensity=e.envIntensity,f?(this.colorPass.whiteBalanceEnabled=o,this.colorPass.whiteBalanceScale=o?function(e,t,s){const i=function(e){const t=ve(e,1e3,4e4)/100,s=t<=66?1:ve(1.292936186062745*Math.pow(t-60,-.1332047592),0,1),i=ve(t<=66?.3900815787690196*Math.log(t)-.6318414437886275:1.129890860895294*Math.pow(t-60,-.0755148492),0,1),a=t>=66?1:t<=19?0:ve(.5432067891101962*Math.log(t-10)-1.19625408914,0,1);return ct.set(s,i,a)}(t),a=1+.2*ve(s,-1,1),n=i.x,r=i.y*a,o=i.z,l=Math.max(r,1e-4);return e.set(1/Math.max(n/l,1e-4),1/Math.max(r/l,1e-4),1/Math.max(o/l,1e-4)),e}(dt,e.temperature,e.temperatureTint):dt.set(1,1,1),this.colorPass.vignetteIntensity=e.vignetteIntensity,this.colorPass.vignetteEnabled=r,this.colorPass.colorTintEnabled=u,this.colorPass.colorTint=e.colorTint,this.colorPass.colorTintIntensity=e.colorTintIntensity,this.colorPass.colorGradingEnabled=c,this.colorPass.toneMapping=e.tonemapMapping,this.colorPass.toneMappingEnabled=g,this.colorPass.toneMappingExposure=e.tonemapExposure,this.colorPass.globalSaturation=e.globalSaturation,this.colorPass.globalContrast=e.globalContrast,this.colorPass.globalGamma=e.globalGamma,this.colorPass.globalGain=e.globalGain,this.colorPass.globalOffset=e.globalOffset,this.colorPass.shadowsSaturation=e.shadowsSaturation,this.colorPass.shadowsContrast=e.shadowsContrast,this.colorPass.shadowsGamma=e.shadowsGamma,this.colorPass.shadowsGain=e.shadowsGain,this.colorPass.shadowsOffset=e.shadowsOffset,this.colorPass.shadowsMax=e.shadowsMax,this.colorPass.midtonesSaturation=e.midtonesSaturation,this.colorPass.midtonesContrast=e.midtonesContrast,this.colorPass.midtonesGamma=e.midtonesGamma,this.colorPass.midtonesGain=e.midtonesGain,this.colorPass.midtonesOffset=e.midtonesOffset,this.colorPass.highlightsSaturation=e.highlightsSaturation,this.colorPass.highlightsContrast=e.highlightsContrast,this.colorPass.highlightsGamma=e.highlightsGamma,this.colorPass.highlightsGain=e.highlightsGain,this.colorPass.highlightsOffset=e.highlightsOffset,this.colorPass.highlightsMin=e.highlightsMin,this.colorPass.enabled=!0):this.colorPass.enabled=!1,s&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==e.depthFocus&&(this.dofPass.uniforms.focus.value=e.depthFocus),void 0!==e.depthAperture&&(this.dofPass.uniforms.aperture.value=e.depthAperture),void 0!==e.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=e.depthMaxBlur)):this.dofPass.enabled=!1,this.lutPass.enabled=M,M&&(null!=t&&(t.flipY=!0,t.generateMipmaps=!1),this.lutPass.lut=t,this.lutPass.intensity=e.lutIntensity)}updatePostProcessEffectUniforms(e){if(0===this.postProcessEffects.length)return;const t=this.postProcessEffectUniformState;t.aoEnabled=this.aoPass.enabled,t.aoTexture=this.aoPass.enabled?this.aoPass.pdRenderTarget.texture:null,this.camera instanceof l?(t.cameraNear=this.camera.near,t.cameraFar=this.camera.far):(t.cameraNear=void 0,t.cameraFar=void 0),t.depthTexture=this.sceneColorRenderTarget.textures[1],t.normalTexture=this.gRenderTarget.textures[2],t.resolution.set(this.gRenderTarget.width,this.gRenderTarget.height),t.simulationTime=e;for(const e of this.postProcessEffects)e.pass.updateUniformState(t)}renderOverlay(){if(!this.running)return;if(0===this.overlayCameras.size)return;const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.previousClientWith/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof o&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,at)&&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===Ne.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=Ne:(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 p&&(e.uniforms[ie].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[ne]&&(e.uniforms[ne].value=this.camera.near),null!=e.uniforms[ae]&&(e.uniforms[ae].value=this.camera.far)))}initNormalUniform(e){e instanceof p&&null!=e.uniforms[oe]&&(e.uniforms[oe].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof R&&(t.uniforms.receiveShadow?t.uniforms.receiveShadow.value=e.receiveShadow:t.uniforms.receiveShadow={value:e.receiveShadow})}initLightVolumeUniform(e){e instanceof R&&(null!=this.lightVolume?null==e.uniforms.uSH?(e.defines.USE_LIGHT_PROBE_VOLUME="",e.uniforms.gridOrigin={value:this.lightVolume.gridOrigin},e.uniforms.gridSize={value:this.lightVolume.gridSize},e.uniforms.gridRes={value:this.lightVolume.gridResolution},e.uniforms.giIntensity={value:this.lightProbeIntensity},e.uniforms.uSH={value:this.lightVolume.shTexture},e.uniformsNeedUpdate=!0,e.needsUpdate=!0):e.uniforms.giIntensity.value=this.lightProbeIntensity:null!=e.uniforms.uSH&&(delete e.defines.USE_LIGHT_PROBE_VOLUME,delete e.uniforms.gridOrigin,delete e.uniforms.gridSize,delete e.uniforms.gridRes,delete e.uniforms.giIntensity,delete e.uniforms.uSH,e.uniformsNeedUpdate=!0,e.needsUpdate=!0))}initResolutionUniform(e){e instanceof p&&null!=e.uniforms[re]&&e.uniforms[re].value.set(this.gRenderTarget.width,this.gRenderTarget.height)}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[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 R&&!t.transparent&&t.depthWrite&&t.alphaTest>0))return;let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Ae(Ee);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new R({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}};et.activeView=null,et=e=t([se(),s("design:paramtypes",[HTMLElement,Object])],et);export{et as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const tt=.05;function st(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}function it(e,t){return e.priority!==t.priority?e.priority-t.priority:e.id-t.id}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 at=new i.Frustum,nt=new i.Box3,rt=new i.Matrix4;export function isObjectInFrustum(e,t){const s=nt.setFromObject(e);return t.intersectsBox(s)}function ot(e,t,s,a){return null==e?new i.Vector3(t,s,a):e.set(t,s,a)}function lt(e,t,s,i){return null!=e&&ht(e.x,t)&&ht(e.y,s)&&ht(e.z,i)}function ht(e,t,s=pt){return Math.abs(e-t)<=s}const pt=1e-4,ut=new i.Vector3,dt=new i.Vector3(1,1,1),ct=new i.Vector3(1,1,1);const mt=new r,ft=new c;function gt(e,t,s=new i.Matrix3){return ft.copy(e),ft.x*=-1,ft.y*=-1,ft.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(ft.y*=-1,ft.z*=-1),s.setFromMatrix4(mt.makeRotationFromEuler(ft))}const Mt=new R({outputs:[W(0,0,0,0),W(0,0,0,0),B(D("white"),Ie(4))],transparent:!0}),vt=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});Mt.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),vt);function Pt(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isLineSegments2||e.isTransformControls||e.isTransformControlsGizmo||e instanceof o&&bt(e,e.material)}function bt(e,t){return null==t||(Array.isArray(t)?t.some(t=>bt(e,t)):t instanceof i.RawShaderMaterial||t instanceof i.ShaderMaterial&&!(t instanceof R))}class yt extends Ve{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.cachedVisibility=[],this.toRender=[],this.needsSwap=!1}render(e,t,s,i,a){const n=e.autoClear;e.autoClear=!1;const r=this.scene.matrixWorldAutoUpdate,l=this.scene.matrixAutoUpdate,h=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const p=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),this.cachedVisibility.length=0;let u=0,d=this.toRender;if(d.length=0,this.scene.traverseVisible(e=>{const t=Pt(e);e instanceof o&&!t?(this.cachedVisibility.push(e),e.visible=!1):t&&(u++,d.push(e))}),u>0)for(const t of d)e.render(t,this.camera);this.cachedVisibility.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=n,s.depthTexture=p,this.scene.matrixWorldAutoUpdate=r,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class Tt extends Ve{constructor(e){super(),this.fn=e}render(e,t,s,i,a){this.fn(e,t,s,i,a)}}const wt=["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"],xt=["directionalShadowMap","directionalShadowMatrix","pointLightShadows","pointShadowMap","pointShadowMatrix","spotLightShadows","spotShadowMap"],St=E("fogColor");export class FogNode extends z{constructor(e,t=St){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),a=e.get(this.fogColor),n=e.get(U("fogFar")),r=e.get(U("fogNear")),o=e.get(U("fogDensity")),l=e.get(L(I.mvPosition.z));return{pars:"\n ",chunk:`\n #ifdef FOG_EXP2\n float fogFactor_${t} = 1.0 - exp( - ${o} * ${o} * ${l} * ${l} );\n #else\n float fogFactor_${t} = smoothstep( ${r}, ${n}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${a}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}const Ct=new i.MeshDepthMaterial({depthPacking:i.RGBADepthPacking});/*
|
|
1
|
+
var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as a,Material as n,Matrix4 as r,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as p,WebGLRenderTarget as d,Texture as u,Euler as c,MeshStandardMaterial as m}from"three";import{CopyShader as f,EffectComposer as g,FXAAShader as M,GammaCorrectionShader as v,LUTPass as P,RenderPass as b,ShaderPass as y,VRButton as T}from"three-stdlib";import{CSMShader as w,CSMUtil as x}from"./csm.js";import{colorToNormal as S,float as C,NodeShaderMaterial as R,standardMaterial as O,uniformFloat as U,uniformVec3 as E,toonMaterial as A,lambertMaterial as F,normalize as G,rgb as B,rgba as D,transformed as I,varying as L,varyingAttributes as V,varyingTransformed as _,vec4 as W,BooleanExpression as j,select as N,ifDefApply as q,uniformSampler2d as k,RgbaNode as H,mix as z,attributes as $,uniformVec2 as X}from"three-shader-graph";import{Reflector as Y}from"three-stdlib";import{BokehPass as K,OutputPass as Q}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 ne,resolutionUniformName as re,sceneNormalUniformName as oe,screenUV as le,supportsDepthTextureExtension as he}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as pe}from"./shader-nodes/time.js";import{aoMapUniformName as de,sceneMapUniformName as ue}from"./shader-nodes/scene-sample.js";import{DepthPass as ce}from"./utils/three/depth-pass.js";import{GPUStatsPanel as me}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as fe}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as ge,traverseVisibleStop as Me}from"./utils/three/traverse.js";import{clamp as ve}from"./utils/math.js";import{ColorPass as Pe}from"./rendering/color-pass.js";import{PostProcessEffectPass as be,PostProcessEffectRegistration as ye,postProcessEffectStages as Te,sanitizePostProcessEffectPriority as we,sanitizePostProcessEffectStage as xe}from"./rendering/post-process-effect.js";import{SSRPass as Se}from"./rendering/ssr/SSRPass.js";import{SSRShader as Ce}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as Re}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as Oe}from"./rendering/outline-effect.js";import{UnrealBloomPass as Ue}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as Ee}from"./shader-nodes/depth.js";import{packDepthToRGBA as Ae}from"three-shader-graph";import{FogVolumeObject as Fe}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Ge}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Be}from"./shader-nodes/pom.js";import{FullScreenQuad as De}from"three-stdlib";import{edgeDepthEffect as Ie}from"./shader-nodes/effects";import{decalDiscard as Le}from"./shader-nodes/decal.js";import{Pass as Ve}from"three/examples/jsm/Addons.js";import{BatchedMesh2 as _e}from"./scene/batched-mesh-2.js";import{applyUvTiling as We}from"./shader/uv-nodes.js";x.patchSetupMaterial();const je=document.createElement("div");je.style.position="absolute",je.style.left="50%",je.style.top="50%",je.style.color="black",je.style.zIndex="999";(new i.Layers).set(9);const Ne=new i.MeshBasicMaterial({color:"black"}),qe=new i.MeshDepthMaterial;var ke;qe.depthPacking=i.RGBADepthPacking,qe.blending=i.NoBlending,qe.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(ke||(ke={}));const He=(()=>{const e=new Uint8Array([255,255,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),ze=(()=>{const e=new Uint8Array([0,0,0,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),$e=(()=>{const e=new Uint8Array([128,128,255,255]),t=new i.DataTexture(e,1,1,i.RGBAFormat);return t.needsUpdate=!0,t})(),Xe=new R({color:C(0),position:W(C(0))});Xe.visible=!1;const Ye=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let Ke=0,Qe=null;const Je=new Map;function Ze(){return null==Qe&&(Qe=new IntersectionObserver(e=>{for(const t of e){const e=Je.get(t.target);e&&e(t.isIntersecting)}},{threshold:0})),Qe}let et=e=class{get fpsCap(){return this._fpsCap}set fpsCap(e){const t=null!=e&&Number.isFinite(e)&&e>0?e:null;t!==this._fpsCap&&(this._fpsCap=t,this.fpsCapRevision++)}setPaused(e){this.paused=e}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.setPixelRatio(this.renderer.getPixelRatio()),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)}addPostProcessEffect(e,t={}){const s={id:++this.postProcessEffectId,pass:new be(e),priority:we(t.priority),stage:xe(t.stage)};return s.pass.enabled=t.enabled??!0,this.postProcessEffects.push(s),this.refreshPostProcessEffectPassOrder(),new ye(this,s)}removePostProcessEffectEntry(e){const t=e,s=this.postProcessEffects.indexOf(t);-1!==s&&(this.postProcessEffects.splice(s,1),this.composer.removePass(t.pass),t.pass.dispose())}refreshPostProcessEffectPassOrder(){for(const e of this.postProcessEffects)this.composer.removePass(e.pass);for(const e of Te){const t=this.getPostProcessEffectStageAnchorPass(e),s=null!=t?this.composer.passes.indexOf(t):this.composer.passes.length,i=this.postProcessEffects.filter(t=>t.stage===e).sort(it);for(let e=0;e<i.length;e++)this.composer.insertPass(i[e].pass,s+e)}}getPostProcessEffectStageAnchorPass(e){switch(e){case"beforeFog":return this.volumetricFogPass;case"beforeDepthOfField":return this.dofPass;case"beforeColorAdjustment":return this.colorPass;case"beforeOutline":return this.outlinePass;case"beforeAntiAliasing":return this.fxaaPass;case"beforeLut":return this.lutPass;case"beforeOutput":return this.outputPass}}constructor(t,s={}){this.container=t,this.options=s,this.isIntersecting=!1,this.windowVisible=!0,this.running=!0,this.paused=!1,this._fpsCap=null,this.fpsCapRevision=0,this.postProcessVolumes=[],this.postProcessSettings={},this.baseToneMapping=i.NoToneMapping,this.baseToneMappingExposure=1,this.csmUpdateInvervals=this.options.shadows?.cascadeUpdateIntervals,this._id=Ke++,this.postProcessEffectId=0,this.postProcessEffects=[],this.postProcessEffectResolution=new i.Vector2(1,1),this.postProcessEffectUniformState={aoEnabled:!1,aoTexture:null,cameraFar:void 0,cameraNear:void 0,depthTexture:new u,normalTexture:new u,resolution:this.postProcessEffectResolution,simulationTime:0},this.fquadCopy=new De(new p(f)),this.fquadCopyOpaque=new De(new R({outputs:[k("tSceneColor",new u).sample(V.uv),W(k("tDepthTexture",new i.DepthTexture(1,1)).sample(V.uv).r)]})),this.simulationTime=0,this.simulationTimeScale=1,this.lightProbeIntensity=2,this.fquadBlendAO=(()=>{const e=W(1),t=new R({outputs:[k("tAO",new u).sample(le),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new De(t)})(),this.resolutionScale=1,this.maxPixelRatio=Ye?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.gbufferDepthPrepassMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.depthPrepassMaterialCache=new WeakMap,this.depthPrepassCachedMaterials=new Map,this.depthPrepassCachedVisibility=[],this.gBufferCachedMaterials=new Map,this.gBufferCachedVisibility=[],this._initiatedMaterialTextures=new Set,this._initiatedTextures=new Set,this.compileInProgress=!1,this.pmremGeneratorResults=new WeakMap,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new a,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,this.fpsCap=s.fpsCap,e.activeView=this,Z.init(),window.renderer=this.renderer=window.renderer??new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}.bind(this.scene),this.renderer.setPixelRatio(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(T.createButton(this.renderer));const n=new Oe(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=n,this.createGRenderTarget(),this.composer=new g(this.renderer,function(e,t){const s=new i.WebGLRenderTarget(Math.max(1,e),Math.max(1,t),{minFilter:i.LinearFilter,magFilter:i.LinearFilter,format:i.RGBAFormat,type:i.HalfFloatType});return s.texture.name="EffectComposer.rt1",s.texture.generateMipmaps=!1,s}(t.clientWidth,t.clientHeight)),this.composer.setPixelRatio(this.renderer.getPixelRatio()),this.composer.setSize(t.clientWidth,t.clientHeight);var r=(t.clientWidth||1)/(t.clientHeight||1);const o=new i.PerspectiveCamera(45,r,.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.baseToneMapping=this.renderer.toneMapping,this.baseToneMappingExposure=this.renderer.toneMappingExposure,this.renderer.gammaFactor=1.4,x.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 b(this.scene,this.camera),new y(f,"prevtexture"));h.enabled=!0,h.needsSwap=!0,h.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=h;const d=new Ue(l,1.5,.4,.85);d.threshold=1,d.strength=.9,d.radius=.5,this.bloomPass=d;const c=new te(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});c.normalRenderTarget?.dispose(),c.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),c.output=te.OUTPUT.Off,c.enabled=!1,this.aoPass=c,this.fquadBlendAO.material.uniforms.tAO.value=c.pdRenderTarget.texture,Ce.fragmentShader=Ce.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const m=new Se({renderer:this.renderer,scene:this.scene,camera:this.camera,width:this.gRenderTarget.width,height:this.gRenderTarget.height,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[2],depthTexture:this.gRenderTarget.depthTexture});m.output=Se.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(c);const w=new Tt((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 Tt((e,t,s,i,a)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(ke.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(S),this.composer.addPass(h),this.composer.addPass(m),this.phasedRenderPass=new yt(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 Re(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new K(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const C=new Pe;this.composer.addPass(C),this.colorPass=C,C.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 O=new y(M);O.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(O),this.fxaaPass=O,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new y(v).clear=!1,this.fixStatsStyle(),this.lutPass=new P({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const U=new y(f,"prevtexture");U.enabled=!0,U.needsSwap=!1,U.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],U.renderToScreen=!0;const E=new Q;!function(e){const t=e.material;if(t.dithering=!0,t.fragmentShader.includes("<dithering_fragment>"))return;const s="#include <colorspace_pars_fragment>";if(!t.fragmentShader.includes(s))return;t.fragmentShader=t.fragmentShader.replace(s,`${s}\n #include <common>\n #include <dithering_pars_fragment>`);const i=t.fragmentShader.lastIndexOf("}");i<0||(t.fragmentShader=`${t.fragmentShader.slice(0,i)}\n #include <dithering_fragment>\n${t.fragmentShader.slice(i)}`,t.needsUpdate=!0)}(E),this.outputPass=E,this.composer.addPass(E)}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 b?t.camera=e:t instanceof fe?t.renderCamera=e:(t instanceof ce||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:80,lightFar:250,lightMargin:20,cascades:Ye?2:3,shadowMapSize:2048*(Ye?.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)),n=Math.max(1,Math.floor(t.clientHeight*s)),r=new i.WebGLRenderTarget(a,n);return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new i.DepthTexture(a,n),r.depthTexture.type=i.UnsignedShortType,r.depthTexture.minFilter=i.NearestFilter,r.depthTexture.magFilter=i.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t){const s=Math.max(1,t.clientWidth*e.getPixelRatio()),a=Math.max(1,t.clientHeight*e.getPixelRatio()),n=new i.DepthTexture(s,a);n.type=i.UnsignedInt248Type,n.minFilter=i.NearestFilter,n.magFilter=i.NearestFilter;const r=new i.WebGLRenderTarget(s,a,{type:i.HalfFloatType,depthTexture:n});return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r}createSceneColorRenderTarget(e,t){const s=this.gRenderTarget.width,a=this.gRenderTarget.height,n=new i.WebGLRenderTarget(s,a,{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return n.texture.minFilter=i.LinearFilter,n.texture.magFilter=i.LinearFilter,n.texture.generateMipmaps=!1,n.textures[1].minFilter=i.NearestFilter,n.textures[1].magFilter=i.NearestFilter,n}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose();const t=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,samples:this.options?.msaa??(Ye?void 0:2),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();for(const e of this.postProcessEffects)this.composer.removePass(e.pass),e.pass.dispose();this.postProcessEffects.length=0,this.container.replaceChildren();Ze().unobserve(this.container),Je.delete(this.container),this.volumetricFogPass.dispose(),x.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.findIndex(t=>t===e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.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 R&&(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:gt(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 R||e instanceof i.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateMaterialProperties(e,t){(e instanceof i.MeshBasicMaterial||e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(null!=t.uniforms.color&&t.uniforms.color.value.setFromColor(e.color),null!=t.uniforms.opacity&&(t.uniforms.opacity.value=e.opacity),null!=t.uniforms.map&&(t.uniforms.map.value=e.map),null!=t.uniforms.alphaMap&&(t.uniforms.alphaMap.value=e.alphaMap),null!=t.uniforms.lightMap&&(t.uniforms.lightMap.value=e.lightMap,t.uniforms.lightMapIntensity.value=e.lightMapIntensity),null!=t.uniforms.aoMap&&(t.uniforms.aoMap.value=e.aoMap,t.uniforms.aoMapIntensity.value=e.aoMapIntensity),null!=t.uniforms.alphaTest&&(t.uniforms.alphaTest.value=e.alphaTest)),(e instanceof m||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)&&(t.uniforms.normalMap&&(t.uniforms.normalMap.value=e.normalMap,t.uniforms.normalScale.value=e.normalScale.x),t.uniforms.emissiveMap&&(t.uniforms.emissiveMap.value=e.emissiveMap,t.uniforms.emissive.value.setFromColor(e.emissive),t.uniforms.emissiveIntensity.value=e.emissiveIntensity)),e instanceof m&&(null!=t.uniforms.roughnessMap&&(t.uniforms.roughnessMap.value=e.roughnessMap),null!=t.uniforms.metalnessMap&&(t.uniforms.metalnessMap.value=e.metalnessMap),null!=t.uniforms.roughness&&(t.uniforms.roughness.value=e.roughness),null!=t.uniforms.metalness&&(t.uniforms.metalness.value=e.metalness)),e instanceof i.MeshPhysicalMaterial&&(t.uniforms.sheenColor&&t.uniforms.sheenColor.value.setFromColor(e.sheenColor).multiplyScalar(e.sheen),t.uniforms.sheenColorMap&&(t.uniforms.sheenColorMap.value=e.sheenColorMap),t.uniforms.sheenRoughness&&(t.uniforms.sheenRoughness.value=e.sheenRoughness),t.uniforms.sheenRoughnessMap&&(t.uniforms.sheenRoughnessMap.value=e.sheenRoughnessMap)),e instanceof Ge&&(t.uniforms.heightMap.value=e.heightMap,t.uniforms.heightScale.value=e.heightScale),this.updateMaterialCommonProperties(e,t)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],a=s[e].value;null!=t&&t.value!==a&&"receiveShadow"!==e&&!1===wt.includes(e)&&(t.value=a)}this.updateMaterialCommonProperties(e,t)}inheritCustomUniformBindings(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s)null==i[e]&&("receiveShadow"===e||wt.includes(e)||xt.includes(e)||(i[e]={value:s[e].value}))}updateMaterialCommonProperties(e,t){t.alphaTest=e.alphaTest,t.side=e.side,t.depthTest=e.depthTest,t.blending=e.blending,t.colorWrite=e.colorWrite,t.premultipliedAlpha=e.premultipliedAlpha,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.visible=e.visible}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of wt){const t=i[e],a=s[e];null!=a&&null!=t&&(t.value=a.value)}}createGBufferMaterial(e,t,s=!1){const a=t===ke.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let n=a.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==n){let s=V.uv;if(e instanceof Ge&&null!=e.heightMap){const t=U("heightScale",e.heightScale??1);s=Be(s,k("heightMap",e.heightMap),t)}let o=_.normal;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=e.normalMap??$e,i=U("useNormalMap",null!=e.normalMap?1:0),a=U("normalScale",e.normalScale?.x??1),n=S(k("normalMap",t).sample(We(s,e.normalMap)),a);o=z(_.normal,n,i)}else e instanceof R&&null!=e.outputNormal&&(o=e.outputNormal);!0!==e.userData.disableAO&&(o=q("DOUBLE_SIDED",o,e=>N(new j("gl_FrontFacing"),e,e.multiplyScalar(-1))));let l=e.userData?.reflective?C(0):C(1);if(e instanceof i.MeshStandardMaterial){const t=U("roughness",e.roughness??1),i=e.roughnessMap??He,a=U("useRoughnessMap",null!=e.roughnessMap?1:0),n=k("roughnessMap",i).sample(We(s,e.roughnessMap)).g.multiply(t);l=z(t,n,a)}else e instanceof R&&null!=e.outputRoughness&&(l=e.outputRoughness);let h=null;if((e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial)&&null!=e.lightMap){const t=e.lightMap,i=U("useLightMap",null!=e.lightMap?1:0),a=U("lightMapIntensity",e.lightMapIntensity??1),n=k("lightMap",t).sample(s).rgb.multiplyScalar(a);h=z(B(0),n,i)}let d=C(0);if(e instanceof i.MeshStandardMaterial){const t=U("metalness",e.metalness??0),i=e.metalnessMap??ze,a=U("useMetalnessMap",null!=e.metalnessMap?1:0),n=k("metalnessMap",i).sample(We(s,e.metalnessMap)).b.multiply(t);d=z(t,n,a)}else e instanceof R&&e.outputRoughness;let u=null,c=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??He,i=U("useAoMap",null!=e.aoMap?1:0);c=U("aoMapIntensity",e.aoMapIntensity??1);const a=k("aoMap",t).sample(We(s,e.aoMap)).r;u=z(C(1),a,i)}else e instanceof R&&e.outputRoughness;const f=U("opacity",e.opacity??1);let g=C(1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){if(null!=e.alphaMap){const t=e.alphaMap;g=k("alphaMap",t).sample(We(s,e.alphaMap)).r}g=g.multiply(f)}else e instanceof R&&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=E("color",(new i.Vector3).setFromColor(e.color));const a=e.map??He,n=U("useAlbedoMap",null!=e.map?1:0),r=k("map",a).sample(We(s,e.map)),o=r.multiply(D(t,1)),l=D(t,1);M=z(l,o,n),e.vertexColors&&(M=M.multiply(W(L($.color.rgb),1)));const h=z(C(1),r.w,n);g=g.multiply(h)}const v=!0===e.userData.hasBloom;let P=B(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=E("emissive",(new i.Vector3).setFromColor(e.emissive)),a=U("emissiveIntensity",e.emissiveIntensity),n=e.emissiveMap??ze,r=U("useEmissiveMap",null!=e.emissiveMap?1:0),o=k("emissiveMap",n).sample(We(s,e.emissiveMap)).rgb.multiply(t);P=z(t,o,r),P=P.multiplyScalar(a)}else e instanceof R&&null!=e.outputEmissive&&(P=e.outputEmissive);let b=null;if(e instanceof i.MeshPhysicalMaterial&&e.sheen>0&&(b=E("sheenColor",(new i.Vector3).setFromColor(e.sheenColor).multiplyScalar(e.sheen)),e.sheen>0&&null!=e.sheenColorMap)){const t=k("sheenColorMap",e.sheenColorMap).sample(s).rgb;b=b.multiply(t)}let y=null;if(e instanceof i.MeshPhysicalMaterial&&e.sheen>0&&(y=U("sheenRoughness",e.sheenRoughness),e.sheen>0&&null!=e.sheenRoughnessMap)){const t=k("sheenRoughnessMap",e.sheenRoughnessMap).sample(s).r;y=y.multiply(t)}let T=null;if(e instanceof i.MeshPhysicalMaterial&&e.anisotropy>0&&(T=U("anisotropy",e.anisotropy),e.anisotropy>0&&null!=e.anisotropyMap)){const t=k("anisotropyMap",e.anisotropyMap).sample(s).r;T=T.multiply(t)}let w=null;if(e instanceof i.MeshPhysicalMaterial&&e.anisotropy>0){const t=e.anisotropyRotation??0;w=X("anisotropyDirection",new i.Vector2(Math.cos(t),Math.sin(t)))}const x=e instanceof p&&null!=e.uniforms[ie],I=e instanceof p&&null!=e.uniforms[ue],H=e instanceof p&&null!=e.uniforms[de],Y=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,K=U("alphaTest",e.alphaTest);let Q,J=e.alphaTest>0?g.lt(K):Y&&t===ke.opaque?g.lt(.8):null;!0===e.userData.isDecal&&(J=J?J.or(Le):Le),Q=Y?W(0,0,0,0):(r=o,G(r).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?l:1);const Z=e instanceof R?e.outputPosition:void 0,ee=e instanceof R?e.outputTransform:void 0;let te,se=D("black",1);if(e instanceof R&&null!=e.outputColor)se=e.outputColor;else if(e instanceof i.MeshStandardMaterial)se=O({color:M,metalness:d,roughness:l,emissive:P.rgb,normal:o,ambientOcclusion:u,ambientOcclusionIntensity:c,bakedLight:h,sheenColor:b,sheenRoughness:y,anisotropy:T,anisotropyDirection:w});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)se=F({color:M.rgb,ambientOcclusion:u,ambientOcclusionIntensity:c});else if(e instanceof i.MeshBasicMaterial){let e=M.rgb,t=h??B("black");null!=u&&(t=t.multiplyScalar(u.subtract(1).multiply(c).add(1))),e=e.add(t),se=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(se=A({color:M,emissive:P.rgb,normal:o,ambientOcclusion:u,ambientOcclusionIntensity:c,bakedLight:h}));(e instanceof R||e instanceof i.MeshStandardMaterial)&&(te=e.envMap);let ae=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(ae=e.fog);let ne=D(se.rgb,g);ae&&(ne=new FogNode(ne));let re=!0;if(t===ke.opaque?(re&&(re=!x&&!I&&!H),re&&(re=!Y)):t===ke.transparent&&re&&(re=Y||x||I||H),!re)return n=Xe,a.set(e,n),n;n=new R({transform:ee,position:null==ee?Z:void 0,outputs:[ne,P.rgba(t===ke.opaque?K:v?1:0),Q],opacity:g,outputEncoding:!1,fog:ae,transparent:e.transparent,lights:!0,envMap:te,alphaTest:e.alphaTest,discard:J}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=n.uniforms.envMapIntensity&&(n.uniforms.envMapIntensity.value=e.envMapIntensity),"alphaMap"in e&&null!=e.alphaMap&&(n.alphaMap=e.alphaMap),(e instanceof R||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(n),e instanceof R&&(Object.assign(n.defines,e.defines),null!=n.uniforms[de]&&(n.uniforms[de].value=this.aoPass.pdRenderTarget.texture,n.defines.USE_SSAO_MAP="")),n.userData.mrtOutputs=3,n.forceSinglePass=e.forceSinglePass,n.side=e.side,n.blending=e.blending,Y?(n.depthWrite=!e.transparent,n.depthTest=e.depthTest,n.colorWrite=t===ke.transparent):(n.depthWrite=e.depthWrite,n.depthTest=e.depthTest),n.visible=e.visible,n.alphaTest=e.alphaTest,n.alphaHash=e.alphaHash,n.vertexColors=e.vertexColors,n.premultipliedAlpha=e.premultipliedAlpha,n.toneMapped=e.toneMapped,n.blendAlpha=e.blendAlpha,n.blendColor=e.blendColor,n.polygonOffset=e.polygonOffset,n.polygonOffsetFactor=e.polygonOffsetFactor,n.polygonOffsetUnits=e.polygonOffsetUnits,n.blending=e.blending,n.wireframe=e.wireframe??!1,n.userData.isGBufferMaterial=!0,n.visible=re,Object.assign(n.userData,e.userData),n.visible&&(this.csm.setupMaterial(n),e instanceof p&&this.inheritCustomUniformBindings(e,n)),a.set(e,n)}var r;return n.visible&&(e instanceof p?this.updateUniformValues(e,n):this.updateMaterialProperties(e,n)),this.initLightVolumeUniform(n),n}isDepthPrepassEnabled(){return!0===this.options.depthPrepass?.enabled}usesSceneFeedbackUniforms(e){return e instanceof p&&(null!=e.uniforms[ie]||null!=e.uniforms[ue]||null!=e.uniforms[de])}isDepthPrepassEligibleMaterial(e){return null!=e&&(!1!==e.visible&&!1!==e.depthTest&&!1!==e.depthWrite&&(!e.transparent&&e.blending!==i.AdditiveBlending&&(!this.usesSceneFeedbackUniforms(e)&&(e instanceof R||e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshBasicMaterial))))}isDepthPrepassEligibleMesh(e){return!!this.isDepthPrepassEnabled()&&((e instanceof i.InstancedMesh||e instanceof _e)&&(!Array.isArray(e.material)&&this.isDepthPrepassEligibleMaterial(e.material)))}createDepthPrepassMaterial(e){if(!this.isDepthPrepassEligibleMaterial(e))return null;let t=this.depthPrepassMaterialCache.get(e);if(null==t){let s,a=C(1);e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(a=U("opacity",e.opacity??1),null!=e.map&&(a=a.multiply(k("map",e.map).sample(V.uv).a)),null!=e.alphaMap&&(a=a.multiply(k("alphaMap",e.alphaMap).sample(V.uv).r))):e instanceof R&&(a=e.outputOpacity??C(1)),null!=e.alphaTest&&e.alphaTest>0&&(s=a.lt(e.alphaTest));const n=e instanceof R?e.outputPosition:void 0,r=e instanceof R?e.outputTransform:void 0;t=new R({outputs:[D(0,0),D(0,0),D(0,0)],opacity:a,transform:r,position:null==r?n:void 0,discard:s,lights:!1,fog:!1,outputEncoding:!1,transparent:!1,alphaTest:e.alphaTest}),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=i.NoBlending,t.lights=!1,t.fog=!1,t.toneMapped=!1,t.side=e.side,t.alphaTest=e.alphaTest,t.visible=e.visible,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.onBeforeCompile=()=>{},t.customProgramCacheKey=()=>`depth-prepass:${e.id}:${e.version}:${e.alphaTest}:${e.side}`;for(const e of wt)delete t.uniforms[e];for(const e of xt)delete t.uniforms[e];delete t.uniforms.receiveShadow,this.depthPrepassMaterialCache.set(e,t)}return e instanceof R?this.updateUniformValues(e,t):this.updateMaterialProperties(e,t),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=i.NoBlending,t.visible=e.visible,t.alphaTest=e.alphaTest,t.side=e.side,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t}applyDepthPrepassMaterials(){const e=this.depthPrepassCachedMaterials,t=this.depthPrepassCachedVisibility;e.clear(),t.length=0,Me(this.scene,s=>{if(Pt(s))return t.push(s),s.visible=!1,!1;if(!(s instanceof o))return;if(e.set(s,s.material),!this.isDepthPrepassEligibleMesh(s))return t.push(s),void(s.visible=!1);const i=this.createDepthPrepassMaterial(s.material);if(null==i)return t.push(s),void(s.visible=!1);s.material=i,s.visible=!0})}unapplyDepthPrepassMaterials(){this.depthPrepassCachedMaterials.forEach((e,t)=>{t.material=e}),this.depthPrepassCachedVisibility.forEach(e=>{e.visible=!0})}renderDepthPrepass(){if(!this.isDepthPrepassEnabled())return;this.applyDepthPrepassMaterials();const e=this.scene.matrixWorldAutoUpdate,t=this.scene.matrixAutoUpdate,s=this.renderer.shadowMap.autoUpdate;this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clearDepth();try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Depth prepass render failed",e)}this.unapplyDepthPrepassMaterials(),this.renderer.shadowMap.autoUpdate=s,this.scene.matrixWorldAutoUpdate=e,this.scene.matrixAutoUpdate=t}updateCsm(){const e=this.csmUpdateInvervals;if(this.renderer.shadowMap.autoUpdate&&null!=this.csmCascadeLastUpdate&&Array.isArray(e)){const t=performance.now();for(let s=0;s<this.csm.lights.length;++s){const i=e[s]??e[e.length-1]??16;(t-this.csmCascadeLastUpdate[s]>=i||0===s)&&this.csm.lights[s].shadow&&(this.csm.lights[s].shadow.needsUpdate=!0,this.csmCascadeLastUpdate[s]=t)}}this.csm.update()}loop(t,s=!1){const a=this.stats,n=a.addPanel(new ee.Panel("Calls","#83f","#002")),l=a.addPanel(new ee.Panel("Triangles","#c32","#002"));let h;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(h=new me(this.renderer.getContext()),a.addPanel(h)),this.showStats=s;let p=10,d=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>p&&(p=e,setTimeout(()=>p=10,5e3)),n.update(e,p);const t=this.renderer.info.render.triangles;t>d&&(d=t,setTimeout(()=>d=1e3,5e3)),l.update(t,d)};performance.now();i.Ray.prototype.intersectTriangle;this.resizeRender();const c=[],m=[],f=[];let g=0;const M=new r,v=new r;let P=0;let b=this.paused,y=!1,T=0,w=null,x=this.fpsCapRevision;const S=()=>{this.running&&!0!==this.options.enableXR&&requestAnimationFrame(U)},C=()=>{e.activeView=this,y&&(y=!1,requestAnimationFrame(()=>U(T)))},O=Ze();Je.set(this.container,e=>{this.isIntersecting=e,e&&C()}),O.observe(this.container),this.container.addEventListener("pointerdown",()=>{C()},{capture:!0});const U=s=>{y=!1;const n=this.renderer.getContext();if(!this.running||null===this.container.offsetParent||this.paused&&n.drawingBufferHeight>1)return y=!0,T=s,setTimeout(()=>{y&&U(s)},500),void(this.paused&&(b=!0));if(this.renderer.domElement.parentElement!==this.container){if(e.activeView!==this&&null!==e.activeView)return y=!0,void(T=s);this.container.replaceChildren(this.renderer.domElement),this.resizeRender()}if(!0!==this.options.enableXR){x!==this.fpsCapRevision&&(x=this.fpsCapRevision,w=null);const e=this.fpsCap;if(null!=e){const t=1e3/e;if(null!=w){const e=s-w;if(e<t)return void S();w=s-e%t}else w=s}else w=s}this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),a.begin(),this.showStats&&h?.startQuery(),this.ssrPass.gpuPanel=h;let r=(s*=.001)-g;if(g=s,b&&(r=.016,b=!1),M.copy(this.camera.matrixWorld),r>1){let e=r;for(;e>.05;)t(tt),e-=tt;t(e)}else t(r);this.onLoopCallbacks.forEach(e=>e(r)),this.paused||(this.simulationTime+=r*this.simulationTimeScale);const l=this.simulationTime;this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),s-P>.08&&!v.equals(M)&&(this.renderer.shadowMap.needsUpdate=!0,P=s),this.updateCsm();let p=!1;c.length=0,m.length=0,f.length=0;const d=at;rt.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),d.setFromProjectionMatrix(rt);let C=!1,O=!1,E=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Fe&&(C=!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&&(p=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[ie])&&isObjectInFrustum(e,d)?(this.initDepthUniform(e.material),O=!0):e instanceof Y&&(e.visible=!1,m.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[de]&&isObjectInFrustum(e,d)&&e.material instanceof R&&this.initAoUniform(e.material),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[ue]&&isObjectInFrustum(e,d)&&(f.push(e),e.material.uniforms[ue].value=this.sceneColorRenderTarget.texture,E=!0),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[pe])e.material.uniforms[pe].value=l;else if(e instanceof o&&Array.isArray(e.material))for(const t of e.material)t.uniforms&&null!=t.uniforms[pe]&&(t.uniforms[pe].value=l)}),this.bloomPass.enabled=p,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderDepthPrepass(),this.renderScene(ke.opaque),this.aoPass.output=te.OUTPUT.Off,(O||E)&&(this.fquadCopyOpaque.material.uniforms.tSceneColor.value=this.gRenderTarget.textures[0],this.fquadCopyOpaque.material.uniforms.tDepthTexture.value=this.gRenderTarget.depthTexture,this.initResolutionUniform(this.fquadCopyOpaque.material),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.clear(),this.fquadCopyOpaque.render(this.renderer),this.renderer.setRenderTarget(this.gRenderTarget)),f.length,c.forEach(e=>e.visible=!0),m.forEach(e=>e.visible=!0),f.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=s),this.volumetricFogPass&&C?(this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene),this.volumetricFogPass.enabled=!0):this.volumetricFogPass&&(this.volumetricFogPass.enabled=!1),this.updatePostProcessEffectUniforms(l);try{!this.paused&&this.running&&(this.render(r),this.showStats&&h?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}a.end(),this.csm?.update(),S()};!0===this.options.enableXR?this.renderer.setAnimationLoop(U):requestAnimationFrame(U)}applyGBufferMaterials(e){const t=this.gBufferCachedMaterials,s=this.gBufferCachedVisibility;t.clear(),s.length=0;Me(this.scene,i=>{if(Pt(i))return s.push(i),i.visible=!1,!1;if(i instanceof o){t.set(i,i.material);let a=!1;if(Array.isArray(i.material)){i.material=i.material.slice();for(let t=0;t<i.material.length;t++)i.material[t]=this.createGBufferMaterial(i.material[t],e,e===ke.opaque&&this.isDepthPrepassEligibleMesh(i)),a||(a=i.material[t].visible),this.initShadowUniform(i,i.material[t])}else i.material=this.createGBufferMaterial(i.material,e,e===ke.opaque&&this.isDepthPrepassEligibleMesh(i)),a||(a=i.material.visible),this.initShadowUniform(i,i.material);a?i.visible=!0:null!=i.children&&0!=i.children.length||(s.push(i),i.visible=!1)}})}unapplyGBufferMaterials(){this.gBufferCachedMaterials.forEach((e,t)=>{t.material=e}),this.gBufferCachedVisibility.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)})}initTextures(e=this.scene){e.traverse(e=>{if(e instanceof o)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++)this._initMaterialTextures(e.material[t]);else this._initMaterialTextures(e.material)})}_initMaterialTextures(e){if(!this._initiatedMaterialTextures.has(e))if(this._initiatedMaterialTextures.add(e),e instanceof p){for(const[t,s]of Object.entries(e.uniforms))if(s.value instanceof u){if(this._initiatedTextures.has(s.value))continue;this.renderer.initTexture(s.value),this._initiatedTextures.add(s.value)}}else for(const[t,s]of Object.entries(e))if(s instanceof u){if(this._initiatedTextures.has(s))continue;this.renderer.initTexture(s),this._initiatedTextures.add(s)}}async compileAsync(e=this.scene){if(this.compileInProgress)return;this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0,this.applyGBufferMaterials(ke.opaque),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials(ke.transparent),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.isDepthPrepassEnabled()&&(this.renderer.setRenderTarget(this.gRenderTarget),this.applyDepthPrepassMaterials(),await this.renderer.compileAsync(e,this.camera),this.unapplyDepthPrepassMaterials()),e===this.scene&&(this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.compileAsync(this.fquadBlendAO.mesh,this.fquadBlendAO.camera),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.compileAsync(this.fquadCopyOpaque.mesh,this.fquadCopyOpaque.camera));const t=this.csm.lights[0]?.shadow.camera;null!=t&&(this.applyDepthMaterial(),await this.renderer.compileAsync(e,t),this.unapplyDepthMaterial()),this.compileInProgress=!1,this.renderer.setRenderTarget(null)}applyDepthMaterial(){const e=this.gBufferCachedMaterials;e.clear(),this.scene.traverse(t=>{(t.isMesh||t.isPoints||t.isLine||t.isSprite)&&(this.initCustomDepthMaterial(t),e.set(t,t.material),t.castShadow?null!=t.customDepthMaterial?t.material=t.customDepthMaterial:t.material=Ct: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!==ke.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===ke.opaque&&this.gBufferCachedMaterials.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof p&&this.updateLightUniformValues(t.material,e)}),this.unapplyGBufferMaterials(),this.renderer.shadowMap.autoUpdate=i,this.scene.matrixWorldAutoUpdate=t,this.scene.matrixAutoUpdate=s}getEnvTexture(e){null==this.pmremGenerator&&(this.pmremGenerator=new i.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader());let t=this.pmremGeneratorResults.get(e);return null==t&&(t=this.pmremGenerator.fromEquirectangular(e).texture,this.pmremGeneratorResults.set(e,t)),t.colorSpace=i.SRGBColorSpace,t}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure);!function(e,t=i.NoToneMapping,s=1){e.tonemapMapping=t,e.tonemapExposure=s,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=e.colorTint??new i.Color("white"),e.colorTint.set("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.globalSaturation=ot(e.globalSaturation,1,1,1),e.globalContrast=ot(e.globalContrast,1,1,1),e.globalGamma=ot(e.globalGamma,1,1,1),e.globalGain=ot(e.globalGain,1,1,1),e.globalOffset=ot(e.globalOffset,0,0,0),e.shadowsSaturation=ot(e.shadowsSaturation,1,1,1),e.shadowsContrast=ot(e.shadowsContrast,1,1,1),e.shadowsGamma=ot(e.shadowsGamma,1,1,1),e.shadowsGain=ot(e.shadowsGain,1,1,1),e.shadowsOffset=ot(e.shadowsOffset,0,0,0),e.shadowsMax=.09,e.midtonesSaturation=ot(e.midtonesSaturation,1,1,1),e.midtonesContrast=ot(e.midtonesContrast,1,1,1),e.midtonesGamma=ot(e.midtonesGamma,1,1,1),e.midtonesGain=ot(e.midtonesGain,1,1,1),e.midtonesOffset=ot(e.midtonesOffset,0,0,0),e.highlightsSaturation=ot(e.highlightsSaturation,1,1,1),e.highlightsContrast=ot(e.highlightsContrast,1,1,1),e.highlightsGamma=ot(e.highlightsGamma,1,1,1),e.highlightsGain=ot(e.highlightsGain,1,1,1),e.highlightsOffset=ot(e.highlightsOffset,0,0,0),e.highlightsMin=.5,e.lut=void 0,e.lutIntensity=0}(this.postProcessSettings,this.baseToneMapping,this.baseToneMappingExposure);const e=this.postProcessSettings;let t,s=!1;if(null==this.camera)return;const a=this.camera.getWorldPosition(dt);let n=[];for(const r of this.postProcessVolumes){if(!st(r.object))continue;let o=r.blendWeight??1;const l=r.distanceToPoint(a);l>r.blendRadius||(r.blendRadius>0&&(o*=ve(1-l/r.blendRadius,0,1)),o>1&&(o=1),o>0&&(n.push(r),void 0!==r.settings.tonemapMapping&&(e.tonemapMapping=r.settings.tonemapMapping),void 0!==r.settings.tonemapExposure&&(e.tonemapExposure=i.MathUtils.lerp(e.tonemapExposure,r.settings.tonemapExposure,o)),void 0!==r.settings.envTexture&&(e.envTexture=r.settings.envTexture),void 0!==r.settings.envIntensity&&(e.envIntensity=i.MathUtils.lerp(e.envIntensity,r.settings.envIntensity,o)),void 0!==r.settings.vignetteIntensity&&(e.vignetteIntensity=i.MathUtils.lerp(e.vignetteIntensity,r.settings.vignetteIntensity,o)),void 0!==r.settings.colorTint&&void 0!==r.settings.colorTintIntensity&&r.settings.colorTintIntensity>0&&(e.colorTint=e.colorTint.lerp(r.settings.colorTint,o)),void 0!==r.settings.colorTintIntensity&&(e.colorTintIntensity=i.MathUtils.lerp(e.colorTintIntensity,r.settings.colorTintIntensity,o)),void 0!==r.settings.depthFocus&&(s=!0,e.depthFocus=void 0!==e.depthFocus?i.MathUtils.lerp(e.depthFocus,r.settings.depthFocus,o):r.settings.depthFocus),void 0!==r.settings.depthAperture&&(s=!0,e.depthAperture=void 0!==e.depthAperture?i.MathUtils.lerp(e.depthAperture,r.settings.depthAperture,o):r.settings.depthAperture),void 0!==r.settings.depthMaxBlur&&(s=!0,e.depthMaxBlur=void 0!==e.depthMaxBlur?i.MathUtils.lerp(e.depthMaxBlur,r.settings.depthMaxBlur,o):r.settings.depthMaxBlur),void 0!==r.settings.temperature&&(e.temperature=i.MathUtils.lerp(e.temperature,r.settings.temperature,o)),void 0!==r.settings.temperatureTint&&(e.temperatureTint=i.MathUtils.lerp(e.temperatureTint,r.settings.temperatureTint,o)),void 0!==r.settings.globalSaturation&&e.globalSaturation.lerp(r.settings.globalSaturation,o),void 0!==r.settings.globalContrast&&e.globalContrast.lerp(r.settings.globalContrast,o),void 0!==r.settings.globalGamma&&e.globalGamma.lerp(r.settings.globalGamma,o),void 0!==r.settings.globalGain&&e.globalGain.lerp(r.settings.globalGain,o),void 0!==r.settings.globalOffset&&e.globalOffset.lerp(r.settings.globalOffset,o),void 0!==r.settings.shadowsSaturation&&e.shadowsSaturation.lerp(r.settings.shadowsSaturation,o),void 0!==r.settings.shadowsContrast&&e.shadowsContrast.lerp(r.settings.shadowsContrast,o),void 0!==r.settings.shadowsGamma&&e.shadowsGamma.lerp(r.settings.shadowsGamma,o),void 0!==r.settings.shadowsGain&&e.shadowsGain.lerp(r.settings.shadowsGain,o),void 0!==r.settings.shadowsOffset&&e.shadowsOffset.lerp(r.settings.shadowsOffset,o),void 0!==r.settings.shadowsMax&&(e.shadowsMax=i.MathUtils.lerp(e.shadowsMax,r.settings.shadowsMax,o)),void 0!==r.settings.midtonesSaturation&&e.midtonesSaturation.lerp(r.settings.midtonesSaturation,o),void 0!==r.settings.midtonesContrast&&e.midtonesContrast.lerp(r.settings.midtonesContrast,o),void 0!==r.settings.midtonesGamma&&e.midtonesGamma.lerp(r.settings.midtonesGamma,o),void 0!==r.settings.midtonesGain&&e.midtonesGain.lerp(r.settings.midtonesGain,o),void 0!==r.settings.midtonesOffset&&e.midtonesOffset.lerp(r.settings.midtonesOffset,o),void 0!==r.settings.highlightsSaturation&&e.highlightsSaturation.lerp(r.settings.highlightsSaturation,o),void 0!==r.settings.highlightsContrast&&e.highlightsContrast.lerp(r.settings.highlightsContrast,o),void 0!==r.settings.highlightsGamma&&e.highlightsGamma.lerp(r.settings.highlightsGamma,o),void 0!==r.settings.highlightsGain&&e.highlightsGain.lerp(r.settings.highlightsGain,o),void 0!==r.settings.highlightsOffset&&e.highlightsOffset.lerp(r.settings.highlightsOffset,o),void 0!==r.settings.highlightsMin&&(e.highlightsMin=i.MathUtils.lerp(e.highlightsMin,r.settings.highlightsMin,o)),void 0!==r.settings.lut&&(t=r.settings.lut),void 0!==r.settings.lutIntensity&&(e.lutIntensity=i.MathUtils.lerp(e.lutIntensity,r.settings.lutIntensity,o))))}if(0===n.length)return this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure);const r=e.vignetteIntensity>pt,o=(h=e.temperature,p=e.temperatureTint,!ht(h,6500)||!ht(p,0));var h,p;const d=(u=e.colorTint,e.colorTintIntensity>pt&&(!ht(u.r,1)||!ht(u.g,1)||!ht(u.b,1)));var u;const c=!(lt((m=e).globalSaturation,1,1,1)&<(m.globalContrast,1,1,1)&<(m.globalGamma,1,1,1)&<(m.globalGain,1,1,1)&<(m.globalOffset,0,0,0)&<(m.shadowsSaturation,1,1,1)&<(m.shadowsContrast,1,1,1)&<(m.shadowsGamma,1,1,1)&<(m.shadowsGain,1,1,1)&<(m.shadowsOffset,0,0,0)&<(m.midtonesSaturation,1,1,1)&<(m.midtonesContrast,1,1,1)&<(m.midtonesGamma,1,1,1)&<(m.midtonesGain,1,1,1)&<(m.midtonesOffset,0,0,0)&<(m.highlightsSaturation,1,1,1)&<(m.highlightsContrast,1,1,1)&<(m.highlightsGamma,1,1,1)&<(m.highlightsGain,1,1,1)&<(m.highlightsOffset,0,0,0));var m;const f=o||d||c||r,g=f&&e.tonemapMapping!==i.NoToneMapping,M=null!=t&&e.lutIntensity>pt;f?(this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1):(this.renderer.toneMapping=e.tonemapMapping,this.renderer.toneMappingExposure=e.tonemapExposure),null!=e.envTexture&&(this.scene.environment=this.getEnvTexture(e.envTexture)),this.scene.environmentIntensity=e.envIntensity,f?(this.colorPass.whiteBalanceEnabled=o,this.colorPass.whiteBalanceScale=o?function(e,t,s){const i=function(e){const t=ve(e,1e3,4e4)/100,s=t<=66?1:ve(1.292936186062745*Math.pow(t-60,-.1332047592),0,1),i=ve(t<=66?.3900815787690196*Math.log(t)-.6318414437886275:1.129890860895294*Math.pow(t-60,-.0755148492),0,1),a=t>=66?1:t<=19?0:ve(.5432067891101962*Math.log(t-10)-1.19625408914,0,1);return ct.set(s,i,a)}(t),a=1+.2*ve(s,-1,1),n=i.x,r=i.y*a,o=i.z,l=Math.max(r,1e-4);return e.set(1/Math.max(n/l,1e-4),1/Math.max(r/l,1e-4),1/Math.max(o/l,1e-4)),e}(ut,e.temperature,e.temperatureTint):ut.set(1,1,1),this.colorPass.vignetteIntensity=e.vignetteIntensity,this.colorPass.vignetteEnabled=r,this.colorPass.colorTintEnabled=d,this.colorPass.colorTint=e.colorTint,this.colorPass.colorTintIntensity=e.colorTintIntensity,this.colorPass.colorGradingEnabled=c,this.colorPass.toneMapping=e.tonemapMapping,this.colorPass.toneMappingEnabled=g,this.colorPass.toneMappingExposure=e.tonemapExposure,this.colorPass.globalSaturation=e.globalSaturation,this.colorPass.globalContrast=e.globalContrast,this.colorPass.globalGamma=e.globalGamma,this.colorPass.globalGain=e.globalGain,this.colorPass.globalOffset=e.globalOffset,this.colorPass.shadowsSaturation=e.shadowsSaturation,this.colorPass.shadowsContrast=e.shadowsContrast,this.colorPass.shadowsGamma=e.shadowsGamma,this.colorPass.shadowsGain=e.shadowsGain,this.colorPass.shadowsOffset=e.shadowsOffset,this.colorPass.shadowsMax=e.shadowsMax,this.colorPass.midtonesSaturation=e.midtonesSaturation,this.colorPass.midtonesContrast=e.midtonesContrast,this.colorPass.midtonesGamma=e.midtonesGamma,this.colorPass.midtonesGain=e.midtonesGain,this.colorPass.midtonesOffset=e.midtonesOffset,this.colorPass.highlightsSaturation=e.highlightsSaturation,this.colorPass.highlightsContrast=e.highlightsContrast,this.colorPass.highlightsGamma=e.highlightsGamma,this.colorPass.highlightsGain=e.highlightsGain,this.colorPass.highlightsOffset=e.highlightsOffset,this.colorPass.highlightsMin=e.highlightsMin,this.colorPass.enabled=!0):this.colorPass.enabled=!1,s&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==e.depthFocus&&(this.dofPass.uniforms.focus.value=e.depthFocus),void 0!==e.depthAperture&&(this.dofPass.uniforms.aperture.value=e.depthAperture),void 0!==e.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=e.depthMaxBlur)):this.dofPass.enabled=!1,this.lutPass.enabled=M,M&&(null!=t&&(t.flipY=!0,t.generateMipmaps=!1),this.lutPass.lut=t,this.lutPass.intensity=e.lutIntensity)}updatePostProcessEffectUniforms(e){if(0===this.postProcessEffects.length)return;const t=this.postProcessEffectUniformState;t.aoEnabled=this.aoPass.enabled,t.aoTexture=this.aoPass.enabled?this.aoPass.pdRenderTarget.texture:null,this.camera instanceof l?(t.cameraNear=this.camera.near,t.cameraFar=this.camera.far):(t.cameraNear=void 0,t.cameraFar=void 0),t.depthTexture=this.sceneColorRenderTarget.textures[1],t.normalTexture=this.gRenderTarget.textures[2],t.resolution.set(this.gRenderTarget.width,this.gRenderTarget.height),t.simulationTime=e;for(const e of this.postProcessEffects)e.pass.updateUniformState(t)}renderOverlay(){if(!this.running)return;if(0===this.overlayCameras.size)return;const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.previousClientWith/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof o&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,at)&&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===Ne.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=Ne:(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 p&&(e.uniforms[ie].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[ne]&&(e.uniforms[ne].value=this.camera.near),null!=e.uniforms[ae]&&(e.uniforms[ae].value=this.camera.far)))}initNormalUniform(e){e instanceof p&&null!=e.uniforms[oe]&&(e.uniforms[oe].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof R&&(t.uniforms.receiveShadow?t.uniforms.receiveShadow.value=e.receiveShadow:t.uniforms.receiveShadow={value:e.receiveShadow})}initLightVolumeUniform(e){e instanceof R&&(null!=this.lightVolume?null==e.uniforms.uSH?(e.defines.USE_LIGHT_PROBE_VOLUME="",e.uniforms.gridOrigin={value:this.lightVolume.gridOrigin},e.uniforms.gridSize={value:this.lightVolume.gridSize},e.uniforms.gridRes={value:this.lightVolume.gridResolution},e.uniforms.giIntensity={value:this.lightProbeIntensity},e.uniforms.uSH={value:this.lightVolume.shTexture},e.uniformsNeedUpdate=!0,e.needsUpdate=!0):e.uniforms.giIntensity.value=this.lightProbeIntensity:null!=e.uniforms.uSH&&(delete e.defines.USE_LIGHT_PROBE_VOLUME,delete e.uniforms.gridOrigin,delete e.uniforms.gridSize,delete e.uniforms.gridRes,delete e.uniforms.giIntensity,delete e.uniforms.uSH,e.uniformsNeedUpdate=!0,e.needsUpdate=!0))}initResolutionUniform(e){e instanceof p&&null!=e.uniforms[re]&&e.uniforms[re].value.set(this.gRenderTarget.width,this.gRenderTarget.height)}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[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 R&&!t.transparent&&t.depthWrite&&t.alphaTest>0))return;let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Ae(Ee);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new R({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}};et.activeView=null,et=e=t([se(),s("design:paramtypes",[HTMLElement,Object])],et);export{et as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const tt=.05;function st(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}function it(e,t){return e.priority!==t.priority?e.priority-t.priority:e.id-t.id}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 at=new i.Frustum,nt=new i.Box3,rt=new i.Matrix4;export function isObjectInFrustum(e,t){const s=nt.setFromObject(e);return t.intersectsBox(s)}function ot(e,t,s,a){return null==e?new i.Vector3(t,s,a):e.set(t,s,a)}function lt(e,t,s,i){return null!=e&&ht(e.x,t)&&ht(e.y,s)&&ht(e.z,i)}function ht(e,t,s=pt){return Math.abs(e-t)<=s}const pt=1e-4,dt=new i.Vector3,ut=new i.Vector3(1,1,1),ct=new i.Vector3(1,1,1);const mt=new r,ft=new c;function gt(e,t,s=new i.Matrix3){return ft.copy(e),ft.x*=-1,ft.y*=-1,ft.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(ft.y*=-1,ft.z*=-1),s.setFromMatrix4(mt.makeRotationFromEuler(ft))}const Mt=new R({outputs:[W(0,0,0,0),W(0,0,0,0),D(B("white"),Ie(4))],transparent:!0}),vt=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});Mt.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),vt);function Pt(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isLineSegments2||e.isTransformControls||e.isTransformControlsGizmo||e instanceof o&&bt(e,e.material)}function bt(e,t){return null==t||(Array.isArray(t)?t.some(t=>bt(e,t)):t instanceof i.RawShaderMaterial||t instanceof i.ShaderMaterial&&!(t instanceof R))}class yt extends Ve{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.cachedVisibility=[],this.toRender=[],this.needsSwap=!1}render(e,t,s,i,a){const n=e.autoClear;e.autoClear=!1;const r=this.scene.matrixWorldAutoUpdate,l=this.scene.matrixAutoUpdate,h=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const p=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),this.cachedVisibility.length=0;let d=0,u=this.toRender;if(u.length=0,this.scene.traverseVisible(e=>{const t=Pt(e);e instanceof o&&!t?(this.cachedVisibility.push(e),e.visible=!1):t&&(d++,u.push(e))}),d>0)for(const t of u)e.render(t,this.camera);this.cachedVisibility.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=n,s.depthTexture=p,this.scene.matrixWorldAutoUpdate=r,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class Tt extends Ve{constructor(e){super(),this.fn=e}render(e,t,s,i,a){this.fn(e,t,s,i,a)}}const wt=["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"],xt=["directionalShadowMap","directionalShadowMatrix","pointLightShadows","pointShadowMap","pointShadowMatrix","spotLightShadows","spotShadowMap"],St=E("fogColor");export class FogNode extends H{constructor(e,t=St){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),a=e.get(this.fogColor),n=e.get(U("fogFar")),r=e.get(U("fogNear")),o=e.get(U("fogDensity")),l=e.get(L(I.mvPosition.z));return{pars:"\n ",chunk:`\n #ifdef FOG_EXP2\n float fogFactor_${t} = 1.0 - exp( - ${o} * ${o} * ${l} * ${l} );\n #else\n float fogFactor_${t} = smoothstep( ${r}, ${n}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${a}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}const Ct=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,Euler as s,Group as r,LoadingManager as a,Mesh as i,Object3D as n,Texture as o,TextureLoader as l,Vector3 as c}from"three";import{GLTFLoader as h,MTLLoader as u,OBJLoader as m,DRACOLoader as d,LUTCubeLoader as p}from"three-stdlib";import{FBXLoader as f}from"three-stdlib";import{cloneMesh as y}from"../utils/mesh.js";import{pathJoin as g}from"../utils/files.js";import{Subject as w,firstValueFrom as x}from"rxjs";import{BoxCollisionShape as M,CapsuleCollisionShape as A,CollisionShapeSource as b,CylinderCollisionShape as L,SphereCollisionShape as _}from"./collision/collision-shape.js";import{importCollisionShapes as v,isCollisionMesh as S}from"./collision/collision-shape-import.js";import*as C from"three";import{iterateMaterials as T}from"../utils/materials.js";import{applyMaterial as R}from"./materializer.js";import{BufferGeometryUtils as P,EXRLoader as K,KTX2Loader as k,TGALoader as I,UltraHDRLoader as B}from"three/examples/jsm/Addons.js";import{disposeScene as D}from"../utils/three/cleanup.js";(()=>{const e=new Uint8Array([255,0,0,255]),t=new C.DataTexture(e,1,1,C.RGBAFormat);t.needsUpdate=!0})();const W=new d;W.setDecoderConfig({type:"js"}),W.setDecoderPath("/assets/draco/");const j=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new a,this.glbLoader=new h(this.loadingManager).setDRACOLoader(W),this.fbxLoader=new f(this.loadingManager),this.objLoader=new m(this.loadingManager),this.textureLoader=new l(this.loadingManager),this.tgaLoader=new I(this.loadingManager),this.exrLoader=new K(this.loadingManager),this.cubeLoader=new p(this.loadingManager),this.hdrLoader=new B(this.loadingManager),this.ktx2Loader=new k(this.loadingManager),this._textureLoader=new C.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this._retrievedMeshes=[],this._retrievedTextures=[],this.makeReady=new w,this.ready=x(this.makeReady),this._texturePromises=new Map,this._arrayTexturesByFileKey=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=g(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){const t=function(e){return E.get(e)}(e),s=getElectronArg("windowId");return null!=s||import.meta.url.includes(".vite")||import.meta.url.includes("hology/packages/core")?g(this.basePath,e)+(null!=s?`?windowId=${s}&v=${t}`:""):new URL(g("..",this.basePath,e),import.meta.url).href}async getTexture(e){if(!e||!e.fileKey)return null;if("png"===e.fileFormat||e.fileFormat,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);null!=e.texture&&(t.flipY!==e.texture?.flipY?(t.needsUpdate=!0,t.flipY=e.texture?.flipY??!0):t.wrapS!==G(e.texture?.wrapS)?(t.needsUpdate=!0,t.wrapS=G(e.texture?.wrapS)):t.wrapT!==G(e.texture?.wrapT)&&(t.wrapT=G(e.texture?.wrapT),t.needsUpdate=!0));const s=O(z(e));t.colorSpace!==s&&(t.colorSpace=s,t.needsUpdate=!0)}else try{await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then(t=>(t.texture3D?t=t.texture3D:(t.wrapS=G(e.texture?.wrapS),t.wrapT=G(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0,t.colorSpace=O(z(e))),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}async getTextureArray(e){const t=e.texture?.textureArrayFileKey,s=e.texture?.textureArrayLayer;if(!t||null==s)return{texture:null,layerIndex:null};if(!this._arrayTexturesByFileKey.has(t)){const e=this._getTextureLoader(t);let s=await e.loadAsync(this.getUri(t));s instanceof o||(s=s.texture3D),this._arrayTexturesByFileKey.set(t,s),this._retrievedTextures.push(s)}return{texture:this._arrayTexturesByFileKey.get(t),layerIndex:s}}_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){this.clearCacheByAsset(e)}clearCacheByAsset(e){null!=e&&(this.clearCacheById(e.id),null!=e.fileKey&&(Array.from(this.cache.keys()).forEach(t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)}),Array.from(this.asyncMeshResults.keys()).forEach(t=>{t.startsWith(e.fileKey)&&this.asyncMeshResults.delete(t)}),Array.from(this._animationCache.keys()).forEach(t=>{t.startsWith(e.fileKey+"|")&&this._animationCache.delete(t)}),Array.from(this._animationPromises.keys()).forEach(t=>{t.startsWith(e.fileKey+"|")&&this._animationPromises.delete(t)}),U(e.fileKey)),null!=e.materialLib&&U(e.materialLib))}clearCacheById(e){const t=Array.from(this.cache.values()).find(t=>t.scene.userData.assetId===e);t&&Array.from(this.cache.keys()).forEach(e=>{this.cache.get(e)===t&&this.cache.delete(e)}),this.textureCache.delete(e),this._texturePromises.delete(e),Array.from(this.collisionShapeCache.keys()).forEach(t=>{t.startsWith(e+"|")&&this.collisionShapeCache.delete(t)})}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new r,animations:[]};if(!j.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new r,animations:[]};const s=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(s))try{this.asyncMeshResults.has(s)||this.asyncMeshResults.set(s,this.loadMesh(e).finally(()=>this.asyncMeshResults.delete(s))),this.cache.set(s,await this.asyncMeshResults.get(s))}catch(e){return this.onError(e),{scene:new r,animations:[]}}const a=this.cache.get(s).scene,n=this.computeCollisionShapes(e,a);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(a);const o=y(a),l=this.cache.get(s).animations;o.traverse(e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())});const c=new AssetMeshInstance;c.add(o),c.collisionShapes=n,c.animations=l;const h=e.receiveShadow??!0,u=e.castShadow??!1;if(o.traverse(e=>{e.castShadow=u,e.receiveShadow=h}),!0===t?.rescale&&"number"==typeof e.mesh?.rescale&&c.scale.setScalar(e.mesh?.rescale),!0===t?.applyMaterials){const s=t?.materialResolver??this.materialProvider;if(null!=s)for(const t of e.materialAssignments??[])await R(c,t,s);else console.warn(`applyMaterials was set to true for ${e.name} but no material resolver was provided.`)}return{scene:c,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),a=r.animations.find(e=>e.name===t);return null!=a&&this._animationCache.set(s,a),a}catch(e){return this.onError(e),null}finally{setTimeout(()=>this._animationPromises.delete(s),1e3)}})();return this._animationPromises.set(s,r),r}computeCollisionShapes(e,t){if(!0!==e.collisionDetection)return[];const s=e.id+"|"+(e.mesh?.collisions?.shapeType??"")+"|"+(e.mesh?.rescale??1)+"|"+JSON.stringify(e.mesh?.colliders??[]);if(!this.collisionShapeCache.has(s)){const r=e.mesh?.colliders??[],a=r.length>0?createAuthoredCollisionShapes(r,e.mesh?.rescale):v(t,e);this.collisionShapeCache.set(s,a)}return this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then(s=>(s.scene.traverse(e=>{e instanceof i&&e.material&&function(e){let t=e.material;if(null==t)return;Array.isArray(t)?e.material=t.map(V):e.material=V(t)}(e),S(e)?e.visible=!1:e instanceof i&&e.geometry instanceof t&&(e.geometry.hasAttribute("normal")||e.geometry.computeVertexNormals())}),this._retrievedMeshes.push(s.scene),s.scene=function(e,t){let s=!1;if(t.traverseVisible(e=>{N.test(e.name)&&(s=!0)}),!s)return t;const r=new C.LOD,a=[t];for(;a.length>0;){const e=a.shift(),t=e.name.match(N);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 a.push(...e.children)}return r}(0,s.scene),function(e){const t=Y;Y.length=0,e.traverse(e=>{(e instanceof C.Camera||e instanceof C.Light)&&t.push(e)}),t.forEach(e=>e.removeFromParent())}(s.scene),s.scene.userData.assetId=e.id,s))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid),e.updateWorldMatrix(!0,!0);const s=[];e.traverse(e=>{e instanceof i&&!(e instanceof C.SkinnedMesh)&&e.geometry instanceof t&&Array.isArray(e.material)&&!S(e)&&s.push({mesh:e,geometry:e.geometry,materialArray:e.material,parent:e.parent})});for(const{mesh:t,geometry:r,materialArray:a,parent:n}of s){t.removeFromParent();for(let s=0;s<a.length;s++){const o=a[s],l=r.groups.filter(e=>e.materialIndex===s);if(0===l.length)continue;const c=this.extractGeometryGroups(r,l);c.groups.length>1&&P.mergeGroups(c);const h=new i(c,o);h.copy(t,!1),h.geometry=c,h.material=o,n?n.add(h):e.add(h)}r.dispose()}let r=!0,a=0,n=0;if(e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!S(e)){a++;const t=Object.keys(e.geometry.attributes).length;t!==n&&0!==n&&(r=!1),n=t}else(e instanceof C.SkinnedMesh||e instanceof C.Bone)&&(r=!1)}),a>1&&r){const s=new Map;e.traverse(r=>{if(r instanceof i&&r.geometry instanceof t&&!S(r)){if(Array.isArray(r.material))return;r.updateWorldMatrix(!0,!0);const t=r.material?.uuid||"default";s.has(t)||s.set(t,{material:r.material,geometries:[],objects:[]});const a=s.get(t),i=e.matrixWorld.clone().invert().multiply(r.matrixWorld);a.geometries.push(r.geometry.clone().applyMatrix4(i)),a.objects.push(r)}});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]:P.mergeGeometries(t.geometries,!0),s.groups.length>1&&P.mergeGroups(s),e.add(new i(s,t.material))}}e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!S(e)){const t=e.geometry;!Array.isArray(e.material)&&t.groups.length>1&&P.mergeGroups(t)}})}extractGeometryGroups(e,s){const r=e.index;if(!r){const r=new t;let a=0;for(const e of s)a+=e.count;if(0===a)return r;for(const t in e.attributes){const i=e.attributes[t],n=i.itemSize,o=i.array,l=new(0,o.constructor)(a*n);let c=0;for(const e of s){const t=e.start*n,s=e.count*n;for(let e=0;e<s;e++)l[c+e]=o[t+e];c+=s}const h=new C.BufferAttribute(l,n,i.normalized);r.setAttribute(t,h)}return r.groups=[{start:0,count:a,materialIndex:0}],r}const a=[];for(const e of s)for(let t=0;t<e.count;t++){const s=r.getX(e.start+t);a.push(s)}if(0===a.length)return new t;const i=new Map,n=[];let o=0;for(const e of a)i.has(e)||(i.set(e,o),o++),n.push(i.get(e));if(0===n.length||0===i.size)return new t;const l=new t;for(const t in e.attributes){const s=e.attributes[t],r=s.itemSize,a=s.array,n=new(0,a.constructor)(i.size*r);for(const[e,t]of i)for(let s=0;s<r;s++)n[t*r+s]=a[e*r+s];const o=new C.BufferAttribute(n,r,s.normalized);l.setAttribute(t,o)}const c=new((n.length>0?Math.max(...n):0)>65535?Uint32Array:Uint16Array)(n.length);for(let e=0;e<n.length;e++)c[e]=n[e];return l.setIndex(new C.BufferAttribute(c,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 u;t.materialOptions={normalizeRGB:!1};const s=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(s)}return this.objLoader.loadAsync(t).then(e=>(F(e),e)).then(e=>({scene:e,animations:e.animations}))}}disposeAll(){this.cache.clear(),this._retrievedMeshes.forEach(e=>D(e)),this._retrievedTextures.forEach(e=>e.dispose()),this._retrievedMeshes.length=0,this._retrievedTextures.length=0}}const E=new Map;function U(e){E.set(e,(E.get(e)??0)+1)}function F(e){if(e instanceof i)for(const t of T(e.material))t instanceof C.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(F)}export class AssetMeshInstance extends n{}export function createAuthoredCollisionShapes(e,t=1){const r=null!=t&&0!==t?1/t:1;return e.map(e=>{let t;switch(e.type){case"box":t=new M((new c).fromArray(e.size).multiplyScalar(r));break;case"sphere":t=new _(e.radius*r);break;case"capsule":t=new A(e.length*r,e.radius*r);break;case"cylinder":t=new L(e.radius*r,e.radius*r,e.height*r,16,new s)}return t.source=b.custom,t.offset.fromArray(e.position??[0,0,0]).multiplyScalar(r),t.rotation.fromArray(e.rotation??[0,0,0,"XYZ"]),t})}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find(e=>e.startsWith(t));return s?.substring(t.length)}function G(e){switch(e){case"clamp":return C.ClampToEdgeWrapping;case"repeat":return C.RepeatWrapping;case"mirror":return C.MirroredRepeatWrapping}return C.RepeatWrapping}function z(e){return e.texture?.colorSpace??function(e){if("exr"===e.fileFormat||e.fileKey?.toLowerCase().endsWith(".exr"))return"linear";const t=`${e.name} ${e.fileKey??""}`.toLowerCase();if($.some(e=>t.includes(e)))return"linear";return"srgb"}(e)}function O(e){return"linear"===e?C.LinearSRGBColorSpace:C.SRGBColorSpace}const $=["_normal","_nrm","_nor","_norm","_roughness","_rough","_metalness","_metallic","_metal","_ao","_ambient","_occlusion","_mask","_height","_disp","_displacement","_bump","_opacity"];new C.Matrix4;const Y=[];const N=/_LOD(\d+)$/;function V(e){let t=e instanceof C.MeshPhysicalMaterial&&0===e.sheen&&0===e.anisotropy;if("MeshLambertMaterial"===e.type||"MeshPhongMaterial"===e.type||t){let t={};(e instanceof C.MeshLambertMaterial||e instanceof C.MeshPhongMaterial||e instanceof C.MeshPhysicalMaterial)&&(t.color=e.color,t.map=e.map,t.bumpMap=e.bumpMap,t.bumpScale=e.bumpScale,t.lightMap=e.lightMap,t.lightMapIntensity=e.lightMapIntensity,t.aoMap=e.aoMap,t.aoMapIntensity=e.aoMapIntensity,t.emissiveMap=e.emissiveMap,t.alphaMap=e.alphaMap,t.envMap=e.envMap,t.envMapRotation=e.envMapRotation,t.wireframe=e.wireframe,t.wireframeLinewidth=e.wireframeLinewidth,t.fog=e.fog,t.opacity=e.opacity,t.transparent=e.transparent,t.side=e.side,t.depthTest=e.depthTest,t.depthWrite=e.depthWrite,t.alphaTest=e.alphaTest,t.displacementMap=e.displacementMap,t.displacementScale=e.displacementScale,t.displacementBias=e.displacementBias);const s=new C.MeshStandardMaterial(t);return s.userData={...e.userData??{}},s.name=e.name,s}return e}/*
|
|
1
|
+
import{AudioLoader as e,BufferGeometry as t,Euler as s,Group as r,LoadingManager as a,Mesh as i,Object3D as n,Texture as o,TextureLoader as l,Vector3 as c}from"three";import{MTLLoader as h,OBJLoader as u,LUTCubeLoader as m}from"three-stdlib";import{cloneMesh as d}from"../utils/mesh.js";import{pathJoin as p}from"../utils/files.js";import{Subject as f,firstValueFrom as y}from"rxjs";import{BoxCollisionShape as g,CapsuleCollisionShape as w,CollisionShapeSource as x,CylinderCollisionShape as M,SphereCollisionShape as A}from"./collision/collision-shape.js";import{importCollisionShapes as b,isCollisionMesh as L}from"./collision/collision-shape-import.js";import*as _ from"three";import{iterateMaterials as v}from"../utils/materials.js";import{applyMaterial as S,getConvertedFbxToGlbAssignedMaterialTextureFlipY as C}from"./materializer.js";import{BufferGeometryUtils as T,DRACOLoader as P,EXRLoader as R,FBXLoader as k,GLTFLoader as K,KTX2Loader as I,TGALoader as W,UltraHDRLoader as B}from"three/examples/jsm/Addons.js";import{disposeScene as j}from"../utils/three/cleanup.js";(()=>{const e=new Uint8Array([255,0,0,255]),t=new _.DataTexture(e,1,1,_.RGBAFormat);t.needsUpdate=!0})();const D=new P;D.setDecoderConfig({type:"js"}),D.setDecoderPath("/assets/draco/");const F=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new a,this.glbLoader=new K(this.loadingManager).setDRACOLoader(D),this.fbxLoader=new k(this.loadingManager),this.objLoader=new u(this.loadingManager),this.textureLoader=new l(this.loadingManager),this.tgaLoader=new W(this.loadingManager),this.exrLoader=new R(this.loadingManager),this.cubeLoader=new m(this.loadingManager),this.hdrLoader=new B(this.loadingManager),this.ktx2Loader=new I(this.loadingManager),this._textureLoader=new _.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this._retrievedMeshes=[],this._retrievedTextures=[],this.makeReady=new f,this.ready=y(this.makeReady),this._texturePromises=new Map,this._arrayTexturesByFileKey=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),this.ktx2Loader.setWorkerLimit(6)}setDataDir(e){this.basePath=p(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){const t=function(e){return E.get(e)}(e),s=getElectronArg("windowId");return null!=s||import.meta.url.includes(".vite")||import.meta.url.includes("hology/packages/core")?p(this.basePath,e)+(null!=s?`?windowId=${s}${null!=t?`&v=${t}`:""}`:""):new URL(p("..",this.basePath,e),import.meta.url).href}async getTexture(e){if(!e||!e.fileKey)return null;if("png"===e.fileFormat||e.fileFormat,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);if(null!=e.texture){const s=$(t,e);t.flipY!==s?(t.needsUpdate=!0,t.flipY=s):t.wrapS!==z(e.texture?.wrapS)?(t.needsUpdate=!0,t.wrapS=z(e.texture?.wrapS)):t.wrapT!==z(e.texture?.wrapT)&&(t.wrapT=z(e.texture?.wrapT),t.needsUpdate=!0)}const s=Y(O(e));t.colorSpace!==s&&(t.colorSpace=s,t.needsUpdate=!0)}else try{await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then(t=>(t.texture3D?t=t.texture3D:(t.wrapS=z(e.texture?.wrapS),t.wrapT=z(e.texture?.wrapT),t.flipY=$(t,e),t.colorSpace=Y(O(e))),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}async getTextureArray(e){const t=e.texture?.textureArrayFileKey,s=e.texture?.textureArrayLayer;if(!t||null==s)return{texture:null,layerIndex:null};if(!this._arrayTexturesByFileKey.has(t)){const e=this._getTextureLoader(t);let s=await e.loadAsync(this.getUri(t));s instanceof o||(s=s.texture3D),this._arrayTexturesByFileKey.set(t,s),this._retrievedTextures.push(s)}return{texture:this._arrayTexturesByFileKey.get(t),layerIndex:s}}_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){this.clearCacheByAsset(e)}clearCacheByAsset(e){null!=e&&(this.clearCacheById(e.id),null!=e.fileKey&&(Array.from(this.cache.keys()).forEach(t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)}),Array.from(this.asyncMeshResults.keys()).forEach(t=>{t.startsWith(e.fileKey)&&this.asyncMeshResults.delete(t)}),Array.from(this._animationCache.keys()).forEach(t=>{t.startsWith(e.fileKey+"|")&&this._animationCache.delete(t)}),Array.from(this._animationPromises.keys()).forEach(t=>{t.startsWith(e.fileKey+"|")&&this._animationPromises.delete(t)}),U(e.fileKey)),null!=e.materialLib&&U(e.materialLib))}clearCacheById(e){const t=Array.from(this.cache.values()).find(t=>t.scene.userData.assetId===e);t&&Array.from(this.cache.keys()).forEach(e=>{this.cache.get(e)===t&&this.cache.delete(e)}),this.textureCache.delete(e),this._texturePromises.delete(e),Array.from(this.collisionShapeCache.keys()).forEach(t=>{t.startsWith(e+"|")&&this.collisionShapeCache.delete(t)})}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new r,animations:[]};if(!F.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new r,animations:[]};const s=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(s))try{this.asyncMeshResults.has(s)||this.asyncMeshResults.set(s,this.loadMesh(e).finally(()=>this.asyncMeshResults.delete(s))),this.cache.set(s,await this.asyncMeshResults.get(s))}catch(e){return this.onError(e),{scene:new r,animations:[]}}const a=this.cache.get(s).scene,n=this.computeCollisionShapes(e,a);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(a);const o=d(a),l=this.cache.get(s).animations;o.traverse(e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())});const c=new AssetMeshInstance;c.add(o),c.collisionShapes=n,c.animations=l;const h=e.receiveShadow??!0,u=e.castShadow??!1;if(o.traverse(e=>{e.castShadow=u,e.receiveShadow=h}),!0===t?.rescale&&"number"==typeof e.mesh?.rescale&&c.scale.setScalar(e.mesh?.rescale),!0===t?.applyMaterials){const s=t?.materialResolver??this.materialProvider;if(null!=s)for(const t of e.materialAssignments??[])await S(c,t,s,void 0,{textureFlipY:C(e)});else console.warn(`applyMaterials was set to true for ${e.name} but no material resolver was provided.`)}return{scene:c,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),a=r.animations.find(e=>e.name===t);return null!=a&&this._animationCache.set(s,a),a}catch(e){return this.onError(e),null}finally{setTimeout(()=>this._animationPromises.delete(s),1e3)}})();return this._animationPromises.set(s,r),r}computeCollisionShapes(e,t){if(!0!==e.collisionDetection)return[];const s=e.id+"|"+(e.mesh?.collisions?.shapeType??"")+"|"+(e.mesh?.rescale??1)+"|"+JSON.stringify(e.mesh?.colliders??[]);if(!this.collisionShapeCache.has(s)){const r=e.mesh?.colliders??[],a=r.length>0?createAuthoredCollisionShapes(r,e.mesh?.rescale):b(t,e);this.collisionShapeCache.set(s,a)}return this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then(s=>(s.scene.traverse(e=>{e instanceof i&&e.material&&function(e){let t=e.material;if(null==t)return;Array.isArray(t)?e.material=t.map(J):e.material=J(t)}(e),L(e)?e.visible=!1:e instanceof i&&e.geometry instanceof t&&(e.geometry.hasAttribute("normal")||e.geometry.computeVertexNormals())}),this._retrievedMeshes.push(s.scene),s.scene=function(e,t){let s=!1;if(t.traverseVisible(e=>{X.test(e.name)&&(s=!0)}),!s)return t;const r=[],a=[t];for(;a.length>0;){const e=a.shift(),t=e.name.match(X);if(null!=t){const s=parseInt(t[1]);if(0!==s){console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`),r.push(e);continue}}a.push(...e.children)}for(const e of r)e.removeFromParent();return t}(0,s.scene),function(e){const t=V;V.length=0,e.traverse(e=>{(e instanceof _.Camera||e instanceof _.Light)&&t.push(e)}),t.forEach(e=>e.removeFromParent())}(s.scene),s.scene.userData.assetId=e.id,s))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid),e.updateWorldMatrix(!0,!0);const s=[];e.traverse(e=>{e instanceof i&&!(e instanceof _.SkinnedMesh)&&e.geometry instanceof t&&Array.isArray(e.material)&&!L(e)&&s.push({mesh:e,geometry:e.geometry,materialArray:e.material,parent:e.parent})});for(const{mesh:t,geometry:r,materialArray:a,parent:n}of s){t.removeFromParent();for(let s=0;s<a.length;s++){const o=a[s],l=r.groups.filter(e=>e.materialIndex===s);if(0===l.length)continue;const c=this.extractGeometryGroups(r,l);c.groups.length>1&&T.mergeGroups(c);const h=new i(c,o);h.copy(t,!1),h.geometry=c,h.material=o,n?n.add(h):e.add(h)}r.dispose()}let r=!0,a=0,n=0;if(e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!L(e)){a++;const t=Object.keys(e.geometry.attributes).length;t!==n&&0!==n&&(r=!1),n=t}else(e instanceof _.SkinnedMesh||e instanceof _.Bone)&&(r=!1)}),a>1&&r){const s=new Map;e.traverse(r=>{if(r instanceof i&&r.geometry instanceof t&&!L(r)){if(Array.isArray(r.material))return;r.updateWorldMatrix(!0,!0);const t=r.material?.uuid||"default";s.has(t)||s.set(t,{material:r.material,geometries:[],objects:[]});const a=s.get(t),i=e.matrixWorld.clone().invert().multiply(r.matrixWorld);a.geometries.push(r.geometry.clone().applyMatrix4(i)),a.objects.push(r)}});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]:T.mergeGeometries(t.geometries,!0),s.groups.length>1&&T.mergeGroups(s),e.add(new i(s,t.material))}}e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!L(e)){const t=e.geometry;!Array.isArray(e.material)&&t.groups.length>1&&T.mergeGroups(t)}})}extractGeometryGroups(e,s){const r=e.index;if(!r){const r=new t;let a=0;for(const e of s)a+=e.count;if(0===a)return r;for(const t in e.attributes){const i=e.attributes[t],n=i.itemSize,o=i.array,l=new(0,o.constructor)(a*n);let c=0;for(const e of s){const t=e.start*n,s=e.count*n;for(let e=0;e<s;e++)l[c+e]=o[t+e];c+=s}const h=new _.BufferAttribute(l,n,i.normalized);r.setAttribute(t,h)}return r.groups=[{start:0,count:a,materialIndex:0}],r}const a=[];for(const e of s)for(let t=0;t<e.count;t++){const s=r.getX(e.start+t);a.push(s)}if(0===a.length)return new t;const i=new Map,n=[];let o=0;for(const e of a)i.has(e)||(i.set(e,o),o++),n.push(i.get(e));if(0===n.length||0===i.size)return new t;const l=new t;for(const t in e.attributes){const s=e.attributes[t],r=s.itemSize,a=s.array,n=new(0,a.constructor)(i.size*r);for(const[e,t]of i)for(let s=0;s<r;s++)n[t*r+s]=a[e*r+s];const o=new _.BufferAttribute(n,r,s.normalized);l.setAttribute(t,o)}const c=new((n.length>0?Math.max(...n):0)>65535?Uint32Array:Uint16Array)(n.length);for(let e=0;e<n.length;e++)c[e]=n[e];return l.setIndex(new _.BufferAttribute(c,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 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=>(G(e),e)).then(e=>({scene:e,animations:e.animations}))}}disposeAll(){this.cache.clear(),this._retrievedMeshes.forEach(e=>j(e)),this._retrievedTextures.forEach(e=>e.dispose()),this._retrievedMeshes.length=0,this._retrievedTextures.length=0}}const E=new Map;function U(e){E.set(e,(E.get(e)??0)+1)}function G(e){if(e instanceof i)for(const t of v(e.material))t instanceof _.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(G)}export class AssetMeshInstance extends n{}export function createAuthoredCollisionShapes(e,t=1){const r=null!=t&&0!==t?1/t:1;return e.map(e=>{let t;switch(e.type){case"box":t=new g((new c).fromArray(e.size).multiplyScalar(r));break;case"sphere":t=new A(e.radius*r);break;case"capsule":t=new w(e.length*r,e.radius*r);break;case"cylinder":t=new M(e.radius*r,e.radius*r,e.height*r,16,new s)}return t.source=x.custom,t.offset.fromArray(e.position??[0,0,0]).multiplyScalar(r),t.rotation.fromArray(e.rotation??[0,0,0,"XYZ"]),t})}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find(e=>e.startsWith(t));return s?.substring(t.length)}function z(e){switch(e){case"clamp":return _.ClampToEdgeWrapping;case"repeat":return _.RepeatWrapping;case"mirror":return _.MirroredRepeatWrapping}return _.RepeatWrapping}function $(e,t){const s=e;return!0!==s.isCompressedTexture&&!0!==s.isCompressedArrayTexture&&(t.texture?.flipY??!0)}function O(e){return e.texture?.colorSpace??function(e){if("exr"===e.fileFormat||e.fileKey?.toLowerCase().endsWith(".exr"))return"linear";const t=`${e.name} ${e.fileKey??""}`.toLowerCase();if(N.some(e=>t.includes(e)))return"linear";return"srgb"}(e)}function Y(e){return"linear"===e?_.LinearSRGBColorSpace:_.SRGBColorSpace}const N=["_normal","_nrm","_nor","_norm","_roughness","_rough","_metalness","_metallic","_metal","_ao","_ambient","_occlusion","_mask","_height","_disp","_displacement","_bump","_opacity"];new _.Matrix4;const V=[];const X=/_LOD(\d+)/;function J(e){let t=e instanceof _.MeshPhysicalMaterial&&0===e.sheen&&0===e.anisotropy;if("MeshLambertMaterial"===e.type||"MeshPhongMaterial"===e.type||t){let t={};(e instanceof _.MeshLambertMaterial||e instanceof _.MeshPhongMaterial||e instanceof _.MeshPhysicalMaterial)&&(t.color=e.color,t.map=e.map,t.bumpMap=e.bumpMap,t.bumpScale=e.bumpScale,t.lightMap=e.lightMap,t.lightMapIntensity=e.lightMapIntensity,t.aoMap=e.aoMap,t.aoMapIntensity=e.aoMapIntensity,t.emissiveMap=e.emissiveMap,t.alphaMap=e.alphaMap,t.envMap=e.envMap,t.envMapRotation=e.envMapRotation,t.wireframe=e.wireframe,t.wireframeLinewidth=e.wireframeLinewidth,t.fog=e.fog,t.opacity=e.opacity,t.transparent=e.transparent,t.side=e.side,t.depthTest=e.depthTest,t.depthWrite=e.depthWrite,t.alphaTest=e.alphaTest,t.displacementMap=e.displacementMap,t.displacementScale=e.displacementScale,t.displacementBias=e.displacementBias);const s=new _.MeshStandardMaterial(t);return s.userData={...e.userData??{}},s.name=e.name,s}return e}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import { Mesh } from 'three';
|
|
2
|
+
import type { SceneObject } from '../materializer.js';
|
|
2
3
|
import { LandscapeMesh } from './landscape.js';
|
|
4
|
+
export interface LandscapeSectionExpansion {
|
|
5
|
+
west?: number;
|
|
6
|
+
east?: number;
|
|
7
|
+
north?: number;
|
|
8
|
+
south?: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function extendLandscapeSections(source: SceneObject, expansion: LandscapeSectionExpansion): boolean;
|
|
3
11
|
export declare function smoothNormalsCrossMeshes(meshes: LandscapeMesh[]): void;
|
|
4
12
|
export declare class SectionGrid {
|
|
5
13
|
private grid;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Vector3 as
|
|
1
|
+
import{Vector3 as t}from"three";export function extendLandscapeSections(t,r){if(null==t.landscape?.options)return!1;const s=function(t){return{west:e(t.west),east:e(t.east),north:e(t.north),south:e(t.south)}}(r),i=s.west+s.east,c=s.north+s.south;if(0===i&&0===c)return!1;const u=t.landscape.options;u.sections.x=Math.max(0,Math.floor(u.sections.x))+i,u.sections.y=Math.max(0,Math.floor(u.sections.y))+c;const a=n(u.sectionSize,0);t.position??(t.position=[0,0,0]),t.position[0]=n(t.position[0],0)+(s.east-s.west)*a/2,t.position[1]=n(t.position[1],0),t.position[2]=n(t.position[2],0)+(s.south-s.north)*a/2;for(const e of t.landscape.heightMaps??[])e.x+=s.west,e.y+=s.north;return o(t.vertexMaterials,s),o(t.landscape.holes,s),!0}function e(t){const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function n(t,e){const n="number"==typeof t?t:Number(t);return Number.isFinite(n)?n:e}function o(t,e){for(const n of t??[]){const t=r(n.m,e);null!=t&&(n.m=t)}}function r(t,e){if(null==t)return;const n=/^(-?\d+),(-?\d+)$/.exec(t);if(null==n)return;return`${Number(n[1])+e.west},${Number(n[2])+e.north}`}export function smoothNormalsCrossMeshes(e){const n=new SectionGrid(e);performance.now();const o=new t,r=new t,s=new t,i=new t;for(const t of e){const e=t.geometry.getAttribute("position"),c=t.geometry.getAttribute("normal");for(const u of m(e.count)){const{otherMesh:a,j:f}=l(u,e.count,t,n);if(null==a)continue;o.fromBufferAttribute(e,u),o.applyMatrix4(t.matrixWorld);const d=a.geometry.getAttribute("position"),h=a.geometry.getAttribute("normal");a.updateMatrixWorld(),r.fromBufferAttribute(d,f),r.applyMatrix4(a.matrixWorld),s.fromBufferAttribute(c,u),i.fromBufferAttribute(h,f);const m=s.add(i).divideScalar(2);c.setXYZ(u,m.x,m.y,m.z),h.setXYZ(f,m.x,m.y,m.z),c.needsUpdate=!0,h.needsUpdate=!0;const x=(e.getY(u)+d.getY(f))/2;e.setY(u,x),d.setY(f,x)}}performance.now()}export class SectionGrid{constructor(t){this.grid=new Map;for(const e of t){const{x:t,y:n}=e;this.grid.has(t)||this.grid.set(t,new Map),this.grid.get(t).set(n,e)}}find(t,e){return this.grid.get(t)?.get(e)}}const s={meshPredicate:(t,e)=>t.find(e.x,e.y-1),vertexFunc:(t,e)=>t+e*(e-1)},i={meshPredicate:(t,e)=>t.find(e.x-1,e.y-1),vertexFunc:(t,e)=>e*e-1},c={meshPredicate:(t,e)=>t.find(e.x+1,e.y-1),vertexFunc:(t,e)=>e*e-e},u={meshPredicate:(t,e)=>t.find(e.x,e.y+1),vertexFunc:(t,e)=>t-e*(e-1)},a={meshPredicate:(t,e)=>t.find(e.x-1,e.y+1),vertexFunc:(t,e)=>e-1},f={meshPredicate:(t,e)=>t.find(e.x+1,e.y+1),vertexFunc:(t,e)=>0},d={meshPredicate:(t,e)=>t.find(e.x-1,e.y),vertexFunc:(t,e)=>t+e-1},h={meshPredicate:(t,e)=>t.find(e.x+1,e.y),vertexFunc:(t,e)=>t-e+1};function l(t,e,n,o){const r=Math.sqrt(e),l=(t+1)%r===0,m=t%r===0;let x;if(t<r?(x=s,m&&(x=i),l&&(x=c)):t>=e-r?(x=u,m?x=a:l&&(x=f)):m?x=d:l&&(x=h),null==x)return{otherMesh:null,j:null};return{otherMesh:x.meshPredicate(o,n),j:x.vertexFunc(t,r)}}function*m(t){const e=Math.sqrt(t);for(let n=0;n<e;n++)yield n,yield n+t-e;for(let t=1,n=e-1;t<n;t++)yield t*e,yield t*e+e-1}export function onEdge(t,e){const n=Math.sqrt(e);return t<n||t%n===0||t>=e-n||(t+1)%n===0}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|