@hology/core 0.0.151 → 0.0.153
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/rates.d.ts +4 -1
- package/dist/effects/vfx/rates.d.ts.map +1 -1
- package/dist/effects/vfx/rates.js +1 -1
- package/dist/effects/vfx/vfx-asset.d.ts +1 -0
- package/dist/effects/vfx/vfx-asset.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-materializer.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/rendering/fog/fog-volume-actor.d.ts.map +1 -1
- package/dist/rendering/fog/fog-volume-actor.js +1 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/shader/builtin/decal-standard-shader.d.ts.map +1 -1
- package/dist/shader/builtin/decal-standard-shader.js +1 -1
- package/dist/shader/builtin/standard-shader.d.ts.map +1 -1
- package/dist/shader/builtin/standard-shader.js +1 -1
- package/dist/shader/parameter.d.ts +1 -0
- package/dist/shader/parameter.d.ts.map +1 -1
- package/dist/shader/sprite-shader.d.ts.map +1 -1
- package/dist/shader/sprite-shader.js +1 -1
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -3,8 +3,11 @@ import { Span, SpanValue } from '@hology/nebula';
|
|
|
3
3
|
export { Rate } from "@hology/nebula";
|
|
4
4
|
export declare class DelayRate extends Rate {
|
|
5
5
|
readonly delay: number;
|
|
6
|
-
|
|
6
|
+
duration?: number;
|
|
7
|
+
constructor(delay?: number, numPan?: number | SpanValue[] | Span, timePan?: number | SpanValue[] | Span, duration?: number);
|
|
8
|
+
private durationPlayed;
|
|
7
9
|
restart(): void;
|
|
10
|
+
getValue(time: number): number;
|
|
8
11
|
clone(): DelayRate;
|
|
9
12
|
}
|
|
10
13
|
export declare class OnceRate extends DelayRate {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rates.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/rates.ts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,QAAQ,CAAC,IAAI,KAAA;CAkBd"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Rate as t}from"@hology/nebula";export{Rate}from"@hology/nebula";export class DelayRate extends t{constructor(t=0,e,s){super(e,
|
|
1
|
+
import{Rate as t}from"@hology/nebula";export{Rate}from"@hology/nebula";export class DelayRate extends t{constructor(t=0,e,i,s){super(e,i),this.delay=t,this.duration=s,this.durationPlayed=0,this.restart()}restart(){this.durationPlayed=0,this.nextTime=0,null!=this.delay&&this.delay>0?this.startTime=-this.delay:this.startTime=0}getValue(t){return null!=this.duration&&this.duration>0&&(this.durationPlayed+=t,this.durationPlayed>=this.duration)?0:super.getValue(t)}clone(){return new DelayRate(this.delay,this.numPan,this.timePan,this.duration)}}export class OnceRate extends DelayRate{constructor(t,e=1){super(t,e,1/0),this.count=e,this.calls=0,this.nextTime=0}clone(){return new OnceRate(this.delay,this.count)}init(){this.restart()}getValue(t){return this.calls++,this.startTime+=t,this.startTime>=this.nextTime?(this.nextTime=1/0,this.count):0}}export class ConstantRate extends DelayRate{constructor(t,e=1){super(t,e,1),this.perSecond=e,this.emitted=0,this.nextTime=0}clone(){return new ConstantRate(this.delay,this.perSecond)}init(){this.restart(),this.emitted=0}getValue(t){if(this.startTime+=t,this.startTime>=this.nextTime){let t=0;for(;this.emitted+t<this.startTime*this.perSecond;)t++;return this.emitted+=t,t}return 0}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vfx-asset.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/vfx-asset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAAE,uBA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 -1,4 +1,4 @@
|
|
|
1
|
-
import e,{Behaviour as t,Body as n,Emitter as i,Rate as a}from"@hology/nebula";import*as r from"three";import{Object3D as s}from"three";import{AttributeVec3Node as o,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as u,UniformFloatNode as m,UniformVec3Node as p,Vec3ExpressionNode as d,Vec4Node as h,attributeFloat as f,attributeVec3 as y,attributeVec4 as w,attributes as g,clamp as v,float as b,glslFunction as x,lambertMaterial as M,log as A,pow as E,rgb as P,rgba as I,smoothstep as T,standardMaterial as C,textureSampler2d as S,transformed as B,uniformFloat as j,uniforms as k,varying as R,varyingAttributes as z,varyingVec3 as D,varyingVec4 as V}from"three-shader-graph";import{prepareClassParameters as L,prepareShapeParameters as O}from"../../scene/materializer.js";import{SerializedParamType as F}from"../../scene/model.js";import{ShapeLibrary as Q}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as W,linearEyeDepth as H}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as U,particleTimeUniformName as q,particleUniforms as G,particleVelcoityUniformName as J}from"../../shader-nodes/particle.js";import{sampleFlipbook as N}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as K}from"./initializsers.js";import{DelayRate as Y,OnceRate as X}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 ne}from"./vfx-collision-behaviour.js";import{SpriteNodeShaderMaterial as ie}from"../../shader/sprite-shader.js";import{DecalUnlitShader as ae}from"../../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as re}from"../../shader/builtin/decal-standard-shader.js";export async function materializeVfx(t,n,i,a,o,l){let c=n;for(;null!=c.parent;)c=c.parent;const u=new s;u.name="particle system local",n.add(u);const m=new s;m.name="particle system world";const p=new te(m,u,r,a),d=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 se(e,i,d,o,l);return t.setParentRecursive(d),t.emit()}))).forEach(e=>d.addEmitter(e)),d.addRenderer(p).emit({onEnd:()=>{}}),{container:m,system:d,dispose:()=>{m.removeFromParent(),u.removeFromParent(),p.dispose()}}}async function se(e,t,i,u,b){const E=function(e){let t;switch(e.rate.type){case"continuous":t=new Y(e.rate.delay??0,e.rate.count,e.rate.time);break;case"once":t=new X(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new a(0,1/0)}return t}(e);let P;switch(e.output.type){case"decal":P=new n(await async function(e,t){const n=!1!==e.unlit?new ae:new re;n.color=new r.Color(e.color),n instanceof ae?n.intensity=e.intensity??1:n.emissiveIntensity=e.intensity??1;if(e.colorMap){const i=await t.getTexture(e.colorMap);n.colorMap=i}if(e.alphaMap){const i=await t.getTexture(e.alphaMap);n.alphaMap=i}const i=n.build();i.blending=Z[e.blendingMode]??r.NormalBlending,i.transparent=!0,i.side=r.BackSide,i.depthTest=!1,null!=i&&!0===e.bloom&&(i.userData.hasBloom=!0);i.defines.IS_PARTICLE="";const a=new r.BoxGeometry(1,1,1),s=new r.Mesh(a,i);null!=e.renderOrder&&(s.renderOrder=e.renderOrder);return s}(e.output,t));break;case"sprite":P=new n(await async function(e,t,n){let i=null;i=null!=e.shader?await le(e,t,n):await async function(e,t){const n=null!=e.texture?await t.getTexture(e.texture):oe,i=S(n);let a=i.sample(z.uv);e.flipbook?.enabled&&(a=N(i,g.uv,e.flipbook.columns,e.flipbook.rows,G.time,e.flipbook.fps,e.flipbook.mode));const s=new m("rotation",0),o=new p("color").rgb,l=j("opacity",1),c=H.subtract(W).divide(H);let u=l;switch(e.opacityChannel??"red"){case"none":break;case"red":u=u.multiply(a.r);break;case"alpha":u=u.multiply(a.a)}if("number"==typeof e.softness&&e.softness>0){const t=v(c,0,1e3);u=u.multiply(T(0,.2*e.softness,t))}const d=x(h,{position:B.position,cameraPosition:k.cameraPosition,viewMatrix:k.viewMatrix,modelViewMatrix:k.modelViewMatrix,rotation:s},"\n // Scale from your model matrix\n vec2 scale;\n scale.x = length(vec3(modelMatrix[0].x, modelMatrix[0].y, modelMatrix[0].z));\n scale.y = length(vec3(modelMatrix[1].x, modelMatrix[1].y, modelMatrix[1].z));\n\n vec3 right, up;\n vec3 objectPos = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;\n\n #ifdef LOCK_Y_AXIS\n vec3 cameraPos = cameraPosition;\n vec3 lookDir = normalize(vec3(cameraPos.x - objectPos.x, 0.0, cameraPos.z - objectPos.z));\n right = normalize(vec3(lookDir.z, 0.0, -lookDir.x));\n up = vec3(0.0, 1.0, 0.0);\n #else\n right = vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);\n up = vec3(viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1]);\n #endif\n\n // then your shared code:\n vec2 center = vec2(0.5, 0.5);\n vec2 alignedPosition = (position.xy - (center - vec2(0.5))) * scale;\n\n vec2 rotatedPosition;\n rotatedPosition.x = cos(rotation) * alignedPosition.x - sin(rotation) * alignedPosition.y;\n rotatedPosition.y = sin(rotation) * alignedPosition.x + cos(rotation) * alignedPosition.y;\n\n vec3 billboardPos = objectPos + right * rotatedPosition.x + up * rotatedPosition.y;\n\n return projectionMatrix * viewMatrix * vec4(billboardPos, 1.0);\n ");var f=new ie({color:I(o.multiply(a.rgb).multiplyScalar(e.intensity??1),u),transparent:!0,position:d,alphaTest:1e-4,uniforms:{color:{value:new r.Color(e.color)}}});f.alphaHash=!0,null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??r.NormalBlending,f}(e,t);i instanceof r.ShaderMaterial&&!0===e.lockY&&(i.defines.LOCK_Y_AXIS="");const a=new r.Mesh(new r.PlaneGeometry(1,1),i);return a.name="sprite",a}(e.output,t,b));break;case"stretchedSprite":P=new n(await async function(e,t){const n=null!=e.texture?await t.getTexture(e.texture):oe,i=S(n).sample(z.uv),a=V(new l("color")),s=a.rgb.multiply(i.rgb);let o=a.w;switch(e.opacityChannel??"red"){case"none":break;case"red":o=o.multiply(i.r);break;case"alpha":o=o.multiply(i.a)}if("number"==typeof e.softness&&e.softness>0){const t=H.subtract(W).divide(A(H)),n=v(t,0,1e3);o=o.multiply(T(0,.2*e.softness,n))}const c=x(h,{position:g.position,offset:y("offset"),modelViewMatrix:k.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 ie({color:I(s.multiplyScalar(e.intensity??1),o),alphaTest:.1,transparent:!0,position:c,uniforms:{color:{value:new r.Color(e.color)}}});null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);u.blending=Z[e.blendingMode]??r.NormalBlending;const m=new _(new r.PlaneGeometry(1,1),u);return m.scaleFactor=e.scale,m}(e.output,t));break;case"shape":P=new n(await async function(e,t,n){if(null==e.shape)return console.log("Shape is null"),new s;const i=Q[e.shape];if(null==i)return console.error(`No shape with type ${e.shape}`),new s;const a=O(e.params??{}),l=i.geometry(a);let u=null;u=null!=e.shader?await le(e,t,n):null!=e.material?ce(await t.getMaterial(e.material)):function(){const e=R(new d("instanceColor")).rgb,t=R(new o("particleData")).x;return new c({color:M({color:e}).rgb.rgba(t),transparent:!0})}();null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);return new r.Mesh(l,u)}(e.output,t,b));break;case"mesh":P=new n(await async function(e,t,n){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new s;const i=await t.getMesh(e.assetId),a=await t.getAsset(e.assetId);if(null!=e.shader||null!=e.material){let a;a=null!=e.shader?await le(e,t,n):ce(await t.getMaterial(e.material)),null!=a&&!0===e.bloom&&(a.userData.hasBloom=!0),null!=a&&!0===e.bloom&&(a.userData.hasBloom=!0),i.traverse(e=>{e instanceof r.Mesh&&(e.material=a)})}else{const e=[];if(null!=a.materialAssignments)for(const n of a.materialAssignments)i.traverse(i=>{i instanceof r.Mesh&&i.material instanceof r.Material&&i.material.color instanceof r.Color&&(i.material.name!=n.name&&null!=n.name||"#"+i.material.color.getHexString()!==n.color||e.push(t.getMaterial(n.materialId).then(e=>i.material=e)))});await Promise.all(e)}const o=[];if(i.traverse(e=>{e instanceof r.Mesh&&o.push(e)}),1===o.length){const e=o[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 i}(e.output,t,b));break;case"trail":P=new n({type:"trail",taper:e.output.taper,headGeometry:null,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 C=new me;C.parent=i,C.setRate(E),C._space=e.output.space;const D=await Promise.all(e.initializers.filter(e=>!1!==e.enabled).filter(e=>null!=ee[e.type]).map(async e=>{const t=ee[e.type],n=await O(e.params??{});return t.build(n)}));D.push(P,new K),C.addInitializers(D);const L=await Promise.all(e.behaviours.filter(e=>!1!==e.enabled).filter(e=>null!=$[e.type]).map(async e=>{const t=$[e.type];for(const[n,i]of Object.entries(e.params))t.parameters&&null!=t.parameters[n]&&"curve"===t.parameters[n].type&&i.type!==F.Curve&&(i.type=F.Curve);const n=await O(e.params??{});return t.build(n)}).sort((e,t)=>e instanceof ne?1:0));L.push(new ue);for(const e of L)e instanceof ne&&(e.physics=u);C.addBehaviours(L);for(const n of e.children){const e=await se(n,t,i,u,b),a=new EmitterPool(()=>{const t=e.clone();return t.onExpired=()=>{const e=C.childEmitters.findIndex(e=>e.id===t.id);-1!=e&&C.childEmitters.splice(e,1),a.release(t)},t}),r=C.eventDispatcher,s=new Map;C.bindEmitterEvent=!0,r.addEventListener("PARTICLE_DEAD",e=>{const t=s.get(e.id);if(null!=t){const e=C.childEmitters.findIndex(e=>e.id===t.id);null!=e&&(t.stopEmit(),C.childEmitters.splice(e,1))}});let o="PARTICLE_CREATED";if("spawnEvent"in n)switch(n.spawnEvent){case"collision":o="PARTICLE_COLLISION";break;case"start":o="PARTICLE_CREATED"}r.addEventListener(o,e=>{const t=a.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),C.childEmitters.push(t),s.set(e.id,t),t.parentParticle=e,t.system=C.system,t.emit()})}return C}const oe=(new r.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 le(e,t,n){const i=n.get(e.shader);if(null==i)return console.error("No shader exists with name "+e.shader),new r.Material;const a=new i.type,s=await L(e.shaderParams,i.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);return Object.assign(a,s),a.build()}function ce(e){const t=R(new d("instanceColor")).rgb;let n,i=R(new o("particleData")).x;if(e instanceof r.MeshStandardMaterial||e instanceof r.MeshLambertMaterial||e instanceof r.MeshBasicMaterial){let a=t.multiply(P(e.color));null!=e.map&&(a=a.multiply(S(e.map).sample(z.uv).rgb)),null!=e.alphaMap&&(i=i.multiply(S(e.alphaMap).sample(z.uv).r)),e instanceof r.MeshStandardMaterial?n=new c({color:C({color:a,emissive:P(e.emissive),emissiveIntensity:b(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(i),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof r.MeshLambertMaterial?n=new c({color:M({color:a}).rgb.rgba(i),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof r.MeshBasicMaterial&&(n=new c({color:a.rgb.rgba(i),transparent:e.transparent,alphaTest:e.alphaTest}))}else e instanceof c&&(n=e.clone(),n.defines.IS_PARTICLE="");return null!=n&&(!0===e.userData?.hasBloom&&null!=n&&(n.userData.hasBloom=!0),n.side=e.side,n.transparent=e.transparent),n??e}class ue extends t{initialize(e){e.body instanceof r.Object3D&&e.body.traverse(e=>{if(e instanceof r.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[U]||null!=t.uniforms[q]||t.uniforms[J])}})}mutate(e,t,n){this.energize(e,t),e.target instanceof s&&e.target.traverse(t=>{if(t instanceof r.Mesh){const n=t.material;n instanceof c&&(null!=n.uniforms[U]&&(n.uniforms[U].value=this.energy),null!=n.uniforms[q]&&(n.uniforms[q].value=e.age),null!=n.uniforms[J]&&(n.uniforms[J].value=e.velocity))}})}}class me extends i{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 me;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 n,Rate as s}from"@hology/nebula";import*as r 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 m,Vec3ExpressionNode as h,Vec4Node as d,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 T,smoothstep as P,standardMaterial as B,textureSampler2d as C,uniformFloat as S,uniforms as R,varying as k,varyingAttributes as j,varyingVec3 as D,varyingVec4 as z}from"three-shader-graph";import{prepareClassParameters as V,prepareShapeParameters as F}from"../../scene/materializer.js";import{SerializedParamType as L}from"../../scene/model.js";import{ShapeLibrary as O}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 G}from"../../shader-nodes/particle.js";import{sampleFlipbook as J}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as N}from"./initializsers.js";import{DelayRate as K,OnceRate as Y}from"./rates.js";import{StretchedSprite as X}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as _,VfxInitializserLibrary as $}from"./vfx-defs.js";import{MultiRenderer as ee}from"./vfx-renderers.js";import{WorldCollisionBehaviour as te}from"./vfx-collision-behaviour.js";import{getSpritePosition as ae,SpriteNodeShaderMaterial as ne}from"../../shader/sprite-shader.js";import{DecalUnlitShader as se}from"../../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as re}from"../../shader/builtin/decal-standard-shader.js";export async function materializeVfx(t,a,n,s,o,l){let c=a;for(;null!=c.parent;)c=c.parent;const u=new i;u.name="particle system local",a.add(u);const p=new i;p.name="particle system world";const m=new ee(p,u,r,s),h=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 ie(e,n,h,o,l);return t.setParentRecursive(h),t.emit()}))).forEach(e=>h.addEmitter(e)),h.addRenderer(m).emit({onEnd:()=>{}}),{container:p,system:h,dispose:()=>{p.removeFromParent(),u.removeFromParent(),m.dispose()}}}async function ie(e,t,n,u,v){const x=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 I;switch(e.output.type){case"decal":I=new a(await async function(e,t){const a=!1!==e.unlit?new se:new re;a.color=new r.Color(e.color),a instanceof se?a.intensity=e.intensity??1:a.emissiveIntensity=e.intensity??1;if(e.colorMap){const n=await t.getTexture(e.colorMap);a.colorMap=n}if(e.alphaMap){const n=await t.getTexture(e.alphaMap);a.alphaMap=n}const n=a.build();n.blending=Z[e.blendingMode]??r.NormalBlending,n.transparent=!0,n.side=r.BackSide,n.depthTest=!1,null!=n&&!0===e.bloom&&(n.userData.hasBloom=!0);n.defines.IS_PARTICLE="";const s=new r.BoxGeometry(1,1,1),i=new r.Mesh(s,n);null!=e.renderOrder&&(i.renderOrder=e.renderOrder);return i}(e.output,t));break;case"sprite":I=new a(await async function(e,t,a){let n=null;n=null!=e.shader?await le(e,t,a):await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):oe,n=C(a);let s=n.sample(j.uv);e.flipbook?.enabled&&(s=J(n,g.uv,e.flipbook.columns,e.flipbook.rows,q.time,e.flipbook.fps,e.flipbook.mode));const i=new p("rotation",0),o=new m("color").rgb,l=S("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(P(0,.2*e.softness,t))}const h=ae(i);var d=new ne({color:T(o.multiply(s.rgb).multiplyScalar(e.intensity??1),u),transparent:!0,position:h,alphaTest:1e-4,uniforms:{color:{value:new r.Color(e.color)}}});d.alphaHash=!0,null!=d&&!0===e.bloom&&(d.userData.hasBloom=!0);return d.blending=Z[e.blendingMode]??r.NormalBlending,d}(e,t);n instanceof r.ShaderMaterial&&!0===e.lockY&&(n.defines.LOCK_Y_AXIS="");const s=new r.Mesh(new r.PlaneGeometry(1,1),n);return s.name="sprite",s}(e.output,t,v));break;case"stretchedSprite":I=new a(await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):oe,n=C(a).sample(j.uv),s=z(new l("color")),i=s.rgb.multiply(n.rgb);let o=s.w;switch(e.opacityChannel??"red"){case"none":break;case"red":o=o.multiply(n.r);break;case"alpha":o=o.multiply(n.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(P(0,.2*e.softness,a))}const c=A(d,{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 ne({color:T(i.multiplyScalar(e.intensity??1),o),alphaTest:.1,transparent:!0,position:c,uniforms:{color:{value:new r.Color(e.color)}}});null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);u.blending=Z[e.blendingMode]??r.NormalBlending;const p=new X(new r.PlaneGeometry(1,1),u);return p.scaleFactor=e.scale,p}(e.output,t));break;case"shape":I=new a(await async function(e,t,a){if(null==e.shape)return console.log("Shape is null"),new i;const n=O[e.shape];if(null==n)return console.error(`No shape with type ${e.shape}`),new i;const s=F(e.params??{}),l=n.geometry(s);let u=null;u=null!=e.shader?await le(e,t,a):null!=e.material?ce(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),transparent:!0})}();null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);return new r.Mesh(l,u)}(e.output,t,v));break;case"mesh":I=new a(await async function(e,t,a){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new i;const n=await t.getMesh(e.assetId),s=await t.getAsset(e.assetId);if(null!=e.shader||null!=e.material){let s;s=null!=e.shader?await le(e,t,a):ce(await t.getMaterial(e.material)),null!=s&&!0===e.bloom&&(s.userData.hasBloom=!0),null!=s&&!0===e.bloom&&(s.userData.hasBloom=!0),n.traverse(e=>{e instanceof r.Mesh&&(e.material=s)})}else{const e=[];if(null!=s.materialAssignments)for(const a of s.materialAssignments)n.traverse(n=>{n instanceof r.Mesh&&n.material instanceof r.Material&&n.material.color instanceof r.Color&&(n.material.name!=a.name&&null!=a.name||"#"+n.material.color.getHexString()!==a.color||e.push(t.getMaterial(a.materialId).then(e=>n.material=e)))});await Promise.all(e)}const o=[];if(n.traverse(e=>{e instanceof r.Mesh&&o.push(e)}),1===o.length){const e=o[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 n}(e.output,t,v));break;case"trail":I=new a({type:"trail",taper:e.output.taper,headGeometry:null,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 B=new pe;B.parent=n,B.setRate(x),B._space=e.output.space;const D=await Promise.all(e.initializers.filter(e=>!1!==e.enabled).filter(e=>null!=$[e.type]).map(async e=>{const t=$[e.type],a=await F(e.params??{});return t.build(a)}));D.push(I,new N),B.addInitializers(D);const V=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,n]of Object.entries(e.params))t.parameters&&null!=t.parameters[a]&&"curve"===t.parameters[a].type&&n.type!==L.Curve&&(n.type=L.Curve);const a=await F(e.params??{});return t.build(a)}).sort((e,t)=>e instanceof te?1:0));V.push(new ue);for(const e of V)e instanceof te&&(e.physics=u);B.addBehaviours(V);for(const a of e.children){const e=await ie(a,t,n,u,v),s=new EmitterPool(()=>{const t=e.clone();return t.onExpired=()=>{const e=B.childEmitters.findIndex(e=>e.id===t.id);-1!=e&&B.childEmitters.splice(e,1),s.release(t)},t}),r=B.eventDispatcher,i=new Map;B.bindEmitterEvent=!0,r.addEventListener("PARTICLE_DEAD",e=>{const t=i.get(e.id);if(null!=t){const e=B.childEmitters.findIndex(e=>e.id===t.id);null!=e&&(t.stopEmit(),B.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"}r.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(),B.childEmitters.push(t),i.set(e.id,t),t.parentParticle=e,t.system=B.system,t.emit()})}return B}const oe=(new r.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 le(e,t,a){const n=a.get(e.shader);if(null==n)return console.error("No shader exists with name "+e.shader),new r.Material;const s=new n.type,i=await V(e.shaderParams,n.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);return Object.assign(s,i),s.build()}function ce(e){const t=k(new h("instanceColor")).rgb;let a,n=k(new o("particleData")).x;if(e instanceof r.MeshStandardMaterial||e instanceof r.MeshLambertMaterial||e instanceof r.MeshBasicMaterial){let s=t.multiply(I(e.color));null!=e.map&&(s=s.multiply(C(e.map).sample(j.uv).rgb)),null!=e.alphaMap&&(n=n.multiply(C(e.alphaMap).sample(j.uv).r)),e instanceof r.MeshStandardMaterial?a=new c({color:B({color:s,emissive:I(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof r.MeshLambertMaterial?a=new c({color:E({color:s}).rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof r.MeshBasicMaterial&&(a=new c({color:s.rgb.rgba(n),transparent:e.transparent,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 ue extends t{initialize(e){e.body instanceof r.Object3D&&e.body.traverse(e=>{if(e instanceof r.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[H]||null!=t.uniforms[U]||t.uniforms[G])}})}mutate(e,t,a){this.energize(e,t),e.target instanceof i&&e.target.traverse(t=>{if(t instanceof r.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[G]&&(a.uniforms[G].value=e.velocity))}})}}class pe extends n{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 pe;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}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fog-volume-actor.d.ts","sourceRoot":"","sources":["../../../src/rendering/fog/fog-volume-actor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAY,MAAM,OAAO,CAAC;AACxC,OAAO,EAAiB,SAAS,EAAa,MAAM,gBAAgB,CAAC;AAIrE,qBACa,SAAU,SAAQ,SAAS;IAGtC,WAAW,EAAE,MAAM,CAAM;IAGzB,aAAa,EAAE,MAAM,CAAI;IAGzB,YAAY,EAAE,MAAM,CAAI;IAGxB,aAAa,EAAE,MAAM,CAAI;
|
|
1
|
+
{"version":3,"file":"fog-volume-actor.d.ts","sourceRoot":"","sources":["../../../src/rendering/fog/fog-volume-actor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAY,MAAM,OAAO,CAAC;AACxC,OAAO,EAAiB,SAAS,EAAa,MAAM,gBAAgB,CAAC;AAIrE,qBACa,SAAU,SAAQ,SAAS;IAGtC,WAAW,EAAE,MAAM,CAAM;IAGzB,aAAa,EAAE,MAAM,CAAI;IAGzB,YAAY,EAAE,MAAM,CAAI;IAGxB,aAAa,EAAE,MAAM,CAAI;IASzB,sBAAsB,EAAE,MAAM,CAAI;IAGlC,MAAM,EAAE,KAAK,CAAoB;IAEjC,OAAO,CAAC,MAAM,CAEZ;IAEF,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI;CAI/B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{Color as i}from"three";import{Actor as o,attach as s,BaseActor as r,Parameter as n}from"../../gameplay";import{FogVolumeObject as a}from"./fog-volume-object";import{EditorSpriteComponent as p}from"../../gameplay/actors/builtin/components/editor-sprite-component";let h=class extends r{constructor(){super(...arguments),this.baseDensity=.5,this.heightFalloff=1,this.heightOffset=0,this.startDistance=3,this.scatteringDistribution=0,this.albedo=new i(1,1,.6),this.sprite=s(p,{file:"assets/cloud-icon.webp"})}onInit(){this.object.add(new a(this))}};e([n({range:[0,5],stepSize:.01,help:"The density (or thickness) of fog."}),t("design:type",Number)],h.prototype,"baseDensity",void 0),e([n(),t("design:type",Number)],h.prototype,"heightFalloff",void 0),e([n(),t("design:type",Number)],h.prototype,"heightOffset",void 0),e([n(),t("design:type",Number)],h.prototype,"startDistance",void 0),e([n({range:[-1,1],help:"\n Controls the direction in which light scatters inside the fog.\n\n - Positive values (> 0): More light is scattered forward, making beams and shafts more visible when looking toward the directional light source. (for dramatic god rays).\n - Zero: Even scattering in all directions—fog appears uniform.\n - Negative values (< 0): Fog is brighter when looking away from the directional light source.\n "}),t("design:type",Number)],h.prototype,"scatteringDistribution",void 0),e([n(),t("design:type",i)],h.prototype,"albedo",void 0),h=e([o()],h);export{h as FogVolume};/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{ConvexPolyhedronCollisionShape as a}from"@hology/core";import{Subject as s}from"rxjs";import*as r from"three";import{BoxGeometry as i,Color as n,Euler as o,Fog as l,FogExp2 as c,Group as h,Material as d,Matrix4 as m,Mesh as p,MeshLambertMaterial as u,MeshPhongMaterial as f,MeshStandardMaterial as g,Object3D as y,PointLight as w,Quaternion as v,Scene as b,Texture as A,Vector2 as S,Vector3 as M,Vector4 as j}from"three";import x,{SpriteRenderer as P}from"@hology/nebula";import{bool as I,BooleanNode as D,float as C,FloatNode as E,NodeShaderMaterial as V,rgb as O,RgbNode as k,Texture2dLookupNode as N,textureSampler2d as F,vec2 as T,Vec2Node as z,vec3 as B,Vec3Node as _,vec4 as L}from"three-shader-graph";import{Service as W}from"typedi";import{VfxActor as $}from"../effects/vfx/vfx-actor.js";import{VisualEffect as R}from"../effects/vfx/vfx-param.js";import{BaseActor as G}from"../gameplay/actors/actor.js";import U from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as H,ThreeBlendingMode as J,withInjectionContext as q}from"../gameplay/index.js";import{RenderingView as X}from"../rendering.js";import{Sampler2DNode as Y}from"../shader-nodes/index.js";import{LambertShader as Z}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as K}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as Q}from"../shader/builtin/landscape-shader.js";import{StandardShader as ee}from"../shader/builtin/standard-shader.js";import{UnlitShader as te}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as ae}from"../shader/parameter.js";import{ArrayMap as se,groupBy as re}from"../utils/collections.js";import{iterateMaterials as ie}from"../utils/materials.js";import{filterChildrenShallow as ne,filterSceneShallow as oe,findFirstVisibleObject as le}from"../utils/three/traverse.js";import{AssetMeshInstance as ce,AssetResourceLoader as he}from"./asset-resource-loader.js";import{isCollisionMesh as de}from"./collision/collision-shape-import.js";import{BoxCollisionShape as me,PhysicalShapeMesh as pe}from"./collision/collision-shape.js";import{LandscapeManager as ue}from"./landscape/landscape-manager.js";import{initLandscape as fe}from"./landscape/landscape.js";import{SectionGrid as ge,smoothNormalsCrossMeshes as ye}from"./landscape/utils.js";import{createGrassFoliageMaterial as we}from"./materials/grass-foliage.js";import{createGrassMaterial as ve}from"./materials/grass.js";import{getMaterialAttribute as be}from"./materials/utils/material-painting.js";import{createWaterMaterial as Ae}from"./materials/water.js";import{SerializedParamType as Se}from"./model.js";import{ShapeLibrary as Me,ShapeLibraryKeys as je}from"./objects/shapes.js";import{ambientLightName as xe,createSky as Pe,defaultSkyMaterial as Ie}from"./sky.js";import{Curve2 as De}from"../utils/curve.js";import{DecalUnlitShader as Ce}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as Ee}from"../shader/builtin/decal-standard-shader.js";import{ColorLayer as Ve,defaultValueColorLayer as Oe,defaultValueMaskLayer as ke,MaskLayer as Ne}from"../shader/color-layer.js";import{LayeredShader as Fe}from"../shader/builtin/layered-shader";import{isColorLayerSerialized as Te}from"../shader/color-layer";import{FogVolume as ze}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as Be}from"../utils/three/unscaled-sprite.js";import{ToonShader as _e}from"../shader/builtin/toon-shader.js";const Le={},We=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),$e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPad"))&&!!navigator.userAgent.match(/AppleWebKit/)&&!navigator.userAgent.match(/CriOS/);export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,a){this.dataProvider=e,this.assetsService=t,this.assetManagerService=a}get(e,t){return new Re(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let Re=class{constructor(e,t,a,i,n,o,l,c){this.scene=e,this.dataProvider=t,this.assetsService=a,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new s,this.removed$=new s,this.error$=new s,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.prefabInstanceChain=[],this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,t.onCreate(e=>this.update(e)),t.onUpdate(e=>this.update(e)),t.onRemove(e=>this.remove(e)),this.createAssetSubscription=a.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=a.onUpdate.subscribe(async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse(e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)}):"mesh"==t.type?(this.findByAssetId(t.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src)}),this.landscapeManagers.forEach(e=>{const a=e.source?.grass?.layers?.some(e=>e.meshes.some(e=>e.assetId===t.id));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new M,!0)})):"prefab"===t.type?this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}):"vfx"===t.type&&this.dataProvider.getObjects().forEach(e=>{Qe(e,(e,a)=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),this.materializeAndInitActor(e))})})})}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===Se.Material&&s.value===a.id){t=!0;break}if(s.type===Se.Array&&"element"in s&&s.element===Se.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1),n=i.userData;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,null!=s?at(e.material[s],i)||(e.material[s]=i):at(e.material,i)||(e.material=i,e===this.sky&&this.applySkySettings(e.material))}getTopLevelActors(){return Array.from(this.materializedActors.entries()).filter(([e,t])=>!e.includes("/")).map(([,e])=>e)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter(e=>"shape_mesh"===e.type||"asset_mesh"===e.type).filter(e=>null!=e.materialAssignments).flatMap(e=>e.materialAssignments).map(async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===Se.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}})),0!==e.length&&this.renderingView){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter(e=>null!=e.assetId&&"asset_mesh"==e.type).filter(e=>e.assetId)));await Promise.all(e.map(e=>this.assetsService.getAsset(e.assetId).then(e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))),this.initTextures()}async init(){await this.preInit(),Ue.clear(),He.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit()}initActorsPostInit(e=this.getTopLevelActors(),t){const a=e.map(async e=>{const a=e.object.userData.src??e.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s=await this.assetsService.getAsset(a.assetId),r={...s?.actor?.params??{},...a.actor?.params??{}},i=null!=t?new Map(Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(t.sceneObjectChain.join("/"))&&e.split("/").length-1===t.sceneObjectChain.length).map(([e,t])=>[e.split("/").pop(),t])):this.materializedActors;for(const t of a.actor.innerParams??[])await this.applyActorComponentParams(e,t.path.slice(),t.params,i);const n=await prepareClassParameters(r,e.constructor,this.assetsService,this.assetManagerService,i,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,n);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(a)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a,s){const r=t.length,i=t.shift();if(0==r){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,s,this.renderingView,this.shaders,this.actorProvider);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[i]&&await this.applyActorComponentParams(e[i],t,a,s)}canObjectBeInstanced(e){return e.physics?.type!==H.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){if(!this._canBeInstancedCache.has(e.assetId)){const t=await this.createFromAsset(e);if(null==t)return!1;const a=[];t.traverse(e=>{!de(e)&&e.isMesh&&a.push(e)});const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof p&&null!=a[0].geometry.morphAttributes&&Object.keys(a[0].geometry.morphAttributes).length>0,i=!0;this._canBeInstancedCache.set(e.assetId,s&&i&&!r)}return this._canBeInstancedCache.get(e.assetId)}async preInit(){this.renderingView?.onLoop(()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)}),this.assetsService.getAssets().then(e=>{for(const t of e)this.assets.set(t.id,t)})}shouldBeMaterialized(e){if(null!=this.detailTier&&"asset_mesh"===e.type&&null!=e.assetId){const t=this.assets.get(e.assetId);if(null!=t){const e=t.mesh?.detailTier;if(null!=e)return e<=this.detailTier}}return!0}async initWithInstancing(){await this.preInit(),await this.prefetchAssets(),Ue.clear(),He.clear();const e=[],t=new se,s=new se;for(const a of this.dataProvider.getObjects())await Qe(a,async(a,r,i)=>{if(!this.shouldBeMaterialized(a))return;const o="asset_mesh"==a.type&&this.canObjectBeInstanced(a)&&await this.canAssetBeInstanced(a),l="shape_mesh"===a.type&&"landscape"!==a.shape&&a.physics?.type!==H.dynamic;if(o||l){if(r&&r.children?.length>0){const e=r.children.findIndex(e=>e.id===a.id);e>=0&&r.children.splice(e,1)}if(l){let e=a.shape+JSON.stringify(a.shapeParams??{})+a.castShadow+a.receiveShadow;const t=a.materialAssignments?.at(0)?.materialId,r=null!=t?this.assets.get(t):null;let o=null;if(null!=r&&"shader"!==r.material.type){if(e+=r.material.type+r.material.shader,null!=r.material.shaderParams){if(e+=Object.entries(r.material.shaderParams).filter(([e,t])=>"color"!=e).map(e=>JSON.stringify(e)).join(),null!=r.material.shaderParams.color){const e=r.material.shaderParams.color;e.type===Se.Color&&null!=e.value&&(o=new n(e.value))}}}else e+=t;s.push(e,{object:{...a,parentTransform:i},color:o})}else{const e=a.assetId+JSON.stringify(a.materialAssignments??[]);t.push(e,{...a,parentTransform:i})}}else null==r&&e.push({...a,parentTransform:i})});for(const e of t.values()){if(0==e.length)continue;const t=await this.createFromAsset(e[0]);if(null==t)continue;const s=await this.createInstancedMesh(e,t),r=new ce;r.add(s),r.userData.src=e[0],t instanceof ce&&(r.collisionShapes=t.collisionShapes),r.collisionShapes.forEach(e=>{e instanceof a&&e.mesh instanceof p&&(e.mesh=e.mesh.geometry)}),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of s.values()){if(0==e.length)continue;const t=e[0].object,a=await this.createFromShape(t),s=le(a,e=>!de(e)&&null!=e.geometry),i=s.material.clone();null!=e[0].color&&null!=i.color&&(i.color=new n(16777215));const l=s.geometry;let c,h;!($e||i instanceof V)?(c=new r.BatchedMesh(e.length,l.getAttribute("position").count,l.index.count,i),c.perObjectFrustumCulled=!0,h=c.addGeometry(l)):c=new r.InstancedMesh(l,i,e.length),c.castShadow=a.castShadow??!0,c.receiveShadow=s.receiveShadow??!0;for(let t=0;t<e.length;t++){const a=e[t],s=(new r.Matrix4).compose((new M).fromArray(a.object.position),(new v).setFromEuler((new o).fromArray(a.object.rotation)),(new M).fromArray(a.object.scale)),i=(new m).copy(a.object.parentTransform).multiply(s);let n;n=c instanceof r.BatchedMesh?c.addInstance(h):t,c.setMatrixAt(n,i),null!=a.color&&c.setColorAt(n,a.color)}for(let t=0;t<e.length;t++){const s=e[t],r=new ce;r.userData.src=e[0],a instanceof pe&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r),r.add(c),null==c.userData.hasCollision&&(c.userData.hasCollision=[]),c.userData.hasCollision[t]=!!s.object.collisionDetection}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const a=le(t,e=>!de(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,et(e[0].materialAssignments,s.materialAssignments)),a.updateMatrix();const i=a.geometry.clone(),n=a.material;let l,c;if(!($e||n instanceof V||!(i.groups.length<2)||Array.isArray(n)&&1!=n.length)){const t=Array.isArray(n)?n[0]:n,a=i.getAttribute("position").count;l=new r.BatchedMesh(e.length,a,null!=i.index?i.index.count:a,t),l.perObjectFrustumCulled=!0,c=l.addGeometry(i)}else l=new r.InstancedMesh(i,n,e.length);for(let t=0;t<e.length;t++){let s=t;l instanceof r.BatchedMesh&&(s=l.addInstance(c));const i=(new r.Matrix4).compose((new M).fromArray(e[t].position),(new v).setFromEuler((new o).fromArray(e[t].rotation)),(new M).fromArray(e[t].scale)),n=(new m).copy(e[t].parentTransform).multiply(i).multiply(a.matrixWorld);l.setMatrixAt(s,n),null==l.userData.hasCollision&&(l.userData.hasCollision=[]),l.userData.hasCollision[t]=!!e[t].collisionDetection}if(l.castShadow=e[0].castShadow??s.castShadow??!0,l.receiveShadow=e[0].receiveShadow??s.receiveShadow??!0,a.material instanceof d&&l.castShadow&&l.receiveShadow)if(Array.isArray(n))for(const e of n)e.side=r.FrontSide;else n.side=r.FrontSide;return l}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else"prefab"===e.type&&this.materializedActors.forEach((t,a)=>{a.startsWith(e.id)&&(t.disposed.next(!0),t.onEndPlay()),this.materializedActors.delete(a)});const t=this.sceneObjectMap.get(e.id);t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter(t=>t.object.userData.src?.id===e.id).forEach(e=>this.components.splice(this.components.indexOf(e,1))),this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))}),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex(t=>t.source.id===e.id);if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return oe(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t)))}async applyMaterial(e,t){await applyMaterial(e,t,e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}},this._originalMaterials)}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof p)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material})}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(U));oe(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of Ue.entries())t.userData.customShaderName&&Ue.delete(e);this.landscapeManagers.forEach(t=>t.updateShaders(e)),oe(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof p)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}})})}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(s=!0)}),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof p&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof p&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);et(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)),this.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new n(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0),a.userData.volumetricIntensity=e.light.point.volumetricIntensity}else if("spot"==e.light.type){const a=t;a.color=new n(e.light.spot.color),a.intensity=e.light.spot.intensity,a.decay=e.light.spot.decay,a.angle=e.light.spot.angle,a.penumbra=e.light.spot.penumbra,a.castShadow=e.light.spot.castShadow,a.distance=Math.max(e.light.spot.distance,0),a.userData.volumetricIntensity=e.light.spot.volumetricIntensity}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional,e):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,e=>!0)})}else if("global_fog"===e.type){const t=(this.scene.fog instanceof c?"density":"linear")!==e.fog.type;this.scene.fog=Ze(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof p){const t=e.material;t instanceof V&&(a.fog instanceof l?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof c&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.materializedActors.get(e.id);if(t instanceof ze){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);null!=a&&a===JSON.stringify(e.actor)||s||(this.remove(e),await this.materializeAndInitActor(e))}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof pe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&Ge(t,e.castShadow,e.receiveShadow),e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t);return Qe(e,async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}}),a}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:ne(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?oe(this.scene,e=>e.userData?.src?.id===t.id,e=>null!=e.userData?.src)[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new n(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof p&&e.geometry&&(t=e)}),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=re(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof p){if(null==e.geometry)return;if(st(be(e,0,!1)),a>0){st(be(e,0,!1))}}});const r=new Set;for(const[e,i]of s.entries()){const s=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==s||null==s.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=be(s,0,!0);st(o);for(const e of i)o.setX(e.i,e.w[0]??0),o.setY(e.i,e.w[1]??0),o.setZ(e.i,e.w[2]??0),o.setW(e.i,e.w[3]??0),n=!0;if(a>0){const e=be(s,4,!0);st(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&r.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>r.has(e.name)))}async materialize(e,t,a=!1,s){if(!this.shouldBeMaterialized(e))return;let r,n;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Ze(e.fog),this.fixFogColor(),r=new h;break;case"sky":this.sky=Pe(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new h,this.worldEnvObj=r;break;case"actor":({object:r,actor:n}=await this.createFromActor(e,s));break;case"group":r=new h;break;case"prefab":r=await this.createFromPrefab(e,s);break;case"vfx":r=await this.createFromVfx(e,s);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,null!=n&&(r.userData.actor=n),this.inEditor,this.inEditor){let e=null;r instanceof pe&&(e=function(e){if(e instanceof me)return new p(new i(...e.offset.toArray()),Ke);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}if(this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==H.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,r,a))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==H.dynamic||Ye(r),null!=this.renderingView)return this.renderingView.renderer.shadowMap.needsUpdate=!0,r;console.warn("RenderingView not found in materializer. No idea what called this")}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao),this.renderingView.aoPass.output=!0===e.worldEnv.ao.onlyAO?5:0;const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const a=e.worldEnv.environment;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{null==this.pmremGenerator&&(this.pmremGenerator=new r.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=a.intensity??1}):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=Ie);const t=await this.assetsService.getAsset(e.sky.materialId),a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);this.applySkySettings(a),null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}applySkySettings(e){e.side=r.BackSide,(e instanceof g||e instanceof r.MeshBasicMaterial||e instanceof r.ShaderMaterial)&&(e.fog=!1)}async createComponent(e,t,a,s){const r=new Le[a.path+"/"+a.className],i=t.id+s;r.id=i,r.object=e;for(const e of a.params)null!=e.value&&(r[e.name]=e.value);return this.components.push(r),i}async createFromActor(e,t){const a=this.actorTypes.find(t=>t.name===e.actor?.type)?.type??U[e.actor?.type];if(null==a)return{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new M).fromArray(e.position),(new o).fromArray(e.rotation),!0);return this.materializedActors.set(this.getNestedActorId(e.id,t),s),{object:s?.object,actor:s}}getNestedActorId(e,t){return null!=t?t.sceneObjectChain.join("/")+"/"+e:e}async createFromVfx(e,t){const a=await this.assetsService.getAsset(e.assetId);null==a&&console.error("Could not find asset",e);const s=await this.actorProvider.create($,(new M).fromArray(e.position),(new o).fromArray(e.rotation),!1);try{await s.fromAsset(a)}catch(e){return console.error("Failed to create VFX asset",e),null}return s.play(),this.materializedActors.set(this.getNestedActorId(e.id,t),s),null!=s&&(s.object.userData.actor=s),s?.object}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse(e=>{e instanceof p&&this._originalMaterials.set(e.id,e.material)});else{let s=new g({name:"Default",color:new n("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.castShadow??!1,e.collisionDetection||(r.collisionShape=null),r.physics=e.physics,a=r,this._originalMaterials.set(a.id,r.material),a.traverse(e=>{})}return t||(await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(a,e))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new h;const a=fe(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new ue(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,t=>{(e.materialAssignments??[]).filter(e=>null!=e.materialId).forEach(e=>this.applyMaterial(t,e))});return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new ge(e.sections);for(const e of t??[]){const t=s.find(e.x,e.y);if(!t)return;const a=t.geometry.getAttribute("position");for(const t of e.points)a.setY(t.i,t.y);a.needsUpdate=!0}const r=e.sections;r.forEach(e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()}),this.inEditor&&!a||setTimeout(()=>ye(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&je.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Me[e].geometry(s);t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Me[e].collision(s));return new pe(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async createFromAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:a}=await this.assetManagerService.getMesh(t,{mergeGeomtries:!0});et(e.materialAssignments,t.materialAssignments).forEach(e=>this.applyMaterial(a,e));const s=e.receiveShadow??!!t.receiveShadow??!0,r=e.castShadow??!!t.castShadow??!1;return a.receiveShadow=s,Ge(a,r,s),e.collisionDetection||(a.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(a.physics=e.physics),this.applyVertexMaterials(e,a),a.traverse(e=>{e instanceof p&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),a}async createFromPrefab(e,t){const a=await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);null==t&&(t={sceneObjectChain:[]}),t.sceneObjectChain.push(e.id);const{object:s}=await this.createFromPrefabAsset(a,t);return t.sceneObjectChain.pop(),s}async createFromPrefabAsset(e,t){const a=new h;await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,a,!0,structuredClone(t))));const s=t.sceneObjectChain.join("/"),r=Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(s)&&e.split("/").length-1===t.sceneObjectChain.length).map(([,e])=>e);r.forEach(e=>{a.add(e.object)}),this.initActorsPostInit(r,structuredClone(t));const i=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(s)).map(([,e])=>e);return{object:a,actors:i}}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),a=new y;return await x.fromJSONAsync(t.particleSystem,r).then(e=>{const t=new P(a,r);e.addRenderer(t),this.renderingView.onLoop(t=>e.update())}),a}async createLight(e){if("point"===e.light.type){const t=new w(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new Be(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new r.SpotLight(e.light.spot.color,e.light.spot.intensity,e.light.spot.distance,e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.target=new y,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new Be(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new r.SpotLightHelper(t))}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new h):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new h):void 0}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===xe);null!=s?(s.intensity=t.intensity,s.color.set(t.color),s.groundColor.set(t.color),s.userData.src=a,s.userData.volumetricIntensity=t.volumetricIntensity):console.warn("Couldn't find ambient light")}applyDirectionalLight(e,t){for(const a of this.renderingView.csm.lights)a.intensity=e.intensity,a.color.set(e.color),a.castShadow=e.castShadow,a.userData.src=t,a.userData.volumetricIntensity=e.volumetricIntensity;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach(e=>e.disposed.next(!0)),this.materializedActors.clear()}};Re=e([W(),t("design:paramtypes",[b,Object,Object,he,X,Array,Array,Object])],Re);export{Re as SceneMaterializer};function Ge(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const Ue=new Map,He=new Map,Je=new u({color:16711935}),qe=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&Ue.has(n)?Ue.get(n):i&&He.has(n)?await He.get(n):He.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,a,s,i,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new n(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(c.map=await i.getTexture(a))}let d;switch(t.material.type){case"phong":d=new f({...c,...h});break;case"water":d=Ae(c,a);break;case"grassFoliage":d=we({color:c.color,map:c.map},a);break;case"grass":d=ve({...c,colorTwo:new n(t.material.params.colorTwo),colorThree:new n(t.material.params.colorThree)},a);break;case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:We?Z:ee,lambert:Z,unlit:te,toon:_e,layered:Fe,landscape:Q,"landscape-composite":K,"decal-unlit":Ce,"decal-standard":Ee}[t.material.type]??o.find(e=>e.name==t.material.shader)?.type;if(e){try{let r=new e;const n=await prepareClassParameters(t.material?.shaderParams??{},e,s,i,null,a,o);Object.assign(r,n),d=r.build()}catch(e){console.log("Shader runtime error: "+e),qe.has(t.material.shader)||qe.set(t.material.shader,Je.clone()),d=qe.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=Je;break;default:throw new Error("Unsupported material type"+t.material.type)}return a?.csm.setupMaterial(d),null!=a&&Ue.set(e,d),d.side=t.material.side??d.side??r.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,null!=t.material.blending&&(d.blending=J[t.material.blending]??r.NormalBlending),t.material.bloom&&(d.userData.hasBloom=!0),t.material.reflective&&(d.userData.reflective=!0),!0===t.material.outlines&&(d.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(d.userData.outlineParameters.color=new n(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(d.userData.outlineParameters.thickness=t.material.outlineParams.thickness))),d.userData.assetId=t.id,He.delete(e),d}export async function prepareClassParameters(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await Xe(t,c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await Xe(a,s,null,null,null);null!=e&&(t[a]=e)}return t}async function Xe(e,t,a,s,r,i,l,c,h=t.value,d=t.type){if(null==t||null==h||""===h)return null;switch(d){case Se.Array:if(Array.isArray(h)&&"element"in t)return await Promise.all(h.map(n=>Xe(e,t,a,s,r,i,l,c,n,t.element)));break;case Se.Number:case Se.FloatNode:let d="string"==typeof h?parseFloat(h):h;return t.type===Se.FloatNode?C(d):d;case Se.Texture:let m=await s.getTexture(await a.getAsset(h));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case Se.Sampler2DNode:return F(await s.getTexture(await a.getAsset(h)));case Se.Boolean:return h;case Se.BooleanNode:return I(h);case Se.Vector2:case Se.Vec2Node:if("object"==typeof h){const e=h instanceof Array?(new S).fromArray(h):new S(h.x,h.y);return t.type===Se.Vec2Node?T(e):e}return null;case Se.Vector3:case Se.Vec3Node:if("object"==typeof h){const e=h instanceof Array?(new M).fromArray(h):new M(h.x,h.y,h.z);return t.type===Se.Vec3Node?B(e):e}return null;case Se.Color:case Se.RgbNode:const p=new n(h);return t.type===Se.RgbNode?O(p):p;case Se.String:return h;case Se.BaseActor:const u=h;return null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),r?.get(u);case Se.Euler:const f=h;return(new o).fromArray(f);case Se.Object3D:return(await s.getMesh(await a.getAsset(h))).scene;case Se.Material:return await materialFromAsset(await a.getAsset(h),i,a,s,l);case Se.AudioBuffer:return await s.getAudio(await a.getAsset(h));case Se.VisualEffect:const g=await a.getAsset(h);if(null==c){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in g)return new R(c,g);console.error("Using a non-vfx asset for visual effect parameter");break;case Se.Curve:return De.decode(h);case Se.ColorLayer:case Se.MaskLayer:if(Te(h)){const e=await Ve.decode(h,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(h.params,null,a,s);return Object.assign(e,t),e}return console.warn("Expecting color layer but got",h),null}return null}function Ye(e){e.updateWorldMatrix(!0,!0),e.updateMatrix(),e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1});const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}function Ze(e){return"linear"===e.type?new l(new n(e.color),e.near??100,e.far??1e3):"density"===e.type?new c(e.color,e.density):void console.warn("Invalid fog type",e)}const Ke=new g({color:4229780});async function Qe(e,t,a,s){null==s&&(s=(new m).identity()),await t(e,a,s);const i=s.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new M).fromArray(e.position),(new v).setFromEuler((new o).fromArray(e.rotation)),(new M).fromArray(e.scale))}(e,new r.Matrix4));return Promise.all((e.children??[]).map(a=>Qe(a,t,e,i)))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?Se.Number:t instanceof E||"function"==typeof e.prototype.isFloat?Se.FloatNode:t instanceof A||e===A||e.isTexture?Se.Texture:t instanceof Y||e===N?Se.Sampler2DNode:t instanceof Boolean||e===Boolean?Se.Boolean:t instanceof D?Se.BooleanNode:t instanceof n||e==n?Se.Color:t instanceof k||"function"==typeof e.prototype.isRgb?Se.RgbNode:t instanceof S||e==S?Se.Vector2:t instanceof z||"function"==typeof e.prototype.isVec2?Se.Vec2Node:t instanceof M||e==M?Se.Vector3:t instanceof _||"function"==typeof e.prototype.isVec3?Se.Vec3Node:t instanceof String||e===String?Se.String:t instanceof G||e==G||e.prototype instanceof G||e.prototype==G?Se.BaseActor:t instanceof o||e==o?Se.Euler:t instanceof y||e==y?Se.Object3D:t instanceof d||e==d?Se.Material:t instanceof AudioBuffer||e==AudioBuffer?Se.AudioBuffer:t instanceof R||e==R?Se.VisualEffect:t instanceof De||e==De?Se.Curve:t instanceof Ve||e==Ve?Se.ColorLayer:t instanceof Ne||e==Ne?Se.MaskLayer:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map(e=>[e.name,{type:e.options.array?Se.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}]))}export function prepareCustomParamsFromType(e,t,a=null){const s=ae(e);if(0===s.length)return{};let r;null!=a?q(a,()=>{r=a.get(e)}):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case S:return t instanceof S?t.toArray():void a();case M:return t instanceof M?t.toArray():void a();case j:return t instanceof j?t.toArray():void a();case n:return t instanceof n?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new n(t).getHexString():void a();case String:return t;case o:return t instanceof o?t.toArray():void a()}}function et(e,t){return function(e,t,a){const s=[],r=new Set;for(const i of[...e??[],...t??[]]){const e=a(i);r.has(e)||(r.add(e),s.push(i))}return s}((e??[]).filter(e=>tt(e.materialId)),(t??[]).filter(e=>tt(e.materialId)),e=>e.color+e.name)}function tt(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[Se.RgbNode,"#000000"],[Se.Color,"#000000"],[Se.Vector4,[0,0,0,0]],[Se.Vec4Node,[0,0,0,0]],[Se.Vector3,[0,0,0]],[Se.Vec3Node,[0,0,0]],[Se.Vector2,[0,0]],[Se.Vec2Node,[0,0]],[Se.Euler,[0,0,0,"XYZ"]],[Se.Array,[]],[Se.ColorLayer,Oe],[Se.MaskLayer,ke]]);export function applyMaterial(e,t,a,s){const i=[];return e.traverse(async e=>{if(e instanceof p||e.isMesh||e instanceof r.SkinnedMesh||e.isSkinnedMesh)for(const t of ie(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let r=0;r<e.material.length;r++){const i=e.material[r];if(null==i.color||!(i.color instanceof n))continue;const o="#"+i.color.getHexString(),l=i.name;if(o===t.color&&(i.name===t.name||null==t.name)||e.userData["originalColor_"+r]===t.color&&e.userData["originalMaterialName_"+r]===t.name){const i=await a(t.materialId),n=e.material[r];null!=i&&n.id!=i.id&&(e.material[r]=i,e.userData["originalColor_"+r]=e.userData["originalColor_"+r]??o,e.userData["originalMaterialName_"+r]=e.userData["originalMaterialName_"+r]??l,null!=s&&s.set(e.id+"#"+r,n))}}else if("color"in e.material){const r="#"+e.material.color.getHexString(),i=e.material.name;if(r===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await a(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??r,e.userData.originalMaterialName=e.userData.originalMaterialName??i,null!=s&&(s.has(e.id)||s.set(e.id,o)))}}}))}function at(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function st(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{ConvexPolyhedronCollisionShape as a}from"@hology/core";import{Subject as s}from"rxjs";import*as r from"three";import{BoxGeometry as i,Color as n,Euler as o,Fog as l,FogExp2 as c,Group as h,Material as d,Matrix4 as m,Mesh as p,MeshLambertMaterial as u,MeshPhongMaterial as f,MeshStandardMaterial as g,Object3D as y,PointLight as w,Quaternion as v,Scene as b,Texture as A,Vector2 as S,Vector3 as M,Vector4 as j}from"three";import x,{SpriteRenderer as P}from"@hology/nebula";import{bool as I,BooleanNode as D,float as C,FloatNode as E,NodeShaderMaterial as V,rgb as O,RgbNode as k,Texture2dLookupNode as N,textureSampler2d as F,vec2 as T,Vec2Node as z,vec3 as B,Vec3Node as _,vec4 as L}from"three-shader-graph";import{Service as W}from"typedi";import{VfxActor as $}from"../effects/vfx/vfx-actor.js";import{VisualEffect as R}from"../effects/vfx/vfx-param.js";import{BaseActor as G}from"../gameplay/actors/actor.js";import U from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as H,ThreeBlendingMode as J,withInjectionContext as q}from"../gameplay/index.js";import{RenderingView as X}from"../rendering.js";import{Sampler2DNode as Y}from"../shader-nodes/index.js";import{LambertShader as Z}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as K}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as Q}from"../shader/builtin/landscape-shader.js";import{StandardShader as ee}from"../shader/builtin/standard-shader.js";import{UnlitShader as te}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as ae}from"../shader/parameter.js";import{ArrayMap as se,groupBy as re}from"../utils/collections.js";import{iterateMaterials as ie}from"../utils/materials.js";import{filterChildrenShallow as ne,filterSceneShallow as oe,findFirstVisibleObject as le}from"../utils/three/traverse.js";import{AssetMeshInstance as ce,AssetResourceLoader as he}from"./asset-resource-loader.js";import{isCollisionMesh as de}from"./collision/collision-shape-import.js";import{BoxCollisionShape as me,PhysicalShapeMesh as pe}from"./collision/collision-shape.js";import{LandscapeManager as ue}from"./landscape/landscape-manager.js";import{initLandscape as fe}from"./landscape/landscape.js";import{SectionGrid as ge,smoothNormalsCrossMeshes as ye}from"./landscape/utils.js";import{createGrassFoliageMaterial as we}from"./materials/grass-foliage.js";import{createGrassMaterial as ve}from"./materials/grass.js";import{getMaterialAttribute as be}from"./materials/utils/material-painting.js";import{createWaterMaterial as Ae}from"./materials/water.js";import{SerializedParamType as Se}from"./model.js";import{ShapeLibrary as Me,ShapeLibraryKeys as je}from"./objects/shapes.js";import{ambientLightName as xe,createSky as Pe,defaultSkyMaterial as Ie}from"./sky.js";import{Curve2 as De}from"../utils/curve.js";import{DecalUnlitShader as Ce}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as Ee}from"../shader/builtin/decal-standard-shader.js";import{ColorLayer as Ve,defaultValueColorLayer as Oe,defaultValueMaskLayer as ke,MaskLayer as Ne}from"../shader/color-layer.js";import{LayeredShader as Fe}from"../shader/builtin/layered-shader";import{isColorLayerSerialized as Te}from"../shader/color-layer";import{FogVolume as ze}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as Be}from"../utils/three/unscaled-sprite.js";import{ToonShader as _e}from"../shader/builtin/toon-shader.js";const Le={},We=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),$e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPad"))&&!!navigator.userAgent.match(/AppleWebKit/)&&!navigator.userAgent.match(/CriOS/);export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,a){this.dataProvider=e,this.assetsService=t,this.assetManagerService=a}get(e,t){return new Re(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let Re=class{constructor(e,t,a,i,n,o,l,c){this.scene=e,this.dataProvider=t,this.assetsService=a,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new s,this.removed$=new s,this.error$=new s,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.prefabInstanceChain=[],this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,t.onCreate(e=>this.update(e)),t.onUpdate(e=>this.update(e)),t.onRemove(e=>this.remove(e)),this.createAssetSubscription=a.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=a.onUpdate.subscribe(async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse(e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)}):"mesh"==t.type?(this.findByAssetId(t.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src)}),this.landscapeManagers.forEach(e=>{const a=e.source?.grass?.layers?.some(e=>e.meshes.some(e=>e.assetId===t.id));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new M,!0)})):"prefab"===t.type?this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}):"vfx"===t.type&&this.dataProvider.getObjects().forEach(e=>{Qe(e,(e,a)=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),this.materializeAndInitActor(e))})})})}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===Se.Material&&s.value===a.id){t=!0;break}if(s.type===Se.Array&&"element"in s&&s.element===Se.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1),n=i.userData;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,null!=s?at(e.material[s],i)||(e.material[s]=i):at(e.material,i)||(e.material=i,e===this.sky&&this.applySkySettings(e.material))}getTopLevelActors(){return Array.from(this.materializedActors.entries()).filter(([e,t])=>!e.includes("/")).map(([,e])=>e)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter(e=>"shape_mesh"===e.type||"asset_mesh"===e.type).filter(e=>null!=e.materialAssignments).flatMap(e=>e.materialAssignments).map(async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===Se.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}})),0!==e.length&&this.renderingView){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter(e=>null!=e.assetId&&"asset_mesh"==e.type).filter(e=>e.assetId)));await Promise.all(e.map(e=>this.assetsService.getAsset(e.assetId).then(e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))),this.initTextures()}async init(){await this.preInit(),Ue.clear(),He.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit()}initActorsPostInit(e=this.getTopLevelActors(),t){const a=e.map(async e=>{const a=e.object.userData.src??e.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s=await this.assetsService.getAsset(a.assetId),r={...s?.actor?.params??{},...a.actor?.params??{}},i=null!=t?new Map(Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(t.sceneObjectChain.join("/"))&&e.split("/").length-1===t.sceneObjectChain.length).map(([e,t])=>[e.split("/").pop(),t])):this.materializedActors;for(const t of a.actor.innerParams??[])await this.applyActorComponentParams(e,t.path.slice(),t.params,i);const n=await prepareClassParameters(r,e.constructor,this.assetsService,this.assetManagerService,i,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,n);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(a)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a,s){const r=t.length,i=t.shift();if(0==r){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,s,this.renderingView,this.shaders,this.actorProvider);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[i]&&await this.applyActorComponentParams(e[i],t,a,s)}canObjectBeInstanced(e){return e.physics?.type!==H.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){if(!this._canBeInstancedCache.has(e.assetId)){const t=await this.createFromAsset(e);if(null==t)return!1;const a=[];t.traverse(e=>{!de(e)&&e.isMesh&&a.push(e)});const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof p&&null!=a[0].geometry.morphAttributes&&Object.keys(a[0].geometry.morphAttributes).length>0,i=!0;this._canBeInstancedCache.set(e.assetId,s&&i&&!r)}return this._canBeInstancedCache.get(e.assetId)}async preInit(){this.renderingView?.onLoop(()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)}),this.assetsService.getAssets().then(e=>{for(const t of e)this.assets.set(t.id,t)})}shouldBeMaterialized(e){if(null!=this.detailTier&&"asset_mesh"===e.type&&null!=e.assetId){const t=this.assets.get(e.assetId);if(null!=t){const e=t.mesh?.detailTier;if(null!=e)return e<=this.detailTier}}return!0}async initWithInstancing(){await this.preInit(),await this.prefetchAssets(),Ue.clear(),He.clear();const e=[],t=new se,s=new se;for(const a of this.dataProvider.getObjects())await Qe(a,async(a,r,i)=>{if(!this.shouldBeMaterialized(a))return;const o="asset_mesh"==a.type&&this.canObjectBeInstanced(a)&&await this.canAssetBeInstanced(a),l="shape_mesh"===a.type&&"landscape"!==a.shape&&a.physics?.type!==H.dynamic;if(o||l){if(r&&r.children?.length>0){const e=r.children.findIndex(e=>e.id===a.id);e>=0&&r.children.splice(e,1)}if(l){let e=a.shape+JSON.stringify(a.shapeParams??{})+a.castShadow+a.receiveShadow;const t=a.materialAssignments?.at(0)?.materialId,r=null!=t?this.assets.get(t):null;let o=null;if(null!=r&&"shader"!==r.material.type){if(e+=r.material.type+r.material.shader,null!=r.material.shaderParams){if(e+=Object.entries(r.material.shaderParams).filter(([e,t])=>"color"!=e).map(e=>JSON.stringify(e)).join(),null!=r.material.shaderParams.color){const e=r.material.shaderParams.color;e.type===Se.Color&&null!=e.value&&(o=new n(e.value))}}}else e+=t;s.push(e,{object:{...a,parentTransform:i},color:o})}else{const e=a.assetId+JSON.stringify(a.materialAssignments??[]);t.push(e,{...a,parentTransform:i})}}else null==r&&e.push({...a,parentTransform:i})});for(const e of t.values()){if(0==e.length)continue;const t=await this.createFromAsset(e[0]);if(null==t)continue;const s=await this.createInstancedMesh(e,t),r=new ce;r.add(s),r.userData.src=e[0],t instanceof ce&&(r.collisionShapes=t.collisionShapes),r.collisionShapes.forEach(e=>{e instanceof a&&e.mesh instanceof p&&(e.mesh=e.mesh.geometry)}),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of s.values()){if(0==e.length)continue;const t=e[0].object,a=await this.createFromShape(t),s=le(a,e=>!de(e)&&null!=e.geometry),i=s.material.clone();null!=e[0].color&&null!=i.color&&(i.color=new n(16777215));const l=s.geometry;let c,h;!($e||i instanceof V||null==l.index)?(c=new r.BatchedMesh(e.length,l.getAttribute("position").count,l.index.count,i),c.perObjectFrustumCulled=!0,h=c.addGeometry(l)):c=new r.InstancedMesh(l,i,e.length),c.castShadow=a.castShadow??!0,c.receiveShadow=s.receiveShadow??!0;for(let t=0;t<e.length;t++){const a=e[t],s=(new r.Matrix4).compose((new M).fromArray(a.object.position),(new v).setFromEuler((new o).fromArray(a.object.rotation)),(new M).fromArray(a.object.scale)),i=(new m).copy(a.object.parentTransform).multiply(s);let n;n=c instanceof r.BatchedMesh?c.addInstance(h):t,c.setMatrixAt(n,i),null!=a.color&&c.setColorAt(n,a.color)}for(let t=0;t<e.length;t++){const s=e[t],r=new ce;r.userData.src=e[0],a instanceof pe&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r),r.add(c),null==c.userData.hasCollision&&(c.userData.hasCollision=[]),c.userData.hasCollision[t]=!!s.object.collisionDetection}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const a=le(t,e=>!de(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,et(e[0].materialAssignments,s.materialAssignments)),a.updateMatrix();const i=a.geometry.clone(),n=a.material;let l,c;if(!($e||n instanceof V||!(i.groups.length<2)||Array.isArray(n)&&1!=n.length)){const t=Array.isArray(n)?n[0]:n,a=i.getAttribute("position").count;l=new r.BatchedMesh(e.length,a,null!=i.index?i.index.count:a,t),l.perObjectFrustumCulled=!0,c=l.addGeometry(i)}else l=new r.InstancedMesh(i,n,e.length);for(let t=0;t<e.length;t++){let s=t;l instanceof r.BatchedMesh&&(s=l.addInstance(c));const i=(new r.Matrix4).compose((new M).fromArray(e[t].position),(new v).setFromEuler((new o).fromArray(e[t].rotation)),(new M).fromArray(e[t].scale)),n=(new m).copy(e[t].parentTransform).multiply(i).multiply(a.matrixWorld);l.setMatrixAt(s,n),null==l.userData.hasCollision&&(l.userData.hasCollision=[]),l.userData.hasCollision[t]=!!e[t].collisionDetection}if(l.castShadow=e[0].castShadow??s.castShadow??!0,l.receiveShadow=e[0].receiveShadow??s.receiveShadow??!0,a.material instanceof d&&l.castShadow&&l.receiveShadow)if(Array.isArray(n))for(const e of n)e.side=r.FrontSide;else n.side=r.FrontSide;return l}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else"prefab"===e.type&&this.materializedActors.forEach((t,a)=>{a.startsWith(e.id)&&(t.disposed.next(!0),t.onEndPlay()),this.materializedActors.delete(a)});const t=this.sceneObjectMap.get(e.id);t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter(t=>t.object.userData.src?.id===e.id).forEach(e=>this.components.splice(this.components.indexOf(e,1))),this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))}),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex(t=>t.source.id===e.id);if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return oe(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t)))}async applyMaterial(e,t){await applyMaterial(e,t,e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}},this._originalMaterials)}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof p)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material})}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(U));oe(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of Ue.entries())t.userData.customShaderName&&Ue.delete(e);this.landscapeManagers.forEach(t=>t.updateShaders(e)),oe(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof p)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}})})}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(s=!0)}),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof p&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof p&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);et(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)),this.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new n(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0),a.userData.volumetricIntensity=e.light.point.volumetricIntensity}else if("spot"==e.light.type){const a=t;a.color=new n(e.light.spot.color),a.intensity=e.light.spot.intensity,a.decay=e.light.spot.decay,a.angle=e.light.spot.angle,a.penumbra=e.light.spot.penumbra,a.castShadow=e.light.spot.castShadow,a.distance=Math.max(e.light.spot.distance,0),a.userData.volumetricIntensity=e.light.spot.volumetricIntensity}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional,e):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,e=>!0)})}else if("global_fog"===e.type){const t=(this.scene.fog instanceof c?"density":"linear")!==e.fog.type;this.scene.fog=Ze(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof p){const t=e.material;t instanceof V&&(a.fog instanceof l?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof c&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.materializedActors.get(e.id);if(t instanceof ze){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);null!=a&&a===JSON.stringify(e.actor)||s||(this.remove(e),await this.materializeAndInitActor(e))}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof pe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&Ge(t,e.castShadow,e.receiveShadow),e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t);return Qe(e,async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}}),a}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:ne(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?oe(this.scene,e=>e.userData?.src?.id===t.id,e=>null!=e.userData?.src)[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new n(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof p&&e.geometry&&(t=e)}),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=re(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof p){if(null==e.geometry)return;if(st(be(e,0,!1)),a>0){st(be(e,0,!1))}}});const r=new Set;for(const[e,i]of s.entries()){const s=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==s||null==s.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=be(s,0,!0);st(o);for(const e of i)o.setX(e.i,e.w[0]??0),o.setY(e.i,e.w[1]??0),o.setZ(e.i,e.w[2]??0),o.setW(e.i,e.w[3]??0),n=!0;if(a>0){const e=be(s,4,!0);st(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&r.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>r.has(e.name)))}async materialize(e,t,a=!1,s){if(!this.shouldBeMaterialized(e))return;let r,n;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Ze(e.fog),this.fixFogColor(),r=new h;break;case"sky":this.sky=Pe(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new h,this.worldEnvObj=r;break;case"actor":({object:r,actor:n}=await this.createFromActor(e,s));break;case"group":r=new h;break;case"prefab":r=await this.createFromPrefab(e,s);break;case"vfx":r=await this.createFromVfx(e,s);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,null!=n&&(r.userData.actor=n),this.inEditor,this.inEditor){let e=null;r instanceof pe&&(e=function(e){if(e instanceof me)return new p(new i(...e.offset.toArray()),Ke);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}if(this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==H.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,r,a))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==H.dynamic||Ye(r),null!=this.renderingView)return this.renderingView.renderer.shadowMap.needsUpdate=!0,r;console.warn("RenderingView not found in materializer. No idea what called this")}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao),this.renderingView.aoPass.output=!0===e.worldEnv.ao.onlyAO?5:0;const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const a=e.worldEnv.environment;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{null==this.pmremGenerator&&(this.pmremGenerator=new r.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=a.intensity??1}):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=Ie);const t=await this.assetsService.getAsset(e.sky.materialId),a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);this.applySkySettings(a),null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}applySkySettings(e){e.side=r.BackSide,(e instanceof g||e instanceof r.MeshBasicMaterial||e instanceof r.ShaderMaterial)&&(e.fog=!1)}async createComponent(e,t,a,s){const r=new Le[a.path+"/"+a.className],i=t.id+s;r.id=i,r.object=e;for(const e of a.params)null!=e.value&&(r[e.name]=e.value);return this.components.push(r),i}async createFromActor(e,t){const a=this.actorTypes.find(t=>t.name===e.actor?.type)?.type??U[e.actor?.type];if(null==a)return{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new M).fromArray(e.position),(new o).fromArray(e.rotation),!0);return this.materializedActors.set(this.getNestedActorId(e.id,t),s),{object:s?.object,actor:s}}getNestedActorId(e,t){return null!=t?t.sceneObjectChain.join("/")+"/"+e:e}async createFromVfx(e,t){const a=await this.assetsService.getAsset(e.assetId);null==a&&console.error("Could not find asset",e);const s=await this.actorProvider.create($,(new M).fromArray(e.position),(new o).fromArray(e.rotation),!1);try{await s.fromAsset(a)}catch(e){return console.error("Failed to create VFX asset",e),null}return s.play(),this.materializedActors.set(this.getNestedActorId(e.id,t),s),null!=s&&(s.object.userData.actor=s),s?.object}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse(e=>{e instanceof p&&this._originalMaterials.set(e.id,e.material)});else{let s=new g({name:"Default",color:new n("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.castShadow??!1,e.collisionDetection||(r.collisionShape=null),r.physics=e.physics,a=r,this._originalMaterials.set(a.id,r.material),a.traverse(e=>{})}return t||(await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(a,e))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new h;const a=fe(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new ue(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,t=>{(e.materialAssignments??[]).filter(e=>null!=e.materialId).forEach(e=>this.applyMaterial(t,e))});return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new ge(e.sections);for(const e of t??[]){const t=s.find(e.x,e.y);if(!t)return;const a=t.geometry.getAttribute("position");for(const t of e.points)a.setY(t.i,t.y);a.needsUpdate=!0}const r=e.sections;r.forEach(e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()}),this.inEditor&&!a||setTimeout(()=>ye(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&je.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Me[e].geometry(s);t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Me[e].collision(s));return new pe(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async createFromAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:a}=await this.assetManagerService.getMesh(t,{mergeGeomtries:!0});et(e.materialAssignments,t.materialAssignments).forEach(e=>this.applyMaterial(a,e));const s=e.receiveShadow??!!t.receiveShadow??!0,r=e.castShadow??!!t.castShadow??!1;return a.receiveShadow=s,Ge(a,r,s),e.collisionDetection||(a.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(a.physics=e.physics),this.applyVertexMaterials(e,a),a.traverse(e=>{e instanceof p&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),a}async createFromPrefab(e,t){const a=await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);null==t&&(t={sceneObjectChain:[]}),t.sceneObjectChain.push(e.id);const{object:s}=await this.createFromPrefabAsset(a,t);return t.sceneObjectChain.pop(),s}async createFromPrefabAsset(e,t){const a=new h;await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,a,!0,structuredClone(t))));const s=t.sceneObjectChain.join("/"),r=Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(s)&&e.split("/").length-1===t.sceneObjectChain.length).map(([,e])=>e);r.forEach(e=>{a.add(e.object)}),this.initActorsPostInit(r,structuredClone(t));const i=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(s)).map(([,e])=>e);return{object:a,actors:i}}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),a=new y;return await x.fromJSONAsync(t.particleSystem,r).then(e=>{const t=new P(a,r);e.addRenderer(t),this.renderingView.onLoop(t=>e.update())}),a}async createLight(e){if("point"===e.light.type){const t=new w(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new Be(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new r.SpotLight(e.light.spot.color,e.light.spot.intensity,e.light.spot.distance,e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.target=new y,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new Be(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new r.SpotLightHelper(t))}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new h):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new h):void 0}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===xe);null!=s?(s.intensity=t.intensity,s.color.set(t.color),s.groundColor.set(t.color),s.userData.src=a,s.userData.volumetricIntensity=t.volumetricIntensity):console.warn("Couldn't find ambient light")}applyDirectionalLight(e,t){for(const a of this.renderingView.csm.lights)a.intensity=e.intensity,a.color.set(e.color),a.castShadow=e.castShadow,a.userData.src=t,a.userData.volumetricIntensity=e.volumetricIntensity;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach(e=>e.disposed.next(!0)),this.materializedActors.clear()}};Re=e([W(),t("design:paramtypes",[b,Object,Object,he,X,Array,Array,Object])],Re);export{Re as SceneMaterializer};function Ge(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const Ue=new Map,He=new Map,Je=new u({color:16711935}),qe=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&Ue.has(n)?Ue.get(n):i&&He.has(n)?await He.get(n):He.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,a,s,i,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new n(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(c.map=await i.getTexture(a))}let d;switch(t.material.type){case"phong":d=new f({...c,...h});break;case"water":d=Ae(c,a);break;case"grassFoliage":d=we({color:c.color,map:c.map},a);break;case"grass":d=ve({...c,colorTwo:new n(t.material.params.colorTwo),colorThree:new n(t.material.params.colorThree)},a);break;case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:We?Z:ee,lambert:Z,unlit:te,toon:_e,layered:Fe,landscape:Q,"landscape-composite":K,"decal-unlit":Ce,"decal-standard":Ee}[t.material.type]??o.find(e=>e.name==t.material.shader)?.type;if(e){try{let r=new e;const n=await prepareClassParameters(t.material?.shaderParams??{},e,s,i,null,a,o);Object.assign(r,n),d=r.build()}catch(e){console.log("Shader runtime error: "+e),qe.has(t.material.shader)||qe.set(t.material.shader,Je.clone()),d=qe.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=Je;break;default:throw new Error("Unsupported material type"+t.material.type)}return a?.csm.setupMaterial(d),null!=a&&Ue.set(e,d),d.side=t.material.side??d.side??r.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,null!=t.material.blending&&(d.blending=J[t.material.blending]??r.NormalBlending),t.material.bloom&&(d.userData.hasBloom=!0),t.material.reflective&&(d.userData.reflective=!0),!0===t.material.outlines&&(d.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(d.userData.outlineParameters.color=new n(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(d.userData.outlineParameters.thickness=t.material.outlineParams.thickness))),d.userData.assetId=t.id,He.delete(e),d}export async function prepareClassParameters(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await Xe(t,c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await Xe(a,s,null,null,null);null!=e&&(t[a]=e)}return t}async function Xe(e,t,a,s,r,i,l,c,h=t.value,d=t.type){if(null==t||null==h||""===h)return null;switch(d){case Se.Array:if(Array.isArray(h)&&"element"in t)return await Promise.all(h.map(n=>Xe(e,t,a,s,r,i,l,c,n,t.element)));break;case Se.Number:case Se.FloatNode:let d="string"==typeof h?parseFloat(h):h;return t.type===Se.FloatNode?C(d):d;case Se.Texture:let m=await s.getTexture(await a.getAsset(h));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case Se.Sampler2DNode:return F(await s.getTexture(await a.getAsset(h)));case Se.Boolean:return h;case Se.BooleanNode:return I(h);case Se.Vector2:case Se.Vec2Node:if("object"==typeof h){const e=h instanceof Array?(new S).fromArray(h):new S(h.x,h.y);return t.type===Se.Vec2Node?T(e):e}return null;case Se.Vector3:case Se.Vec3Node:if("object"==typeof h){const e=h instanceof Array?(new M).fromArray(h):new M(h.x,h.y,h.z);return t.type===Se.Vec3Node?B(e):e}return null;case Se.Color:case Se.RgbNode:const p=new n(h);return t.type===Se.RgbNode?O(p):p;case Se.String:return h;case Se.BaseActor:const u=h;return null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),r?.get(u);case Se.Euler:const f=h;return(new o).fromArray(f);case Se.Object3D:return(await s.getMesh(await a.getAsset(h))).scene;case Se.Material:return await materialFromAsset(await a.getAsset(h),i,a,s,l);case Se.AudioBuffer:return await s.getAudio(await a.getAsset(h));case Se.VisualEffect:const g=await a.getAsset(h);if(null==c){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in g)return new R(c,g);console.error("Using a non-vfx asset for visual effect parameter");break;case Se.Curve:return De.decode(h);case Se.ColorLayer:case Se.MaskLayer:if(Te(h)){const e=await Ve.decode(h,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(h.params,null,a,s);return Object.assign(e,t),e}return console.warn("Expecting color layer but got",h),null}return null}function Ye(e){e.updateWorldMatrix(!0,!0),e.updateMatrix(),e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1});const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}function Ze(e){return"linear"===e.type?new l(new n(e.color),e.near??100,e.far??1e3):"density"===e.type?new c(e.color,e.density):void console.warn("Invalid fog type",e)}const Ke=new g({color:4229780});async function Qe(e,t,a,s){null==s&&(s=(new m).identity()),await t(e,a,s);const i=s.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new M).fromArray(e.position),(new v).setFromEuler((new o).fromArray(e.rotation)),(new M).fromArray(e.scale))}(e,new r.Matrix4));return Promise.all((e.children??[]).map(a=>Qe(a,t,e,i)))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?Se.Number:t instanceof E||"function"==typeof e.prototype.isFloat?Se.FloatNode:t instanceof A||e===A||e.isTexture?Se.Texture:t instanceof Y||e===N?Se.Sampler2DNode:t instanceof Boolean||e===Boolean?Se.Boolean:t instanceof D?Se.BooleanNode:t instanceof n||e==n?Se.Color:t instanceof k||"function"==typeof e.prototype.isRgb?Se.RgbNode:t instanceof S||e==S?Se.Vector2:t instanceof z||"function"==typeof e.prototype.isVec2?Se.Vec2Node:t instanceof M||e==M?Se.Vector3:t instanceof _||"function"==typeof e.prototype.isVec3?Se.Vec3Node:t instanceof String||e===String?Se.String:t instanceof G||e==G||e.prototype instanceof G||e.prototype==G?Se.BaseActor:t instanceof o||e==o?Se.Euler:t instanceof y||e==y?Se.Object3D:t instanceof d||e==d?Se.Material:t instanceof AudioBuffer||e==AudioBuffer?Se.AudioBuffer:t instanceof R||e==R?Se.VisualEffect:t instanceof De||e==De?Se.Curve:t instanceof Ve||e==Ve?Se.ColorLayer:t instanceof Ne||e==Ne?Se.MaskLayer:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map(e=>[e.name,{type:e.options.array?Se.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}]))}export function prepareCustomParamsFromType(e,t,a=null){const s=ae(e);if(0===s.length)return{};let r;null!=a?q(a,()=>{r=a.get(e)}):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case S:return t instanceof S?t.toArray():void a();case M:return t instanceof M?t.toArray():void a();case j:return t instanceof j?t.toArray():void a();case n:return t instanceof n?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new n(t).getHexString():void a();case String:return t;case o:return t instanceof o?t.toArray():void a()}}function et(e,t){return function(e,t,a){const s=[],r=new Set;for(const i of[...e??[],...t??[]]){const e=a(i);r.has(e)||(r.add(e),s.push(i))}return s}((e??[]).filter(e=>tt(e.materialId)),(t??[]).filter(e=>tt(e.materialId)),e=>e.color+e.name)}function tt(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[Se.RgbNode,"#000000"],[Se.Color,"#000000"],[Se.Vector4,[0,0,0,0]],[Se.Vec4Node,[0,0,0,0]],[Se.Vector3,[0,0,0]],[Se.Vec3Node,[0,0,0]],[Se.Vector2,[0,0]],[Se.Vec2Node,[0,0]],[Se.Euler,[0,0,0,"XYZ"]],[Se.Array,[]],[Se.ColorLayer,Oe],[Se.MaskLayer,ke]]);export function applyMaterial(e,t,a,s){const i=[];return e.traverse(async e=>{if(e instanceof p||e.isMesh||e instanceof r.SkinnedMesh||e.isSkinnedMesh)for(const t of ie(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let r=0;r<e.material.length;r++){const i=e.material[r];if(null==i.color||!(i.color instanceof n))continue;const o="#"+i.color.getHexString(),l=i.name;if(o===t.color&&(i.name===t.name||null==t.name)||e.userData["originalColor_"+r]===t.color&&e.userData["originalMaterialName_"+r]===t.name){const i=await a(t.materialId),n=e.material[r];null!=i&&n.id!=i.id&&(e.material[r]=i,e.userData["originalColor_"+r]=e.userData["originalColor_"+r]??o,e.userData["originalMaterialName_"+r]=e.userData["originalMaterialName_"+r]??l,null!=s&&s.set(e.id+"#"+r,n))}}else if("color"in e.material){const r="#"+e.material.color.getHexString(),i=e.material.name;if(r===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await a(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??r,e.userData.originalMaterialName=e.userData.originalMaterialName??i,null!=s&&(s.has(e.id)||s.set(e.id,o)))}}}))}function at(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function st(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decal-standard-shader.d.ts","sourceRoot":"","sources":["../../../src/shader/builtin/decal-standard-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAIhD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAGrD,qBAAa,mBAAoB,SAAQ,eAAe;IACzC,KAAK,EAAE,KAAK,CAAwB;IACtB,OAAO,EAAE,MAAM,CAAI;IACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEL,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IAET,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB,QAAQ,CAAC,EAAE,KAAK,CAAC;IACF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC1C,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,WAAW,CAAC,EAAE,OAAO,
|
|
1
|
+
{"version":3,"file":"decal-standard-shader.d.ts","sourceRoot":"","sources":["../../../src/shader/builtin/decal-standard-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAIhD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAGrD,qBAAa,mBAAoB,SAAQ,eAAe;IACzC,KAAK,EAAE,KAAK,CAAwB;IACtB,OAAO,EAAE,MAAM,CAAI;IACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEL,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IAET,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB,QAAQ,CAAC,EAAE,KAAK,CAAC;IACF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC1C,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,WAAW,CAAC,EAAE,OAAO,CAAmB;IAIrD,MAAM;;;IA+DN,KAAK;CASN"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{Color as a,Texture as s,Vector2 as r}from"three";import{colorToNormal as o,float as i,rgba as p,standardMaterial as l,textureSampler2d as n,uniforms as d,normalize as h,varying as m,rgb as c,AttributeVec3Node as y,ifDefApply as u,Vec3ExpressionNode as S}from"three-shader-graph";import{decalAlpha as g,decalNormal as v,decalUV as M}from"../../shader-nodes/decal.js";import{depthWorldPosition as D}from"../../shader-nodes/depth.js";import{DecalNodeShader as b}from"../decal-shader.js";import{Parameter as I}from"../parameter.js";export class DecalStandardShader extends b{constructor(){super(...arguments),this.color=new a("#FFFFFF"),this.opacity=1,this.roughness=1,this.metalness=0}output(){const e=M,t=m(new y("particleData"));let a=u("IS_PARTICLE",i(this.opacity),()=>t.x);null!=this.alphaMap&&(a=a.multiply(n(this.alphaMap).sample(e).r)),a=a.multiply(g);const s=m(u("IS_PARTICLE",c(this.color),()=>new S("instanceColor")));let r=u("IS_PARTICLE",c(this.color),()=>s.rgb),b=p(r,a);null!=this.colorMap&&(b=b.multiply(n(this.colorMap).sample(e)));let I=p(this.emissive,a);null!=this.emissiveMap&&(I=I.multiply(n(this.emissiveMap).sample(e)));let f=i(this.roughness);null!=this.roughnessMap&&(f=f.multiply(n(this.roughnessMap).sample(e).g));let F=i(this.metalness);null!=this.metalnessMap&&(F=F.multiply(n(this.metalnessMap).sample(e).b));let
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{Color as a,Texture as s,Vector2 as r}from"three";import{colorToNormal as o,float as i,rgba as p,standardMaterial as l,textureSampler2d as n,uniforms as d,normalize as h,varying as m,rgb as c,AttributeVec3Node as y,ifDefApply as u,Vec3ExpressionNode as S}from"three-shader-graph";import{decalAlpha as g,decalNormal as v,decalUV as M}from"../../shader-nodes/decal.js";import{depthWorldPosition as D}from"../../shader-nodes/depth.js";import{DecalNodeShader as b}from"../decal-shader.js";import{Parameter as I}from"../parameter.js";export class DecalStandardShader extends b{constructor(){super(...arguments),this.color=new a("#FFFFFF"),this.opacity=1,this.roughness=1,this.metalness=0,this.normalScale=new r(1,1)}output(){const e=M,t=m(new y("particleData"));let a=u("IS_PARTICLE",i(this.opacity),()=>t.x);null!=this.alphaMap&&(a=a.multiply(n(this.alphaMap).sample(e).r)),a=a.multiply(g);const s=m(u("IS_PARTICLE",c(this.color),()=>new S("instanceColor")));let r=u("IS_PARTICLE",c(this.color),()=>s.rgb),b=p(r,a);null!=this.colorMap&&(b=b.multiply(n(this.colorMap).sample(e)));let I=p(this.emissive,a);null!=this.emissiveMap&&(I=I.multiply(n(this.emissiveMap).sample(e)));let f=i(this.roughness);null!=this.roughnessMap&&(f=f.multiply(n(this.roughnessMap).sample(e).g));let F=i(this.metalness);null!=this.metalnessMap&&(F=F.multiply(n(this.metalnessMap).sample(e).b));let w=h(m(d.normalMatrix).multiplyVec(v));null!=this.normalMap&&(w=o(n(this.normalMap).sample(e),this.normalScale?.x??1,w,D,e));let x=null;return null!=this.aoMap&&(x=n(this.aoMap).sample(e).r),{color:l({color:b,emissive:I,emissiveIntensity:i(this.emissiveIntensity??1),roughness:f,metalness:F,normal:w,ambientOcclusion:x,ambientOcclusionIntensity:i(this.aoMapIntensity??1),worldPosition:D})}}build(){const e=super.build();return e.depthTest=!0,e.depthWrite=!1,e.userData.isDecal=!0,e}}e([I(),t("design:type",a)],DecalStandardShader.prototype,"color",void 0),e([I({range:[0,1]}),t("design:type",Number)],DecalStandardShader.prototype,"opacity",void 0),e([I(),t("design:type",s)],DecalStandardShader.prototype,"colorMap",void 0),e([I(),t("design:type",s)],DecalStandardShader.prototype,"alphaMap",void 0),e([I({range:[0,1]}),t("design:type",Number)],DecalStandardShader.prototype,"roughness",void 0),e([I(),t("design:type",s)],DecalStandardShader.prototype,"roughnessMap",void 0),e([I({range:[0,1]}),t("design:type",Number)],DecalStandardShader.prototype,"metalness",void 0),e([I(),t("design:type",s)],DecalStandardShader.prototype,"metalnessMap",void 0),e([I(),t("design:type",s)],DecalStandardShader.prototype,"aoMap",void 0),e([I(),t("design:type",Number)],DecalStandardShader.prototype,"aoMapIntensity",void 0),e([I(),t("design:type",a)],DecalStandardShader.prototype,"emissive",void 0),e([I({range:[0,10]}),t("design:type",Number)],DecalStandardShader.prototype,"emissiveIntensity",void 0),e([I(),t("design:type",s)],DecalStandardShader.prototype,"emissiveMap",void 0),e([I(),t("design:type",s)],DecalStandardShader.prototype,"normalMap",void 0),e([I(),t("design:type",r)],DecalStandardShader.prototype,"normalScale",void 0);/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standard-shader.d.ts","sourceRoot":"","sources":["../../../src/shader/builtin/standard-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,oBAAoB,EAAE,8BAA8B,EAAkB,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAChI,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAOtC,qBAAa,cAAe,SAAQ,MAAM;IAE3B,KAAK,EAAE,KAAK,CAAwB;IAChB,GAAG,CAAC,EAAE,OAAO,CAAC;IACpB,OAAO,EAAE,MAAM,CAAI;IACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACL,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IACT,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,KAAK,CAAC;IACF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC1C,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,OA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AAM,CAAC,EAAE,OAAO,CAAC;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IAGvC,SAAS,CAAC,EAAE,OAAO,CAAiB;IACpC,WAAW,CAAC,EAAE,MAAM,CAAA;IAGjC,KAAK,IAAI,QAAQ;CAgDlB;AAGD,oBAAY,YAAY;IACtB,IAAI,IAAA;IACJ,MAAM,IAAA;IACN,GAAG,IAAA;CACJ;AAED,qBAAa,wBAAyB,SAAQ,oBAAoB;IACzD,SAAS,EAAE,OAAO,CAAA;IAClB,WAAW,EAAE,MAAM,CAAA;IACnB,YAAY,EAAE,YAAY,CAAA;IAC1B,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;gBAEZ,MAAM,GAAE,OAAO,CAAC;QAC1B,SAAS,EAAE,OAAO,CAAC;QACnB,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,YAAY,CAAC;QAC3B,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAA;KAClB,GAAG,8BAA8B,CAAM;IAYxC,eAAe,CAAC,MAAM,KAAA;IAqLtB,KAAK,IAAI,IAAI;CAUd"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as a}from"tslib";import{Color as t,MeshStandardMaterial as n,Texture as r,Vector2 as i}from"three";import{Shader as s}from"../shader.js";import{Parameter as o}from"../parameter.js";import{removeObjectUndefined as p}from"../../utils/collections.js";const l=new r;export class StandardShader extends s{constructor(){super(...arguments),this.color=new t("#FFFFFF"),this.opacity=1,this.roughness=1,this.metalness=0,this.heightMap=l}build(){const e=null!=this.normalMap&&null!=this.map&&null!=this.heightMap&&this.heightMap!=l&&0!==this.heightScale;return new(e?ParallaxStandardMaterial:n)(p({color:this.color,opacity:this.opacity,roughness:this.roughness,metalness:this.metalness,map:this.map,lightMap:this.lightMap,lightMapIntensity:this.lightMapIntensity,aoMap:this.aoMap,aoMapIntensity:this.aoMapIntensity,emissive:this.emissive,emissiveIntensity:this.emissiveIntensity,emissiveMap:this.emissiveMap,bumpMap:this.bumpMap,bumpScale:this.bumpScale,normalMap:this.normalMap,normalScale:this.normalScale,displacementMap:this.displacementMap,displacementScale:this.displacementScale,displacementBias:this.displacementBias,roughnessMap:this.roughnessMap,metalnessMap:this.metalnessMap,alphaMap:this.alphaMap,envMap:this.envMap,envMapIntensity:this.envMapIntensity,refractionRatio:this.refractionRatio,...e?{heightMap:this.heightMap,heightScale:this.heightScale}:{}}))}}e([o(),a("design:type",t)],StandardShader.prototype,"color",void 0),e([o({label:"Color Map"}),a("design:type",r)],StandardShader.prototype,"map",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"opacity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"alphaMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"roughness",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"roughnessMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"metalness",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"metalnessMap",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"lightMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"lightMapIntensity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"aoMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"aoMapIntensity",void 0),e([o(),a("design:type",t)],StandardShader.prototype,"emissive",void 0),e([o({range:[0,10]}),a("design:type",Number)],StandardShader.prototype,"emissiveIntensity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"emissiveMap",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"bumpMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"bumpScale",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"normalMap",void 0),e([o(),a("design:type",i)],StandardShader.prototype,"normalScale",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"displacementMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"displacementScale",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"displacementBias",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"envMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"envMapIntensity",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"refractionRatio",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"heightMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"heightScale",void 0);export var ParallaxType;!function(e){e[e.none=0]="none",e[e.offset=1]="offset",e[e.pom=2]="pom"}(ParallaxType||(ParallaxType={}));export class ParallaxStandardMaterial extends n{constructor(e={}){super(e),e.heightMap&&(this.heightMap=e.heightMap),this.heightScale=e.heightScale??.05,this.parallaxType=e.parallaxType??ParallaxType.pom,this.minLayers=e.minLayers??10,this.maxLayers=e.maxLayers??32}onBeforeCompile(e){e.uniforms.heightMap={value:this.heightMap},e.uniforms.heightScale={value:this.heightScale},e.uniforms.minLayers={value:this.minLayers},e.uniforms.maxLayers={value:this.maxLayers},e.uniforms.parallaxType={value:this.parallaxType},e.vertexTangents=!0,e.vertexShader=e.vertexShader.replace("#include <uv_pars_vertex>","\n #include <uv_pars_vertex>\n varying vec3 vViewDirTS;\n varying mat3 vTBN;\n "),e.vertexShader=e.vertexShader.replace("#include <begin_vertex>","\n #include <begin_vertex>\n vec3 N = normalize(normalMatrix * normal);\n vec3 T = normalize(normalMatrix * tangent.xyz);\n vec3 B = cross(N, T) * tangent.w;\n vTBN = mat3(T, B, N);\n\n vec3 viewDir = cameraPosition - (modelMatrix * vec4(transformed, 1.0)).xyz;\n vViewDirTS = normalize(vTBN * viewDir);\n "),e.fragmentShader=e.fragmentShader.replace("#include <uv_pars_fragment>","\n #include <uv_pars_fragment>\n uniform sampler2D heightMap;\n uniform float heightScale;\n uniform int minLayers;\n uniform int maxLayers;\n uniform int parallaxType;\n\n varying vec3 vViewDirTS;\n varying mat3 vTBN;\n\n vec2 parallaxOffset(vec2 uv, vec3 viewDirTS) {\n float h = texture(heightMap, uv).r;\n return uv - (viewDirTS.xy / viewDirTS.z) * (h * heightScale);\n }\n\n vec2 parallaxOcclusion2(vec2 uv, vec3 viewDirTS) {\n vec3 viewDir = normalize(vViewPosition);\n vec3 vv = -viewDir * vTBN;\n float parallaxLimit = -length(vv.xy) / vv.z;\n parallaxLimit *= heightScale;\n\n vec2 vOffsetDir = normalize(vv.xy);\n vec2 vMaxOffset = vOffsetDir * parallaxLimit;\n\n // Probably should use actual normal but it might not matter\n vec3 nNormal = vec3(0.0, 0.0, 1.0);\n float nNumSamples = mix(float(maxLayers), float(minLayers), dot(viewDir, nNormal));\n float fStepSize = 1.0 / nNumSamples;\n\n float fCurrRayHeight = 1.0;\n vec2 vCurrOffset = vec2(0.0);\n vec2 vLastOffset = vec2(0.0);\n float fLastSampledHeight = 1.0;\n float fCurrSampledHeight = 1.0;\n\n for (int nCurrSample = 0; nCurrSample < 50; nCurrSample++) {\n if (float(nCurrSample) > nNumSamples) break;\n\n fCurrSampledHeight = texture2D(heightMap, uv + vCurrOffset).r;\n if (fCurrSampledHeight > fCurrRayHeight) {\n float delta1 = fCurrSampledHeight - fCurrRayHeight;\n float delta2 = (fCurrRayHeight + fStepSize) - fLastSampledHeight;\n float ratio = delta1 / (delta1 + delta2);\n vCurrOffset = ratio * vLastOffset + (1.0 - ratio) * vCurrOffset;\n break;\n } else {\n fCurrRayHeight -= fStepSize;\n vLastOffset = vCurrOffset;\n vCurrOffset += fStepSize * vMaxOffset;\n fLastSampledHeight = fCurrSampledHeight;\n }\n }\n\n return uv + vCurrOffset;\n }\n "),e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>","\n vec2 uvPOM = vMapUv ;\n if (parallaxType == 1) {\n uvPOM = parallaxOffset(vMapUv , vViewDirTS);\n } else if (parallaxType == 2) {\n uvPOM = parallaxOcclusion2(vMapUv , vViewDirTS);\n }\n\n\n vec4 texelColor = texture2D(map, uvPOM);\n //texelColor = mapTexelToLinear(texelColor);\n diffuseColor *= texelColor;\n "),e.fragmentShader=e.fragmentShader.replace("#include <normal_fragment_maps>","\n vec3 mapN = texture2D(normalMap, uvPOM).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n normal = normalize( tbn * mapN );\n "),e.fragmentShader=e.fragmentShader.replace("#include <roughnessmap_fragment>","\n float roughnessFactor = roughness;\n #ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, uvPOM );\n // reads channel G, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n roughnessFactor *= texelRoughness.g;\n #endif\n "),e.fragmentShader=e.fragmentShader.replace("#include <metalnesssmap_fragment>","\n float metalnessFactor = metalness;\n #ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, uvPOM );\n // reads channel B, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n metalnessFactor *= texelMetalness.b;\n #endif\n "),e.fragmentShader=e.fragmentShader.replace("#include <aomap_fragment>","\n #ifdef USE_AOMAP\n\n // reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n float ambientOcclusion = ( texture2D( aoMap, uvPOM ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n\n #if defined( USE_CLEARCOAT ) \n clearcoatSpecularIndirect *= ambientOcclusion;\n #endif\n\n #if defined( USE_SHEEN ) \n sheenSpecularIndirect *= ambientOcclusion;\n #endif\n\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n\n float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\n #endif\n\n #endif\n "),this.userData.shader=e}clone(){const e=super.clone();return e.heightMap=this.heightMap,e.heightScale=this.heightScale,e.parallaxType=this.parallaxType,e.minLayers=this.minLayers,e.maxLayers=this.maxLayers,e}}/*
|
|
1
|
+
import{__decorate as e,__metadata as a}from"tslib";import{Color as t,MeshStandardMaterial as n,Texture as r,Vector2 as i}from"three";import{Shader as s}from"../shader.js";import{Parameter as o}from"../parameter.js";import{removeObjectUndefined as p}from"../../utils/collections.js";const l=new r;export class StandardShader extends s{constructor(){super(...arguments),this.color=new t("#FFFFFF"),this.opacity=1,this.roughness=1,this.metalness=0,this.normalScale=new i(1,1),this.heightMap=l}build(){const e=null!=this.normalMap&&null!=this.map&&null!=this.heightMap&&this.heightMap!=l&&0!==this.heightScale;return new(e?ParallaxStandardMaterial:n)(p({color:this.color,opacity:this.opacity,roughness:this.roughness,metalness:this.metalness,map:this.map,lightMap:this.lightMap,lightMapIntensity:this.lightMapIntensity,aoMap:this.aoMap,aoMapIntensity:this.aoMapIntensity,emissive:this.emissive,emissiveIntensity:this.emissiveIntensity,emissiveMap:this.emissiveMap,bumpMap:this.bumpMap,bumpScale:this.bumpScale,normalMap:this.normalMap,normalScale:this.normalScale,displacementMap:this.displacementMap,displacementScale:this.displacementScale,displacementBias:this.displacementBias,roughnessMap:this.roughnessMap,metalnessMap:this.metalnessMap,alphaMap:this.alphaMap,envMap:this.envMap,envMapIntensity:this.envMapIntensity,refractionRatio:this.refractionRatio,...e?{heightMap:this.heightMap,heightScale:this.heightScale}:{}}))}}e([o(),a("design:type",t)],StandardShader.prototype,"color",void 0),e([o({label:"Color Map"}),a("design:type",r)],StandardShader.prototype,"map",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"opacity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"alphaMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"roughness",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"roughnessMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"metalness",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"metalnessMap",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"lightMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"lightMapIntensity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"aoMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"aoMapIntensity",void 0),e([o(),a("design:type",t)],StandardShader.prototype,"emissive",void 0),e([o({range:[0,10]}),a("design:type",Number)],StandardShader.prototype,"emissiveIntensity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"emissiveMap",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"bumpMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"bumpScale",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"normalMap",void 0),e([o(),a("design:type",i)],StandardShader.prototype,"normalScale",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"displacementMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"displacementScale",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"displacementBias",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"envMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"envMapIntensity",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"refractionRatio",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"heightMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"heightScale",void 0);export var ParallaxType;!function(e){e[e.none=0]="none",e[e.offset=1]="offset",e[e.pom=2]="pom"}(ParallaxType||(ParallaxType={}));export class ParallaxStandardMaterial extends n{constructor(e={}){super(e),e.heightMap&&(this.heightMap=e.heightMap),this.heightScale=e.heightScale??.05,this.parallaxType=e.parallaxType??ParallaxType.pom,this.minLayers=e.minLayers??10,this.maxLayers=e.maxLayers??32}onBeforeCompile(e){e.uniforms.heightMap={value:this.heightMap},e.uniforms.heightScale={value:this.heightScale},e.uniforms.minLayers={value:this.minLayers},e.uniforms.maxLayers={value:this.maxLayers},e.uniforms.parallaxType={value:this.parallaxType},e.vertexTangents=!0,e.vertexShader=e.vertexShader.replace("#include <uv_pars_vertex>","\n #include <uv_pars_vertex>\n varying vec3 vViewDirTS;\n varying mat3 vTBN;\n "),e.vertexShader=e.vertexShader.replace("#include <begin_vertex>","\n #include <begin_vertex>\n vec3 N = normalize(normalMatrix * normal);\n vec3 T = normalize(normalMatrix * tangent.xyz);\n vec3 B = cross(N, T) * tangent.w;\n vTBN = mat3(T, B, N);\n\n vec3 viewDir = cameraPosition - (modelMatrix * vec4(transformed, 1.0)).xyz;\n vViewDirTS = normalize(vTBN * viewDir);\n "),e.fragmentShader=e.fragmentShader.replace("#include <uv_pars_fragment>","\n #include <uv_pars_fragment>\n uniform sampler2D heightMap;\n uniform float heightScale;\n uniform int minLayers;\n uniform int maxLayers;\n uniform int parallaxType;\n\n varying vec3 vViewDirTS;\n varying mat3 vTBN;\n\n vec2 parallaxOffset(vec2 uv, vec3 viewDirTS) {\n float h = texture(heightMap, uv).r;\n return uv - (viewDirTS.xy / viewDirTS.z) * (h * heightScale);\n }\n\n vec2 parallaxOcclusion2(vec2 uv, vec3 viewDirTS) {\n vec3 viewDir = normalize(vViewPosition);\n vec3 vv = -viewDir * vTBN;\n float parallaxLimit = -length(vv.xy) / vv.z;\n parallaxLimit *= heightScale;\n\n vec2 vOffsetDir = normalize(vv.xy);\n vec2 vMaxOffset = vOffsetDir * parallaxLimit;\n\n // Probably should use actual normal but it might not matter\n vec3 nNormal = vec3(0.0, 0.0, 1.0);\n float nNumSamples = mix(float(maxLayers), float(minLayers), dot(viewDir, nNormal));\n float fStepSize = 1.0 / nNumSamples;\n\n float fCurrRayHeight = 1.0;\n vec2 vCurrOffset = vec2(0.0);\n vec2 vLastOffset = vec2(0.0);\n float fLastSampledHeight = 1.0;\n float fCurrSampledHeight = 1.0;\n\n for (int nCurrSample = 0; nCurrSample < 50; nCurrSample++) {\n if (float(nCurrSample) > nNumSamples) break;\n\n fCurrSampledHeight = texture2D(heightMap, uv + vCurrOffset).r;\n if (fCurrSampledHeight > fCurrRayHeight) {\n float delta1 = fCurrSampledHeight - fCurrRayHeight;\n float delta2 = (fCurrRayHeight + fStepSize) - fLastSampledHeight;\n float ratio = delta1 / (delta1 + delta2);\n vCurrOffset = ratio * vLastOffset + (1.0 - ratio) * vCurrOffset;\n break;\n } else {\n fCurrRayHeight -= fStepSize;\n vLastOffset = vCurrOffset;\n vCurrOffset += fStepSize * vMaxOffset;\n fLastSampledHeight = fCurrSampledHeight;\n }\n }\n\n return uv + vCurrOffset;\n }\n "),e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>","\n vec2 uvPOM = vMapUv ;\n if (parallaxType == 1) {\n uvPOM = parallaxOffset(vMapUv , vViewDirTS);\n } else if (parallaxType == 2) {\n uvPOM = parallaxOcclusion2(vMapUv , vViewDirTS);\n }\n\n\n vec4 texelColor = texture2D(map, uvPOM);\n //texelColor = mapTexelToLinear(texelColor);\n diffuseColor *= texelColor;\n "),e.fragmentShader=e.fragmentShader.replace("#include <normal_fragment_maps>","\n vec3 mapN = texture2D(normalMap, uvPOM).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n normal = normalize( tbn * mapN );\n "),e.fragmentShader=e.fragmentShader.replace("#include <roughnessmap_fragment>","\n float roughnessFactor = roughness;\n #ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, uvPOM );\n // reads channel G, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n roughnessFactor *= texelRoughness.g;\n #endif\n "),e.fragmentShader=e.fragmentShader.replace("#include <metalnesssmap_fragment>","\n float metalnessFactor = metalness;\n #ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, uvPOM );\n // reads channel B, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n metalnessFactor *= texelMetalness.b;\n #endif\n "),e.fragmentShader=e.fragmentShader.replace("#include <aomap_fragment>","\n #ifdef USE_AOMAP\n\n // reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n float ambientOcclusion = ( texture2D( aoMap, uvPOM ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n\n #if defined( USE_CLEARCOAT ) \n clearcoatSpecularIndirect *= ambientOcclusion;\n #endif\n\n #if defined( USE_SHEEN ) \n sheenSpecularIndirect *= ambientOcclusion;\n #endif\n\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n\n float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\n #endif\n\n #endif\n "),this.userData.shader=e}clone(){const e=super.clone();return e.heightMap=this.heightMap,e.heightScale=this.heightScale,e.parallaxType=this.parallaxType,e.minLayers=this.minLayers,e.maxLayers=this.maxLayers,e}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parameter.d.ts","sourceRoot":"","sources":["../../src/shader/parameter.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAA;AAEzB,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAA;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AACxD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAC7F,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAExH,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAEzD,MAAM,MAAM,aAAa,GAAG,IAAI,CAC9B,SAAS,GACT,MAAM,GAC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|
|
|
1
|
-
{"version":3,"file":"sprite-shader.d.ts","sourceRoot":"","sources":["../../src/shader/sprite-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAE7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,EAAC,QAAQ,EAAyD,SAAS,EAAO,MAAM,oBAAoB,CAAC;AACpH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,8BAAsB,gBAAgB;IACpC,KAAK,IAAI,QAAQ;IAwBjB,QAAQ,CAAC,MAAM,IAAI,gBAAgB;CACpC;AAGD,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,SAAS,
|
|
1
|
+
{"version":3,"file":"sprite-shader.d.ts","sourceRoot":"","sources":["../../src/shader/sprite-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAE7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,EAAC,QAAQ,EAAyD,SAAS,EAAO,MAAM,oBAAoB,CAAC;AACpH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,8BAAsB,gBAAgB;IACpC,KAAK,IAAI,QAAQ;IAwBjB,QAAQ,CAAC,MAAM,IAAI,gBAAgB;CACpC;AAGD,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,SAAS,YAgCpD;AAED,qBAAa,wBAAyB,SAAQ,kBAAkB;IAE9D,IAAI,KAAK,IAGQ,KAAK,CAAC,mBAAmB,CADzC;IACD,IAAI,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,mBAAmB,EAEzC;IACD,IAAI,QAAQ,IAGQ,MAAM,CADzB;IACD,IAAI,QAAQ,CAAC,KAAK,EAAE,MAAM,EAEzB;CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{NodeShaderMaterial as o}from"../shader-nodes/index.js";import{Vec4Node as
|
|
1
|
+
import{NodeShaderMaterial as o}from"../shader-nodes/index.js";import{Vec4Node as e,glslFunction as i,transformed as t,uniforms as r,UniformFloatNode as n}from"three-shader-graph";import*as a from"three";export class SpriteNodeShader{build(){const o=this.output(),e=getSpritePosition(new n("rotation",0));return new SpriteNodeShaderMaterial({color:o.color,discard:o.discard,transparent:o.transparent??!0,position:e,uniforms:{color:{value:new a.Color(0)}}})}}export function getSpritePosition(o){return i(e,{position:t.position,cameraPosition:r.cameraPosition,viewMatrix:r.viewMatrix,modelViewMatrix:r.modelViewMatrix,rotation:o},"\n // Scale from your model matrix\n vec2 scale;\n scale.x = length(vec3(modelMatrix[0].x, modelMatrix[0].y, modelMatrix[0].z));\n scale.y = length(vec3(modelMatrix[1].x, modelMatrix[1].y, modelMatrix[1].z));\n\n vec3 right, up;\n vec3 objectPos = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;\n\n #ifdef LOCK_Y_AXIS\n vec3 cameraPos = cameraPosition;\n vec3 lookDir = normalize(vec3(cameraPos.x - objectPos.x, 0.0, cameraPos.z - objectPos.z));\n right = normalize(vec3(lookDir.z, 0.0, -lookDir.x));\n up = vec3(0.0, 1.0, 0.0);\n #else\n right = vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);\n up = vec3(viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1]);\n #endif\n\n // then your shared code:\n vec2 center = vec2(0.5, 0.5);\n vec2 alignedPosition = (position.xy - (center - vec2(0.5))) * scale;\n\n vec2 rotatedPosition;\n rotatedPosition.x = cos(rotation) * alignedPosition.x - sin(rotation) * alignedPosition.y;\n rotatedPosition.y = sin(rotation) * alignedPosition.x + cos(rotation) * alignedPosition.y;\n\n vec3 billboardPos = objectPos + right * rotatedPosition.x + up * rotatedPosition.y;\n\n return projectionMatrix * viewMatrix * vec4(billboardPos, 1.0);\n ")}export class SpriteNodeShaderMaterial extends o{get color(){return this.uniforms.color.value}set color(o){this.uniforms.color.value=new a.Color(o)}get rotation(){return this.uniforms.rotation.value}set rotation(o){this.uniforms.rotation.value=o}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hology/core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.153",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -168,7 +168,7 @@
|
|
|
168
168
|
"dependencies": {
|
|
169
169
|
"@babel/runtime": "^7.24.8",
|
|
170
170
|
"@dimforge/rapier3d-compat": "^0.14.0",
|
|
171
|
-
"@hology/nebula": "^0.0.
|
|
171
|
+
"@hology/nebula": "^0.0.153",
|
|
172
172
|
"@plumier/reflect": "^1.1.0",
|
|
173
173
|
"@recast-navigation/three": "0.39.0",
|
|
174
174
|
"recast-navigation": "0.39.0",
|