shop-components 0.2.6 → 0.2.8
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/shop-components.cjs +3883 -1
- package/dist/shop-components.mjs +12481 -65
- package/dist/stories/device-viewer/slot/slot-item.d.ts +55 -23
- package/package.json +4 -15
- package/dist/assets/loader.worker-fysOIq2s.js +0 -7
- package/dist/cropper.cjs +0 -1244
- package/dist/cropper.mjs +0 -25459
- package/dist/device-viewer.cjs +0 -414
- package/dist/device-viewer.mjs +0 -708
- package/dist/query-YTc5aJd1.mjs +0 -708
- package/dist/query-l2HhpUKG.js +0 -39
- package/dist/scene-Ibg8IbTP.js +0 -3893
- package/dist/scene-Uu7Z9Hmw.mjs +0 -13407
package/dist/shop-components.cjs
CHANGED
|
@@ -1 +1,3883 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./scene-Ibg8IbTP.js"),i="shop-components",a="0.2.5",c="Shop components",l="dist/shop-components.umd.js",d="dist/shop-components.mjs",p="dist/main.d.ts",g={dts:"tsc --emitDeclarationOnly & tsc & storybook build -o dist",test:'echo "Error: no test specified" && exit 1',dev:"storybook dev -p 6006",build:"storybook build -o dist",vite:"vite build",vitedev:"vite dev",version:"auto-changelog -p && git add CHANGELOG.md"},u=["dist","package.json"],y=[],b="machengda<machengda@seer-group.com>",f="ISC",m={"@needle-tools/gltf-progressive":"^3.3.5","@storybook/addon-essentials":"^8.0.6","@storybook/addon-links":"^8.0.6","@storybook/addon-mdx-gfm":"^8.0.6","@storybook/addon-themes":"^8.0.6","@storybook/blocks":"^8.0.6","@storybook/web-components":"^8.0.6","@storybook/web-components-vite":"^8.0.6","auto-changelog":"^2.4.0",react:"^18.2.0","react-dom":"^18.2.0",storybook:"^8.0.6",vite:"^5.1.6","vite-plugin-dts":"^3.7.3"},h={"string-width":"4.2.3"},v={"@nodetoy/three-nodetoy":"^0.1.36","@tweakpane/core":"^2.0.3","@tweenjs/tween.js":"^23.1.2","@types/bezier-js":"^4.1.1","@types/howler":"^2.2.11","@types/three":"0.180.0","bezier-js":"^6.1.4",eventemitter3:"^5.0.1",howler:"^2.2.4",lit:"^3.1.0","stats-fps.js":"0.0.6",stylus:"^0.63.0",terser:"^5.44.0",three:"0.180.0","three-gpu-pathtracer":"0.0.23","three-mesh-bvh":"^0.7.5","troika-three-text":"^0.49.1",tweakpane:"^4.0.3"},S={name:i,version:a,description:c,main:l,module:d,types:p,scripts:g,files:u,keywords:y,author:b,license:f,devDependencies:m,resolutions:h,dependencies:v};function o(){const t="Nebular Engin",s=S.version,n=`%c ${t} %c v${s} `;console.log(n,"background:#111827;color:#ffffff;padding:4px 10px;border-radius:4px 0 0 4px;font-weight:700;","background:#10B981;color:#ffffff;padding:4px 10px;border-radius:0 4px 4px 0;font-weight:700;")}const r="__SHOP_COMPONENTS_BANNER_PRINTED__";try{const t=globalThis;t[r]||(t[r]=!0,o())}catch{o()}exports.Amr=e.Amr;Object.defineProperty(exports,"DeviceLines",{enumerable:!0,get:()=>e.DeviceLines});exports.Line=e.Line;exports.Logo=e.Logo;exports.SGLBLoader=e.SGLBLoader;exports.SLOT_EVENTS=e.SLOT_EVENTS;exports.Scene3D=e.Scene3D;exports.Skin=e.Skin;exports.Slot=e.Slot;exports.SlotState=e.SlotState;exports.TriViewCapture=e.TriViewCapture;exports.arrayBufferToUrl=e.arrayBufferToUrl;exports.calculateArrayAverage=e.calculateArrayAverage;exports.calculateFocalLength=e.calculateFocalLength;exports.createSGLBFile=e.createSGLBFile;exports.downloadBlob=e.downloadBlob;exports.dracoExporter=e.dracoExporter;exports.font=e.font;exports.gltfExporter=e.gltfExporter;exports.gltfLoader=e.gltfLoader;exports.imageBitmapToUrl=e.imageBitmapToUrl;exports.isAppleDevice=e.isAppleDevice;exports.textureLoader=e.textureLoader;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("three"),fr=require("three/examples/jsm/loaders/HDRLoader.js"),Hi=require("three/examples/jsm/postprocessing/RenderPass"),Ni=require("three/examples/jsm/postprocessing/OutlinePass"),dr=require("three/examples/jsm/postprocessing/ShaderPass"),pr=require("three/examples/jsm/shaders/FXAAShader"),mr=require("three/examples/jsm/postprocessing/UnrealBloomPass"),gr=require("three/examples/jsm/controls/OrbitControls"),vr=require("three/examples/jsm/postprocessing/OutputPass"),_r=require("three/examples/jsm/postprocessing/EffectComposer"),se=require("three/examples/jsm/renderers/CSS2DRenderer"),yr=require("three/examples/jsm/loaders/FontLoader"),xr=require("three/examples/jsm/loaders/GLTFLoader"),wr=require("three/examples/jsm/loaders/DRACOLoader"),br=require("three/examples/jsm/exporters/DRACOExporter"),Ar=require("three/examples/jsm/exporters/GLTFExporter"),Ft=require("lit"),Tr=require("three/examples/jsm/lines/LineSegments2.js"),Sr=require("three/examples/jsm/lines/LineSegmentsGeometry.js"),Os=require("three/examples/jsm/lines/LineMaterial.js"),Cr=require("three/examples/jsm/lines/Line2.js"),Wi=require("three/examples/jsm/lines/LineGeometry.js"),Mr=require("three/examples/jsm/renderers/CSS3DRenderer"),Pr=require("three/examples/jsm/utils/BufferGeometryUtils"),ue=require("three-mesh-bvh"),Ge=require("three/examples/jsm/postprocessing/Pass.js");var Ot=typeof document<"u"?document.currentScript:null;function zs(n,e,t=0){if(n.isInterleavedBufferAttribute){const i=n.itemSize;for(let r=0,l=n.count;r<l;r++){const o=r+t;e.setX(o,n.getX(r)),i>=2&&e.setY(o,n.getY(r)),i>=3&&e.setZ(o,n.getZ(r)),i>=4&&e.setW(o,n.getW(r))}}else{const i=e.array,r=i.constructor,l=i.BYTES_PER_ELEMENT*n.itemSize*t;new r(i.buffer,l,n.array.length).set(n.array)}}function nt(n,e=null){const t=n.array.constructor,i=n.normalized,r=n.itemSize,l=e===null?n.count:e;return new d.BufferAttribute(new t(r*l),r,i)}function ze(n,e){if(!n&&!e)return!0;if(!!n!=!!e)return!1;const t=n.count===e.count,i=n.normalized===e.normalized,r=n.array.constructor===e.array.constructor,l=n.itemSize===e.itemSize;return!(!t||!i||!r||!l)}function Rr(n){const e=n[0].index!==null,t=new Set(Object.keys(n[0].attributes));if(!n[0].getAttribute("position"))throw new Error("StaticGeometryGenerator: position attribute is required.");for(let i=0;i<n.length;++i){const r=n[i];let l=0;if(e!==(r.index!==null))throw new Error("StaticGeometryGenerator: All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");for(const o in r.attributes){if(!t.has(o))throw new Error('StaticGeometryGenerator: All geometries must have compatible attributes; make sure "'+o+'" attribute exists among all geometries, or in none of them.');l++}if(l!==t.size)throw new Error("StaticGeometryGenerator: All geometries must have the same number of attributes.")}}function Ir(n){let e=0;for(let t=0,i=n.length;t<i;t++)e+=n[t].getIndex().count;return e}function Er(n){let e=0;for(let t=0,i=n.length;t<i;t++)e+=n[t].getAttribute("position").count;return e}function Fr(n,e,t){n.index&&n.index.count!==e&&n.setIndex(null);const i=n.attributes;for(const r in i)i[r].count!==t&&n.deleteAttribute(r)}function Dr(n,e={},t=new d.BufferGeometry){const{useGroups:i=!1,forceUpdate:r=!1,skipAssigningAttributes:l=[],overwriteIndex:o=!0}=e;Rr(n);const c=n[0].index!==null,h=c?Ir(n):-1,m=Er(n);if(Fr(t,h,m),i){let s=0;for(let a=0,u=n.length;a<u;a++){const g=n[a];let _;c?_=g.getIndex().count:_=g.getAttribute("position").count,t.addGroup(s,_,a),s+=_}}if(c){let s=!1;if(t.index||(t.setIndex(new d.BufferAttribute(new Uint32Array(h),1,!1)),s=!0),s||o){let a=0,u=0;const g=t.getIndex();for(let _=0,f=n.length;_<f;_++){const v=n[_],y=v.getIndex();if(!(!r&&!s&&l[_]))for(let w=0;w<y.count;++w)g.setX(a+w,y.getX(w)+u);a+=y.count,u+=v.getAttribute("position").count}}}const p=Object.keys(n[0].attributes);for(let s=0,a=p.length;s<a;s++){let u=!1;const g=p[s];if(!t.getAttribute(g)){const v=n[0].getAttribute(g);t.setAttribute(g,nt(v,m)),u=!0}let _=0;const f=t.getAttribute(g);for(let v=0,y=n.length;v<y;v++){const x=n[v],w=!r&&!u&&l[v],b=x.getAttribute(g);w||zs(b,f,_),_+=b.count}}}function Br(n,e,t){const i=n.index,l=n.attributes.position.count,o=i?i.count:l;let c=n.groups;c.length===0&&(c=[{count:o,start:0,materialIndex:0}]);let h=n.getAttribute("materialIndex");if(!h||h.count!==l){let p;t.length<=255?p=new Uint8Array(l):p=new Uint16Array(l),h=new d.BufferAttribute(p,1,!1),n.deleteAttribute("materialIndex"),n.setAttribute("materialIndex",h)}const m=h.array;for(let p=0;p<c.length;p++){const s=c[p],a=s.start,u=s.count,g=Math.min(u,o-a),_=Array.isArray(e)?e[s.materialIndex]:e,f=t.indexOf(_);for(let v=0;v<g;v++){let y=a+v;i&&(y=i.getX(y)),m[y]=f}}}function Lr(n,e){if(!n.index){const t=n.attributes.position.count,i=new Array(t);for(let r=0;r<t;r++)i[r]=r;n.setIndex(i)}if(!n.attributes.normal&&e&&e.includes("normal")&&n.computeVertexNormals(),!n.attributes.uv&&e&&e.includes("uv")){const t=n.attributes.position.count;n.setAttribute("uv",new d.BufferAttribute(new Float32Array(t*2),2,!1))}if(!n.attributes.uv2&&e&&e.includes("uv2")){const t=n.attributes.position.count;n.setAttribute("uv2",new d.BufferAttribute(new Float32Array(t*2),2,!1))}if(!n.attributes.tangent&&e&&e.includes("tangent"))if(n.attributes.uv&&n.attributes.normal)n.computeTangents();else{const t=n.attributes.position.count;n.setAttribute("tangent",new d.BufferAttribute(new Float32Array(t*4),4,!1))}if(!n.attributes.color&&e&&e.includes("color")){const t=n.attributes.position.count,i=new Float32Array(t*4);i.fill(1),n.setAttribute("color",new d.BufferAttribute(i,4))}}function Ri(n){let e=0;if(n.byteLength!==0){const t=new Uint8Array(n);for(let i=0;i<n.byteLength;i++){const r=t[i];e=(e<<5)-e+r,e|=0}}return e}function Gi(n){let e=n.uuid;const t=Object.values(n.attributes);n.index&&(t.push(n.index),e+=`index|${n.index.version}`);const i=Object.keys(t).sort();for(const r of i){const l=t[r];e+=`${r}_${l.version}|`}return e}function ji(n){const e=n.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${Ri(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}class kr{constructor(e=null){this.matrixWorld=new d.Matrix4,this.geometryHash=null,this.skeletonHash=null,this.primitiveCount=-1,e!==null&&this.updateFrom(e)}updateFrom(e){const t=e.geometry,i=(t.index?t.index.count:t.attributes.position.count)/3;this.matrixWorld.copy(e.matrixWorld),this.geometryHash=Gi(t),this.primitiveCount=i,this.skeletonHash=ji(e)}didChange(e){const t=e.geometry,i=(t.index?t.index.count:t.attributes.position.count)/3;return!(this.matrixWorld.equals(e.matrixWorld)&&this.geometryHash===Gi(t)&&this.skeletonHash===ji(e)&&this.primitiveCount===i)}}const ge=new d.Vector3,ve=new d.Vector3,_e=new d.Vector3,qi=new d.Vector4,ft=new d.Vector3,Zt=new d.Vector3,Yi=new d.Vector4,Qi=new d.Vector4,dt=new d.Matrix4,Zi=new d.Matrix4;function Xi(n,e,t){const i=n.skeleton,r=n.geometry,l=i.bones,o=i.boneInverses;Yi.fromBufferAttribute(r.attributes.skinIndex,e),Qi.fromBufferAttribute(r.attributes.skinWeight,e),dt.elements.fill(0);for(let c=0;c<4;c++){const h=Qi.getComponent(c);if(h!==0){const m=Yi.getComponent(c);Zi.multiplyMatrices(l[m].matrixWorld,o[m]),Or(dt,Zi,h)}}return dt.multiply(n.bindMatrix).premultiply(n.bindMatrixInverse),t.transformDirection(dt),t}function Xt(n,e,t,i,r){ft.set(0,0,0);for(let l=0,o=n.length;l<o;l++){const c=e[l],h=n[l];c!==0&&(Zt.fromBufferAttribute(h,i),t?ft.addScaledVector(Zt,c):ft.addScaledVector(Zt.sub(r),c))}r.add(ft)}function Or(n,e,t){const i=n.elements,r=e.elements;for(let l=0,o=r.length;l<o;l++)i[l]+=r[l]*t}function zr(n){const{index:e,attributes:t}=n;if(e)for(let i=0,r=e.count;i<r;i+=3){const l=e.getX(i),o=e.getX(i+2);e.setX(i,o),e.setX(i+2,l)}else for(const i in t){const r=t[i],l=r.itemSize;for(let o=0,c=r.count;o<c;o+=3)for(let h=0;h<l;h++){const m=r.getComponent(o,h),p=r.getComponent(o+2,h);r.setComponent(o,h,p),r.setComponent(o+2,h,m)}}return n}function Vr(n,e={},t=new d.BufferGeometry){e={applyWorldTransforms:!0,attributes:[],...e};const i=n.geometry,r=e.applyWorldTransforms,l=e.attributes.includes("normal"),o=e.attributes.includes("tangent"),c=i.attributes,h=t.attributes;for(const y in t.attributes)(!e.attributes.includes(y)||!(y in i.attributes))&&t.deleteAttribute(y);!t.index&&i.index&&(t.index=i.index.clone()),h.position||t.setAttribute("position",nt(c.position)),l&&!h.normal&&c.normal&&t.setAttribute("normal",nt(c.normal)),o&&!h.tangent&&c.tangent&&t.setAttribute("tangent",nt(c.tangent)),ze(i.index,t.index),ze(c.position,h.position),l&&ze(c.normal,h.normal),o&&ze(c.tangent,h.tangent);const m=c.position,p=l?c.normal:null,s=o?c.tangent:null,a=i.morphAttributes.position,u=i.morphAttributes.normal,g=i.morphAttributes.tangent,_=i.morphTargetsRelative,f=n.morphTargetInfluences,v=new d.Matrix3;v.getNormalMatrix(n.matrixWorld),i.index&&t.index.array.set(i.index.array);for(let y=0,x=c.position.count;y<x;y++)ge.fromBufferAttribute(m,y),p&&ve.fromBufferAttribute(p,y),s&&(qi.fromBufferAttribute(s,y),_e.fromBufferAttribute(s,y)),f&&(a&&Xt(a,f,_,y,ge),u&&Xt(u,f,_,y,ve),g&&Xt(g,f,_,y,_e)),n.isSkinnedMesh&&(n.applyBoneTransform(y,ge),p&&Xi(n,y,ve),s&&Xi(n,y,_e)),r&&ge.applyMatrix4(n.matrixWorld),h.position.setXYZ(y,ge.x,ge.y,ge.z),p&&(r&&ve.applyNormalMatrix(v),h.normal.setXYZ(y,ve.x,ve.y,ve.z)),s&&(r&&_e.transformDirection(n.matrixWorld),h.tangent.setXYZW(y,_e.x,_e.y,_e.z,qi.w));for(const y in e.attributes){const x=e.attributes[y];x==="position"||x==="tangent"||x==="normal"||!(x in c)||(h[x]||t.setAttribute(x,nt(c[x])),ze(c[x],h[x]),zs(c[x],h[x]))}return n.matrixWorld.determinant()<0&&zr(t),t}class Ur extends d.BufferGeometry{constructor(){super(),this.version=0,this.hash=null,this._diff=new kr}isCompatible(e,t){const i=e.geometry;for(let r=0;r<t.length;r++){const l=t[r],o=i.attributes[l],c=this.attributes[l];if(o&&!ze(o,c))return!1}return!0}updateFrom(e,t){const i=this._diff;return i.didChange(e)?(Vr(e,t,this),i.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const ui=0,Vs=1,Us=2;function Hr(n,e){for(let t=0,i=n.length;t<i;t++)n[t].traverseVisible(l=>{l.isMesh&&e(l)})}function Nr(n){const e=[];for(let t=0,i=n.length;t<i;t++){const r=n[t];Array.isArray(r.material)?e.push(...r.material):e.push(r.material)}return e}function Wr(n,e,t){if(n.length===0){e.setIndex(null);const i=e.attributes;for(const r in i)e.deleteAttribute(r);for(const r in t.attributes)e.setAttribute(t.attributes[r],new d.BufferAttribute(new Float32Array(0),4,!1))}else Dr(n,t,e);for(const i in e.attributes)e.attributes[i].needsUpdate=!0}class Gr{constructor(e){this.objects=null,this.useGroups=!0,this.applyWorldTransforms=!0,this.generateMissingAttributes=!0,this.overwriteIndex=!0,this.attributes=["position","normal","color","tangent","uv","uv2"],this._intermediateGeometry=new Map,this._geometryMergeSets=new WeakMap,this._mergeOrder=[],this._dummyMesh=null,this.setObjects(e||[])}_getDummyMesh(){if(!this._dummyMesh){const e=new d.MeshBasicMaterial,t=new d.BufferGeometry;t.setAttribute("position",new d.BufferAttribute(new Float32Array(9),3)),this._dummyMesh=new d.Mesh(t,e)}return this._dummyMesh}_getMeshes(){const e=[];return Hr(this.objects,t=>{e.push(t)}),e.sort((t,i)=>t.uuid>i.uuid?1:t.uuid<i.uuid?-1:0),e.length===0&&e.push(this._getDummyMesh()),e}_updateIntermediateGeometries(){const{_intermediateGeometry:e}=this,t=this._getMeshes(),i=new Set(e.keys()),r={attributes:this.attributes,applyWorldTransforms:this.applyWorldTransforms};for(let l=0,o=t.length;l<o;l++){const c=t[l],h=c.uuid;i.delete(h);let m=e.get(h);(!m||!m.isCompatible(c,this.attributes))&&(m&&m.dispose(),m=new Ur,e.set(h,m)),m.updateFrom(c,r)&&this.generateMissingAttributes&&Lr(m,this.attributes)}i.forEach(l=>{e.delete(l)})}setObjects(e){Array.isArray(e)?this.objects=[...e]:this.objects=[e]}generate(e=new d.BufferGeometry){const{useGroups:t,overwriteIndex:i,_intermediateGeometry:r,_geometryMergeSets:l}=this,o=this._getMeshes(),c=[],h=[],m=l.get(e)||[];this._updateIntermediateGeometries();let p=!1;o.length!==m.length&&(p=!0);for(let a=0,u=o.length;a<u;a++){const g=o[a],_=r.get(g.uuid);h.push(_);const f=m[a];!f||f.uuid!==_.uuid?(c.push(!1),p=!0):f.version!==_.version?c.push(!1):c.push(!0)}Wr(h,e,{useGroups:t,forceUpdate:p,skipAssigningAttributes:c,overwriteIndex:i}),p&&e.dispose(),l.set(e,h.map(a=>({version:a.version,uuid:a.uuid})));let s=ui;return p?s=Us:c.includes(!1)&&(s=Vs),{changeType:s,materials:Nr(o),geometry:e}}}function jr(n){const e=new Set;for(let t=0,i=n.length;t<i;t++){const r=n[t];for(const l in r){const o=r[l];o&&o.isTexture&&e.add(o)}}return Array.from(e)}function qr(n){const e=[],t=new Set;for(let r=0,l=n.length;r<l;r++)n[r].traverse(o=>{o.visible&&(o.isRectAreaLight||o.isSpotLight||o.isPointLight||o.isDirectionalLight)&&(e.push(o),o.iesMap&&t.add(o.iesMap))});const i=Array.from(t).sort((r,l)=>r.uuid<l.uuid?1:r.uuid>l.uuid?-1:0);return{lights:e,iesTextures:i}}class Yr{get initialized(){return!!this.bvh}constructor(e){this.bvhOptions={},this.attributes=["position","normal","tangent","color","uv","uv2"],this.generateBVH=!0,this.bvh=null,this.geometry=new d.BufferGeometry,this.staticGeometryGenerator=new Gr(e),this._bvhWorker=null,this._pendingGenerate=null,this._buildAsync=!1}setObjects(e){this.staticGeometryGenerator.setObjects(e)}setBVHWorker(e){this._bvhWorker=e}async generateAsync(e=null){if(!this._bvhWorker)throw new Error('PathTracingSceneGenerator: "setBVHWorker" must be called before "generateAsync" can be called.');if(this.bvh instanceof Promise)return this._pendingGenerate||(this._pendingGenerate=new Promise(async()=>(await this.bvh,this._pendingGenerate=null,this.generateAsync(e)))),this._pendingGenerate;{this._buildAsync=!0;const t=this.generate(e);return this._buildAsync=!1,t.bvh=this.bvh=await t.bvh,t}}generate(e=null){const{staticGeometryGenerator:t,geometry:i,attributes:r}=this,l=t.objects;t.attributes=r,l.forEach(s=>{s.traverse(a=>{a.isSkinnedMesh&&a.skeleton&&a.skeleton.update()})});const o=t.generate(i),c=o.materials,h=jr(c),{lights:m,iesTextures:p}=qr(l);if(o.changeType!==ui&&Br(i,c,c),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(o.changeType===Us){const s={strategy:ue.SAH,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(i,s):this.bvh=new ue.MeshBVH(i,s)}else o.changeType===Vs&&this.bvh.refit()}return{bvhChanged:o.changeType!==ui,bvh:this.bvh,lights:m,iesTextures:p,geometry:i,materials:c,textures:h,objects:l}}}class Ii extends d.ShaderMaterial{set needsUpdate(e){super.needsUpdate=!0,this.dispatchEvent({type:"recompilation"})}constructor(e){super(e);for(const t in this.uniforms)Object.defineProperty(this,t,{get(){return this.uniforms[t].value},set(i){this.uniforms[t].value=i}})}setDefine(e,t=void 0){if(t==null){if(e in this.defines)return delete this.defines[e],this.needsUpdate=!0,!0}else if(this.defines[e]!==t)return this.defines[e]=t,this.needsUpdate=!0,!0;return!1}}class Qr extends Ii{constructor(e){super({blending:d.NoBlending,uniforms:{target1:{value:null},target2:{value:null},opacity:{value:1}},vertexShader:`
|
|
2
|
+
|
|
3
|
+
varying vec2 vUv;
|
|
4
|
+
|
|
5
|
+
void main() {
|
|
6
|
+
|
|
7
|
+
vUv = uv;
|
|
8
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
9
|
+
|
|
10
|
+
}`,fragmentShader:`
|
|
11
|
+
|
|
12
|
+
uniform float opacity;
|
|
13
|
+
|
|
14
|
+
uniform sampler2D target1;
|
|
15
|
+
uniform sampler2D target2;
|
|
16
|
+
|
|
17
|
+
varying vec2 vUv;
|
|
18
|
+
|
|
19
|
+
void main() {
|
|
20
|
+
|
|
21
|
+
vec4 color1 = texture2D( target1, vUv );
|
|
22
|
+
vec4 color2 = texture2D( target2, vUv );
|
|
23
|
+
|
|
24
|
+
float invOpacity = 1.0 - opacity;
|
|
25
|
+
float totalAlpha = color1.a * invOpacity + color2.a * opacity;
|
|
26
|
+
|
|
27
|
+
if ( color1.a != 0.0 || color2.a != 0.0 ) {
|
|
28
|
+
|
|
29
|
+
gl_FragColor.rgb = color1.rgb * ( invOpacity * color1.a / totalAlpha ) + color2.rgb * ( opacity * color2.a / totalAlpha );
|
|
30
|
+
gl_FragColor.a = totalAlpha;
|
|
31
|
+
|
|
32
|
+
} else {
|
|
33
|
+
|
|
34
|
+
gl_FragColor = vec4( 0.0 );
|
|
35
|
+
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
}`}),this.setValues(e)}}function pt(n=1){let e="uint";return n>1&&(e="uvec"+n),`
|
|
39
|
+
${e} sobolReverseBits( ${e} x ) {
|
|
40
|
+
|
|
41
|
+
x = ( ( ( x & 0xaaaaaaaau ) >> 1 ) | ( ( x & 0x55555555u ) << 1 ) );
|
|
42
|
+
x = ( ( ( x & 0xccccccccu ) >> 2 ) | ( ( x & 0x33333333u ) << 2 ) );
|
|
43
|
+
x = ( ( ( x & 0xf0f0f0f0u ) >> 4 ) | ( ( x & 0x0f0f0f0fu ) << 4 ) );
|
|
44
|
+
x = ( ( ( x & 0xff00ff00u ) >> 8 ) | ( ( x & 0x00ff00ffu ) << 8 ) );
|
|
45
|
+
return ( ( x >> 16 ) | ( x << 16 ) );
|
|
46
|
+
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
${e} sobolHashCombine( uint seed, ${e} v ) {
|
|
50
|
+
|
|
51
|
+
return seed ^ ( v + ${e}( ( seed << 6 ) + ( seed >> 2 ) ) );
|
|
52
|
+
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
${e} sobolLaineKarrasPermutation( ${e} x, ${e} seed ) {
|
|
56
|
+
|
|
57
|
+
x += seed;
|
|
58
|
+
x ^= x * 0x6c50b47cu;
|
|
59
|
+
x ^= x * 0xb82f1e52u;
|
|
60
|
+
x ^= x * 0xc7afe638u;
|
|
61
|
+
x ^= x * 0x8d22f6e6u;
|
|
62
|
+
return x;
|
|
63
|
+
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
${e} nestedUniformScrambleBase2( ${e} x, ${e} seed ) {
|
|
67
|
+
|
|
68
|
+
x = sobolLaineKarrasPermutation( x, seed );
|
|
69
|
+
x = sobolReverseBits( x );
|
|
70
|
+
return x;
|
|
71
|
+
|
|
72
|
+
}
|
|
73
|
+
`}function mt(n=1){let e="uint",t="float",i="",r=".r",l="1u";return n>1&&(e="uvec"+n,t="vec"+n,i=n+"",n===2?(r=".rg",l="uvec2( 1u, 2u )"):n===3?(r=".rgb",l="uvec3( 1u, 2u, 3u )"):(r="",l="uvec4( 1u, 2u, 3u, 4u )")),`
|
|
74
|
+
|
|
75
|
+
${t} sobol${i}( int effect ) {
|
|
76
|
+
|
|
77
|
+
uint seed = sobolGetSeed( sobolBounceIndex, uint( effect ) );
|
|
78
|
+
uint index = sobolPathIndex;
|
|
79
|
+
|
|
80
|
+
uint shuffle_seed = sobolHashCombine( seed, 0u );
|
|
81
|
+
uint shuffled_index = nestedUniformScrambleBase2( sobolReverseBits( index ), shuffle_seed );
|
|
82
|
+
${t} sobol_pt = sobolGetTexturePoint( shuffled_index )${r};
|
|
83
|
+
${e} result = ${e}( sobol_pt * 16777216.0 );
|
|
84
|
+
|
|
85
|
+
${e} seed2 = sobolHashCombine( seed, ${l} );
|
|
86
|
+
result = nestedUniformScrambleBase2( result, seed2 );
|
|
87
|
+
|
|
88
|
+
return SOBOL_FACTOR * ${t}( result >> 8 );
|
|
89
|
+
|
|
90
|
+
}
|
|
91
|
+
`}const Hs=`
|
|
92
|
+
|
|
93
|
+
// Utils
|
|
94
|
+
const float SOBOL_FACTOR = 1.0 / 16777216.0;
|
|
95
|
+
const uint SOBOL_MAX_POINTS = 256u * 256u;
|
|
96
|
+
|
|
97
|
+
${pt(1)}
|
|
98
|
+
${pt(2)}
|
|
99
|
+
${pt(3)}
|
|
100
|
+
${pt(4)}
|
|
101
|
+
|
|
102
|
+
uint sobolHash( uint x ) {
|
|
103
|
+
|
|
104
|
+
// finalizer from murmurhash3
|
|
105
|
+
x ^= x >> 16;
|
|
106
|
+
x *= 0x85ebca6bu;
|
|
107
|
+
x ^= x >> 13;
|
|
108
|
+
x *= 0xc2b2ae35u;
|
|
109
|
+
x ^= x >> 16;
|
|
110
|
+
return x;
|
|
111
|
+
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
`,Zr=`
|
|
115
|
+
|
|
116
|
+
const uint SOBOL_DIRECTIONS_1[ 32 ] = uint[ 32 ](
|
|
117
|
+
0x80000000u, 0xc0000000u, 0xa0000000u, 0xf0000000u,
|
|
118
|
+
0x88000000u, 0xcc000000u, 0xaa000000u, 0xff000000u,
|
|
119
|
+
0x80800000u, 0xc0c00000u, 0xa0a00000u, 0xf0f00000u,
|
|
120
|
+
0x88880000u, 0xcccc0000u, 0xaaaa0000u, 0xffff0000u,
|
|
121
|
+
0x80008000u, 0xc000c000u, 0xa000a000u, 0xf000f000u,
|
|
122
|
+
0x88008800u, 0xcc00cc00u, 0xaa00aa00u, 0xff00ff00u,
|
|
123
|
+
0x80808080u, 0xc0c0c0c0u, 0xa0a0a0a0u, 0xf0f0f0f0u,
|
|
124
|
+
0x88888888u, 0xccccccccu, 0xaaaaaaaau, 0xffffffffu
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
const uint SOBOL_DIRECTIONS_2[ 32 ] = uint[ 32 ](
|
|
128
|
+
0x80000000u, 0xc0000000u, 0x60000000u, 0x90000000u,
|
|
129
|
+
0xe8000000u, 0x5c000000u, 0x8e000000u, 0xc5000000u,
|
|
130
|
+
0x68800000u, 0x9cc00000u, 0xee600000u, 0x55900000u,
|
|
131
|
+
0x80680000u, 0xc09c0000u, 0x60ee0000u, 0x90550000u,
|
|
132
|
+
0xe8808000u, 0x5cc0c000u, 0x8e606000u, 0xc5909000u,
|
|
133
|
+
0x6868e800u, 0x9c9c5c00u, 0xeeee8e00u, 0x5555c500u,
|
|
134
|
+
0x8000e880u, 0xc0005cc0u, 0x60008e60u, 0x9000c590u,
|
|
135
|
+
0xe8006868u, 0x5c009c9cu, 0x8e00eeeeu, 0xc5005555u
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
const uint SOBOL_DIRECTIONS_3[ 32 ] = uint[ 32 ](
|
|
139
|
+
0x80000000u, 0xc0000000u, 0x20000000u, 0x50000000u,
|
|
140
|
+
0xf8000000u, 0x74000000u, 0xa2000000u, 0x93000000u,
|
|
141
|
+
0xd8800000u, 0x25400000u, 0x59e00000u, 0xe6d00000u,
|
|
142
|
+
0x78080000u, 0xb40c0000u, 0x82020000u, 0xc3050000u,
|
|
143
|
+
0x208f8000u, 0x51474000u, 0xfbea2000u, 0x75d93000u,
|
|
144
|
+
0xa0858800u, 0x914e5400u, 0xdbe79e00u, 0x25db6d00u,
|
|
145
|
+
0x58800080u, 0xe54000c0u, 0x79e00020u, 0xb6d00050u,
|
|
146
|
+
0x800800f8u, 0xc00c0074u, 0x200200a2u, 0x50050093u
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
const uint SOBOL_DIRECTIONS_4[ 32 ] = uint[ 32 ](
|
|
150
|
+
0x80000000u, 0x40000000u, 0x20000000u, 0xb0000000u,
|
|
151
|
+
0xf8000000u, 0xdc000000u, 0x7a000000u, 0x9d000000u,
|
|
152
|
+
0x5a800000u, 0x2fc00000u, 0xa1600000u, 0xf0b00000u,
|
|
153
|
+
0xda880000u, 0x6fc40000u, 0x81620000u, 0x40bb0000u,
|
|
154
|
+
0x22878000u, 0xb3c9c000u, 0xfb65a000u, 0xddb2d000u,
|
|
155
|
+
0x78022800u, 0x9c0b3c00u, 0x5a0fb600u, 0x2d0ddb00u,
|
|
156
|
+
0xa2878080u, 0xf3c9c040u, 0xdb65a020u, 0x6db2d0b0u,
|
|
157
|
+
0x800228f8u, 0x400b3cdcu, 0x200fb67au, 0xb00ddb9du
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
uint getMaskedSobol( uint index, uint directions[ 32 ] ) {
|
|
161
|
+
|
|
162
|
+
uint X = 0u;
|
|
163
|
+
for ( int bit = 0; bit < 32; bit ++ ) {
|
|
164
|
+
|
|
165
|
+
uint mask = ( index >> bit ) & 1u;
|
|
166
|
+
X ^= mask * directions[ bit ];
|
|
167
|
+
|
|
168
|
+
}
|
|
169
|
+
return X;
|
|
170
|
+
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
vec4 generateSobolPoint( uint index ) {
|
|
174
|
+
|
|
175
|
+
if ( index >= SOBOL_MAX_POINTS ) {
|
|
176
|
+
|
|
177
|
+
return vec4( 0.0 );
|
|
178
|
+
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// NOTE: this sobol "direction" is also available but we can't write out 5 components
|
|
182
|
+
// uint x = index & 0x00ffffffu;
|
|
183
|
+
uint x = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_1 ) ) & 0x00ffffffu;
|
|
184
|
+
uint y = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_2 ) ) & 0x00ffffffu;
|
|
185
|
+
uint z = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_3 ) ) & 0x00ffffffu;
|
|
186
|
+
uint w = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_4 ) ) & 0x00ffffffu;
|
|
187
|
+
|
|
188
|
+
return vec4( x, y, z, w ) * SOBOL_FACTOR;
|
|
189
|
+
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
`,Xr=`
|
|
193
|
+
|
|
194
|
+
// Seeds
|
|
195
|
+
uniform sampler2D sobolTexture;
|
|
196
|
+
uint sobolPixelIndex = 0u;
|
|
197
|
+
uint sobolPathIndex = 0u;
|
|
198
|
+
uint sobolBounceIndex = 0u;
|
|
199
|
+
|
|
200
|
+
uint sobolGetSeed( uint bounce, uint effect ) {
|
|
201
|
+
|
|
202
|
+
return sobolHash(
|
|
203
|
+
sobolHashCombine(
|
|
204
|
+
sobolHashCombine(
|
|
205
|
+
sobolHash( bounce ),
|
|
206
|
+
sobolPixelIndex
|
|
207
|
+
),
|
|
208
|
+
effect
|
|
209
|
+
)
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
vec4 sobolGetTexturePoint( uint index ) {
|
|
215
|
+
|
|
216
|
+
if ( index >= SOBOL_MAX_POINTS ) {
|
|
217
|
+
|
|
218
|
+
index = index % SOBOL_MAX_POINTS;
|
|
219
|
+
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
uvec2 dim = uvec2( textureSize( sobolTexture, 0 ).xy );
|
|
223
|
+
uint y = index / dim.x;
|
|
224
|
+
uint x = index - y * dim.x;
|
|
225
|
+
vec2 uv = vec2( x, y ) / vec2( dim );
|
|
226
|
+
return texture( sobolTexture, uv );
|
|
227
|
+
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
${mt(1)}
|
|
231
|
+
${mt(2)}
|
|
232
|
+
${mt(3)}
|
|
233
|
+
${mt(4)}
|
|
234
|
+
|
|
235
|
+
`;class Jr extends Ii{constructor(){super({blending:d.NoBlending,uniforms:{resolution:{value:new d.Vector2}},vertexShader:`
|
|
236
|
+
|
|
237
|
+
varying vec2 vUv;
|
|
238
|
+
void main() {
|
|
239
|
+
|
|
240
|
+
vUv = uv;
|
|
241
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
242
|
+
|
|
243
|
+
}
|
|
244
|
+
`,fragmentShader:`
|
|
245
|
+
|
|
246
|
+
${Hs}
|
|
247
|
+
${Zr}
|
|
248
|
+
|
|
249
|
+
varying vec2 vUv;
|
|
250
|
+
uniform vec2 resolution;
|
|
251
|
+
void main() {
|
|
252
|
+
|
|
253
|
+
uint index = uint( gl_FragCoord.y ) * uint( resolution.x ) + uint( gl_FragCoord.x );
|
|
254
|
+
gl_FragColor = generateSobolPoint( index );
|
|
255
|
+
|
|
256
|
+
}
|
|
257
|
+
`})}}class Kr{generate(e,t=256){const i=new d.WebGLRenderTarget(t,t,{type:d.FloatType,format:d.RGBAFormat,minFilter:d.NearestFilter,magFilter:d.NearestFilter,generateMipmaps:!1}),r=e.getRenderTarget();e.setRenderTarget(i);const l=new Ge.FullScreenQuad(new Jr);return l.material.resolution.set(t,t),l.render(e),e.setRenderTarget(r),l.dispose(),i}}class $r extends d.PerspectiveCamera{set bokehSize(e){this.fStop=this.getFocalLength()/e}get bokehSize(){return this.getFocalLength()/this.fStop}constructor(...e){super(...e),this.fStop=1.4,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=25,this.anamorphicRatio=1}copy(e,t){return super.copy(e,t),this.fStop=e.fStop,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio,this}}class en{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof $r?(this.bokehSize=e.bokehSize,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio):(this.bokehSize=0,this.apertureRotation=0,this.apertureBlades=0,this.focusDistance=10,this.anamorphicRatio=1)}}function Jt(n){const e=new Uint16Array(n.length);for(let t=0,i=n.length;t<i;++t)e[t]=d.DataUtils.toHalfFloat(n[t]);return e}function Ji(n,e,t=0,i=n.length){let r=t,l=t+i-1;for(;r<l;){const o=r+l>>1;n[o]<e?r=o+1:l=o}return r-t}function tn(n,e,t){return .2126*n+.7152*e+.0722*t}function sn(n,e=d.HalfFloatType){const t=n.clone();t.source=new d.Source({...t.image});const{width:i,height:r,data:l}=t.image;let o=l;if(t.type!==e){e===d.HalfFloatType?o=new Uint16Array(l.length):o=new Float32Array(l.length);let c;l instanceof Int8Array||l instanceof Int16Array||l instanceof Int32Array?c=2**(8*l.BYTES_PER_ELEMENT-1)-1:c=2**(8*l.BYTES_PER_ELEMENT)-1;for(let h=0,m=l.length;h<m;h++){let p=l[h];t.type===d.HalfFloatType&&(p=d.DataUtils.fromHalfFloat(l[h])),t.type!==d.FloatType&&t.type!==d.HalfFloatType&&(p/=c),e===d.HalfFloatType&&(o[h]=d.DataUtils.toHalfFloat(p))}t.image.data=o,t.type=e}if(t.flipY){const c=o;o=o.slice();for(let h=0;h<r;h++)for(let m=0;m<i;m++){const p=r-h-1,s=4*(h*i+m),a=4*(p*i+m);o[a+0]=c[s+0],o[a+1]=c[s+1],o[a+2]=c[s+2],o[a+3]=c[s+3]}t.flipY=!1,t.image.data=o}return t}class rn{constructor(){const e=new d.DataTexture(Jt(new Float32Array([0,0,0,0])),1,1);e.type=d.HalfFloatType,e.format=d.RGBAFormat,e.minFilter=d.LinearFilter,e.magFilter=d.LinearFilter,e.wrapS=d.RepeatWrapping,e.wrapT=d.RepeatWrapping,e.generateMipmaps=!1,e.needsUpdate=!0;const t=new d.DataTexture(Jt(new Float32Array([0,1])),1,2);t.type=d.HalfFloatType,t.format=d.RedFormat,t.minFilter=d.LinearFilter,t.magFilter=d.LinearFilter,t.generateMipmaps=!1,t.needsUpdate=!0;const i=new d.DataTexture(Jt(new Float32Array([0,0,1,1])),2,2);i.type=d.HalfFloatType,i.format=d.RedFormat,i.minFilter=d.LinearFilter,i.magFilter=d.LinearFilter,i.generateMipmaps=!1,i.needsUpdate=!0,this.map=e,this.marginalWeights=t,this.conditionalWeights=i,this.totalSum=0}dispose(){this.marginalWeights.dispose(),this.conditionalWeights.dispose(),this.map.dispose()}updateFrom(e){const t=sn(e);t.wrapS=d.RepeatWrapping,t.wrapT=d.ClampToEdgeWrapping;const{width:i,height:r,data:l}=t.image,o=new Float32Array(i*r),c=new Float32Array(i*r),h=new Float32Array(r),m=new Float32Array(r);let p=0,s=0;for(let f=0;f<r;f++){let v=0;for(let y=0;y<i;y++){const x=f*i+y,w=d.DataUtils.fromHalfFloat(l[4*x+0]),b=d.DataUtils.fromHalfFloat(l[4*x+1]),C=d.DataUtils.fromHalfFloat(l[4*x+2]),T=tn(w,b,C);v+=T,p+=T,o[x]=T,c[x]=v}if(v!==0)for(let y=f*i,x=f*i+i;y<x;y++)o[y]/=v,c[y]/=v;s+=v,h[f]=v,m[f]=s}if(s!==0)for(let f=0,v=h.length;f<v;f++)h[f]/=s,m[f]/=s;const a=new Uint16Array(r),u=new Uint16Array(i*r);for(let f=0;f<r;f++){const v=(f+1)/r,y=Ji(m,v);a[f]=d.DataUtils.toHalfFloat((y+.5)/r)}for(let f=0;f<r;f++)for(let v=0;v<i;v++){const y=f*i+v,x=(v+1)/i,w=Ji(c,x,f*i,i);u[y]=d.DataUtils.toHalfFloat((w+.5)/i)}this.dispose();const{marginalWeights:g,conditionalWeights:_}=this;g.image={width:r,height:1,data:a},g.needsUpdate=!0,_.image={width:i,height:r,data:u},_.needsUpdate=!0,this.totalSum=p,this.map=t}}const Kt=6,nn=0,on=1,an=2,ln=3,cn=4,$=new d.Vector3,j=new d.Vector3,Ki=new d.Matrix4,Se=new d.Quaternion,$i=new d.Vector3,Ce=new d.Vector3,hn=new d.Vector3(0,1,0);class un{constructor(){const e=new d.DataTexture(new Float32Array(4),1,1);e.format=d.RGBAFormat,e.type=d.FloatType,e.wrapS=d.ClampToEdgeWrapping,e.wrapT=d.ClampToEdgeWrapping,e.generateMipmaps=!1,e.minFilter=d.NearestFilter,e.magFilter=d.NearestFilter,this.tex=e,this.count=0}updateFrom(e,t=[]){const i=this.tex,r=Math.max(e.length*Kt,1),l=Math.ceil(Math.sqrt(r));i.image.width!==l&&(i.dispose(),i.image.data=new Float32Array(l*l*4),i.image.width=l,i.image.height=l);const o=i.image.data;for(let h=0,m=e.length;h<m;h++){const p=e[h],s=h*Kt*4;let a=0;for(let g=0;g<Kt*4;g++)o[s+g]=0;p.getWorldPosition(j),o[s+a++]=j.x,o[s+a++]=j.y,o[s+a++]=j.z;let u=nn;if(p.isRectAreaLight&&p.isCircular?u=on:p.isSpotLight?u=an:p.isDirectionalLight?u=ln:p.isPointLight&&(u=cn),o[s+a++]=u,o[s+a++]=p.color.r,o[s+a++]=p.color.g,o[s+a++]=p.color.b,o[s+a++]=p.intensity,p.getWorldQuaternion(Se),p.isRectAreaLight)$.set(p.width,0,0).applyQuaternion(Se),o[s+a++]=$.x,o[s+a++]=$.y,o[s+a++]=$.z,a++,j.set(0,p.height,0).applyQuaternion(Se),o[s+a++]=j.x,o[s+a++]=j.y,o[s+a++]=j.z,o[s+a++]=$.cross(j).length()*(p.isCircular?Math.PI/4:1);else if(p.isSpotLight){const g=p.radius||0;$i.setFromMatrixPosition(p.matrixWorld),Ce.setFromMatrixPosition(p.target.matrixWorld),Ki.lookAt($i,Ce,hn),Se.setFromRotationMatrix(Ki),$.set(1,0,0).applyQuaternion(Se),o[s+a++]=$.x,o[s+a++]=$.y,o[s+a++]=$.z,a++,j.set(0,1,0).applyQuaternion(Se),o[s+a++]=j.x,o[s+a++]=j.y,o[s+a++]=j.z,o[s+a++]=Math.PI*g*g,o[s+a++]=g,o[s+a++]=p.decay,o[s+a++]=p.distance,o[s+a++]=Math.cos(p.angle),o[s+a++]=Math.cos(p.angle*(1-p.penumbra)),o[s+a++]=p.iesMap?t.indexOf(p.iesMap):-1}else if(p.isPointLight){const g=$.setFromMatrixPosition(p.matrixWorld);o[s+a++]=g.x,o[s+a++]=g.y,o[s+a++]=g.z,a++,a+=4,a+=1,o[s+a++]=p.decay,o[s+a++]=p.distance}else if(p.isDirectionalLight){const g=$.setFromMatrixPosition(p.matrixWorld),_=j.setFromMatrixPosition(p.target.matrixWorld);Ce.subVectors(g,_).normalize(),o[s+a++]=Ce.x,o[s+a++]=Ce.y,o[s+a++]=Ce.z}}this.count=e.length;const c=Ri(o.buffer);return this.hash!==c?(this.hash=c,i.needsUpdate=!0,!0):!1}}function es(n,e,t,i,r){if(e>i)throw new Error;const l=n.length/e,o=n.constructor.BYTES_PER_ELEMENT*8;let c=1;switch(n.constructor){case Uint8Array:case Uint16Array:case Uint32Array:c=2**o-1;break;case Int8Array:case Int16Array:case Int32Array:c=2**(o-1)-1;break}for(let h=0;h<l;h++){const m=4*h,p=e*h;for(let s=0;s<i;s++)t[r+m+s]=e>=s+1?n[p+s]/c:0}}class fn extends d.DataArrayTexture{constructor(){super(),this._textures=[],this.type=d.FloatType,this.format=d.RGBAFormat,this.internalFormat="RGBA32F"}updateAttribute(e,t){const i=this._textures[e];i.updateFrom(t);const r=i.image,l=this.image;if(r.width!==l.width||r.height!==l.height)throw new Error("FloatAttributeTextureArray: Attribute must be the same dimensions when updating single layer.");const{width:o,height:c,data:h}=l,p=o*c*4*e;let s=t.itemSize;s===3&&(s=4),es(i.image.data,s,h,4,p),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,i=e.length;for(let s=0,a=i;s<a;s++)if(e[s].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const r=this._textures;for(;r.length<i;){const s=new ue.FloatVertexAttributeTexture;r.push(s)}for(;r.length>i;)r.pop();for(let s=0,a=i;s<a;s++)r[s].updateFrom(e[s]);const o=r[0].image,c=this.image;(o.width!==c.width||o.height!==c.height||o.depth!==i)&&(c.width=o.width,c.height=o.height,c.depth=i,c.data=new Float32Array(c.width*c.height*c.depth*4));const{data:h,width:m,height:p}=c;for(let s=0,a=i;s<a;s++){const u=r[s],_=m*p*4*s;let f=e[s].itemSize;f===3&&(f=4),es(u.image.data,f,h,4,_)}this.dispose(),this.needsUpdate=!0}}class dn extends fn{updateNormalAttribute(e){this.updateAttribute(0,e)}updateTangentAttribute(e){this.updateAttribute(1,e)}updateUvAttribute(e){this.updateAttribute(2,e)}updateColorAttribute(e){this.updateAttribute(3,e)}updateFrom(e,t,i,r){this.setAttributes([e,t,i,r])}}function Ei(n,e){return n.uuid<e.uuid?1:n.uuid>e.uuid?-1:0}function fi(n){return`${n.source.uuid}:${n.colorSpace}`}function pn(n){const e=new Set,t=[];for(let i=0,r=n.length;i<r;i++){const l=n[i],o=fi(l);e.has(o)||(e.add(o),t.push(l))}return t}function mn(n){const e=n.map(i=>i.iesMap||null).filter(i=>i),t=new Set(e);return Array.from(t).sort(Ei)}function gn(n){const e=new Set;for(let i=0,r=n.length;i<r;i++){const l=n[i];for(const o in l){const c=l[o];c&&c.isTexture&&e.add(c)}}const t=Array.from(e);return pn(t).sort(Ei)}function vn(n){const e=[];return n.traverse(t=>{t.visible&&(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight)&&e.push(t)}),e.sort(Ei)}const Ns=45,ts=Ns*4;class _n{constructor(){this._features={}}isUsed(e){return e in this._features}setUsed(e,t=!0){t===!1?delete this._features[e]:this._features[e]=!0}reset(){this._features={}}}class yn extends d.DataTexture{constructor(){super(new Float32Array(4),1,1),this.format=d.RGBAFormat,this.type=d.FloatType,this.wrapS=d.ClampToEdgeWrapping,this.wrapT=d.ClampToEdgeWrapping,this.minFilter=d.NearestFilter,this.magFilter=d.NearestFilter,this.generateMipmaps=!1,this.features=new _n}updateFrom(e,t){function i(g,_,f=-1){if(_ in g&&g[_]){const v=fi(g[_]);return s[v]}else return f}function r(g,_,f){return _ in g?g[_]:f}function l(g,_,f,v){const y=g[_]&&g[_].isTexture?g[_]:null;if(y){y.matrixAutoUpdate&&y.updateMatrix();const x=y.matrix.elements;let w=0;f[v+w++]=x[0],f[v+w++]=x[3],f[v+w++]=x[6],w++,f[v+w++]=x[1],f[v+w++]=x[4],f[v+w++]=x[7],w++}return 8}let o=0;const c=e.length*Ns,h=Math.ceil(Math.sqrt(c))||1,{image:m,features:p}=this,s={};for(let g=0,_=t.length;g<_;g++)s[fi(t[g])]=g;m.width!==h&&(this.dispose(),m.data=new Float32Array(h*h*4),m.width=h,m.height=h);const a=m.data;p.reset();for(let g=0,_=e.length;g<_;g++){const f=e[g];if(f.isFogVolumeMaterial){p.setUsed("FOG");for(let x=0;x<ts;x++)a[o+x]=0;a[o+0*4+0]=f.color.r,a[o+0*4+1]=f.color.g,a[o+0*4+2]=f.color.b,a[o+2*4+3]=r(f,"emissiveIntensity",0),a[o+3*4+0]=f.emissive.r,a[o+3*4+1]=f.emissive.g,a[o+3*4+2]=f.emissive.b,a[o+13*4+1]=f.density,a[o+13*4+3]=0,a[o+14*4+2]=4,o+=ts;continue}a[o++]=f.color.r,a[o++]=f.color.g,a[o++]=f.color.b,a[o++]=i(f,"map"),a[o++]=r(f,"metalness",0),a[o++]=i(f,"metalnessMap"),a[o++]=r(f,"roughness",0),a[o++]=i(f,"roughnessMap"),a[o++]=r(f,"ior",1.5),a[o++]=r(f,"transmission",0),a[o++]=i(f,"transmissionMap"),a[o++]=r(f,"emissiveIntensity",0),"emissive"in f?(a[o++]=f.emissive.r,a[o++]=f.emissive.g,a[o++]=f.emissive.b):(a[o++]=0,a[o++]=0,a[o++]=0),a[o++]=i(f,"emissiveMap"),a[o++]=i(f,"normalMap"),"normalScale"in f?(a[o++]=f.normalScale.x,a[o++]=f.normalScale.y):(a[o++]=1,a[o++]=1),a[o++]=r(f,"clearcoat",0),a[o++]=i(f,"clearcoatMap"),a[o++]=r(f,"clearcoatRoughness",0),a[o++]=i(f,"clearcoatRoughnessMap"),a[o++]=i(f,"clearcoatNormalMap"),"clearcoatNormalScale"in f?(a[o++]=f.clearcoatNormalScale.x,a[o++]=f.clearcoatNormalScale.y):(a[o++]=1,a[o++]=1),o++,a[o++]=r(f,"sheen",0),"sheenColor"in f?(a[o++]=f.sheenColor.r,a[o++]=f.sheenColor.g,a[o++]=f.sheenColor.b):(a[o++]=0,a[o++]=0,a[o++]=0),a[o++]=i(f,"sheenColorMap"),a[o++]=r(f,"sheenRoughness",0),a[o++]=i(f,"sheenRoughnessMap"),a[o++]=i(f,"iridescenceMap"),a[o++]=i(f,"iridescenceThicknessMap"),a[o++]=r(f,"iridescence",0),a[o++]=r(f,"iridescenceIOR",1.3);const v=r(f,"iridescenceThicknessRange",[100,400]);a[o++]=v[0],a[o++]=v[1],"specularColor"in f?(a[o++]=f.specularColor.r,a[o++]=f.specularColor.g,a[o++]=f.specularColor.b):(a[o++]=1,a[o++]=1,a[o++]=1),a[o++]=i(f,"specularColorMap"),a[o++]=r(f,"specularIntensity",1),a[o++]=i(f,"specularIntensityMap");const y=r(f,"thickness",0)===0&&r(f,"attenuationDistance",1/0)===1/0;if(a[o++]=Number(y),o++,"attenuationColor"in f?(a[o++]=f.attenuationColor.r,a[o++]=f.attenuationColor.g,a[o++]=f.attenuationColor.b):(a[o++]=1,a[o++]=1,a[o++]=1),a[o++]=r(f,"attenuationDistance",1/0),a[o++]=i(f,"alphaMap"),a[o++]=f.opacity,a[o++]=f.alphaTest,!y&&f.transmission>0)a[o++]=0;else switch(f.side){case d.FrontSide:a[o++]=1;break;case d.BackSide:a[o++]=-1;break;case d.DoubleSide:a[o++]=0;break}a[o++]=Number(r(f,"matte",!1)),a[o++]=Number(r(f,"castShadow",!0)),a[o++]=Number(f.vertexColors)|Number(f.flatShading)<<1,a[o++]=Number(f.transparent),o+=l(f,"map",a,o),o+=l(f,"metalnessMap",a,o),o+=l(f,"roughnessMap",a,o),o+=l(f,"transmissionMap",a,o),o+=l(f,"emissiveMap",a,o),o+=l(f,"normalMap",a,o),o+=l(f,"clearcoatMap",a,o),o+=l(f,"clearcoatNormalMap",a,o),o+=l(f,"clearcoatRoughnessMap",a,o),o+=l(f,"sheenColorMap",a,o),o+=l(f,"sheenRoughnessMap",a,o),o+=l(f,"iridescenceMap",a,o),o+=l(f,"iridescenceThicknessMap",a,o),o+=l(f,"specularColorMap",a,o),o+=l(f,"specularIntensityMap",a,o)}const u=Ri(a.buffer);return this.hash!==u?(this.hash=u,this.needsUpdate=!0,!0):!1}}const is=new d.Color;function xn(n){return n?`${n.uuid}:${n.version}`:null}function wn(n,e){for(const t in e)t in n&&(n[t]=e[t])}class ss extends d.WebGLArrayRenderTarget{constructor(e,t,i){const r={format:d.RGBAFormat,type:d.UnsignedByteType,minFilter:d.LinearFilter,magFilter:d.LinearFilter,wrapS:d.RepeatWrapping,wrapT:d.RepeatWrapping,generateMipmaps:!1,...i};super(e,t,1,r),wn(this.texture,r),this.texture.setTextures=(...o)=>{this.setTextures(...o)},this.hashes=[null];const l=new Ge.FullScreenQuad(new bn);this.fsQuad=l}setTextures(e,t,i=this.width,r=this.height){const l=e.getRenderTarget(),o=e.toneMapping,c=e.getClearAlpha();e.getClearColor(is);const h=t.length||1;(i!==this.width||r!==this.height||this.depth!==h)&&(this.setSize(i,r,h),this.hashes=new Array(h).fill(null)),e.setClearColor(0,0),e.toneMapping=d.NoToneMapping;const m=this.fsQuad,p=this.hashes;let s=!1;for(let a=0,u=h;a<u;a++){const g=t[a],_=xn(g);g&&(p[a]!==_||g.isWebGLRenderTarget)&&(g.matrixAutoUpdate=!1,g.matrix.identity(),m.material.map=g,e.setRenderTarget(this,a),m.render(e),g.updateMatrix(),g.matrixAutoUpdate=!0,p[a]=_,s=!0)}return m.material.map=null,e.setClearColor(is,c),e.setRenderTarget(l),e.toneMapping=o,s}dispose(){super.dispose(),this.fsQuad.dispose()}}class bn extends d.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}constructor(){super({uniforms:{map:{value:null}},vertexShader:`
|
|
258
|
+
varying vec2 vUv;
|
|
259
|
+
void main() {
|
|
260
|
+
|
|
261
|
+
vUv = uv;
|
|
262
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
263
|
+
|
|
264
|
+
}
|
|
265
|
+
`,fragmentShader:`
|
|
266
|
+
uniform sampler2D map;
|
|
267
|
+
varying vec2 vUv;
|
|
268
|
+
void main() {
|
|
269
|
+
|
|
270
|
+
gl_FragColor = texture2D( map, vUv );
|
|
271
|
+
|
|
272
|
+
}
|
|
273
|
+
`})}}function An(n,e=Math.random()){for(let t=n.length-1;t>0;t--){const i=Math.floor(e()*(t+1)),r=n[t];n[t]=n[i],n[i]=r}return n}class Tn{constructor(e,t,i=Math.random){const r=e**t,l=new Uint16Array(r);let o=r;for(let c=0;c<r;c++)l[c]=c;this.samples=new Float32Array(t),this.strataCount=e,this.reset=function(){for(let c=0;c<r;c++)l[c]=c;o=0},this.reshuffle=function(){o=0},this.next=function(){const{samples:c}=this;o>=l.length&&(An(l,i),this.reshuffle());let h=l[o++];for(let m=0;m<t;m++)c[m]=(h%e+i())/e,h=Math.floor(h/e);return c}}}class Sn{constructor(e,t,i=Math.random){let r=0;for(const h of t)r+=h;const l=new Float32Array(r),o=[];let c=0;for(const h of t){const m=new Tn(e,h,i);m.samples=new Float32Array(l.buffer,c,m.samples.length),c+=m.samples.length*4,o.push(m)}this.samples=l,this.strataCount=e,this.next=function(){for(const h of o)h.next();return l},this.reshuffle=function(){for(const h of o)h.reshuffle()},this.reset=function(){for(const h of o)h.reset()}}}class Cn{constructor(e=0){this.m=2147483648,this.a=1103515245,this.c=12345,this.seed=e}nextInt(){return this.seed=(this.a*this.seed+this.c)%this.m,this.seed}nextFloat(){return this.nextInt()/(this.m-1)}}class Mn extends d.DataTexture{constructor(e=1,t=1,i=8){super(new Float32Array(1),1,1,d.RGBAFormat,d.FloatType),this.minFilter=d.NearestFilter,this.magFilter=d.NearestFilter,this.strata=i,this.sampler=null,this.generator=new Cn,this.stableNoise=!1,this.random=()=>this.stableNoise?this.generator.nextFloat():Math.random(),this.init(e,t,i)}init(e=this.image.height,t=this.image.width,i=this.strata){const{image:r}=this;if(r.width===t&&r.height===e&&this.sampler!==null)return;const l=new Array(e*t).fill(4),o=new Sn(i,l,this.random);r.width=t,r.height=e,r.data=o.samples,this.sampler=o,this.dispose(),this.next()}next(){this.sampler.next(),this.needsUpdate=!0}reset(){this.sampler.reset(),this.generator.seed=0}}function Pn(n,e=Math.random){for(let t=n.length-1;t>0;t--){const i=~~((e()-1e-6)*t),r=n[t];n[t]=n[i],n[i]=r}}function Rn(n,e){n.fill(0);for(let t=0;t<e;t++)n[t]=1}class rs{constructor(e){this.count=0,this.size=-1,this.sigma=-1,this.radius=-1,this.lookupTable=null,this.score=null,this.binaryPattern=null,this.resize(e),this.setSigma(1.5)}findVoid(){const{score:e,binaryPattern:t}=this;let i=1/0,r=-1;for(let l=0,o=t.length;l<o;l++){if(t[l]!==0)continue;const c=e[l];c<i&&(i=c,r=l)}return r}findCluster(){const{score:e,binaryPattern:t}=this;let i=-1/0,r=-1;for(let l=0,o=t.length;l<o;l++){if(t[l]!==1)continue;const c=e[l];c>i&&(i=c,r=l)}return r}setSigma(e){if(e===this.sigma)return;const t=~~(Math.sqrt(10*2*e**2)+1),i=2*t+1,r=new Float32Array(i*i),l=e*e;for(let o=-t;o<=t;o++)for(let c=-t;c<=t;c++){const h=(t+c)*i+o+t,m=o*o+c*c;r[h]=Math.E**(-m/(2*l))}this.lookupTable=r,this.sigma=e,this.radius=t}resize(e){this.size!==e&&(this.size=e,this.score=new Float32Array(e*e),this.binaryPattern=new Uint8Array(e*e))}invert(){const{binaryPattern:e,score:t,size:i}=this;t.fill(0);for(let r=0,l=e.length;r<l;r++)if(e[r]===0){const o=~~(r/i),c=r-o*i;this.updateScore(c,o,1),e[r]=1}else e[r]=0}updateScore(e,t,i){const{size:r,score:l,lookupTable:o}=this,c=this.radius,h=2*c+1;for(let m=-c;m<=c;m++)for(let p=-c;p<=c;p++){const s=(c+p)*h+m+c,a=o[s];let u=e+m;u=u<0?r+u:u%r;let g=t+p;g=g<0?r+g:g%r;const _=g*r+u;l[_]+=i*a}}addPointIndex(e){this.binaryPattern[e]=1;const t=this.size,i=~~(e/t),r=e-i*t;this.updateScore(r,i,1),this.count++}removePointIndex(e){this.binaryPattern[e]=0;const t=this.size,i=~~(e/t),r=e-i*t;this.updateScore(r,i,-1),this.count--}copy(e){this.resize(e.size),this.score.set(e.score),this.binaryPattern.set(e.binaryPattern),this.setSigma(e.sigma),this.count=e.count}}class In{constructor(){this.random=Math.random,this.sigma=1.5,this.size=64,this.majorityPointsRatio=.1,this.samples=new rs(1),this.savedSamples=new rs(1)}generate(){const{samples:e,savedSamples:t,sigma:i,majorityPointsRatio:r,size:l}=this;e.resize(l),e.setSigma(i);const o=Math.floor(l*l*r),c=e.binaryPattern;Rn(c,o),Pn(c,this.random);for(let s=0,a=c.length;s<a;s++)c[s]===1&&e.addPointIndex(s);for(;;){const s=e.findCluster();e.removePointIndex(s);const a=e.findVoid();if(s===a){e.addPointIndex(s);break}e.addPointIndex(a)}const h=new Uint32Array(l*l);t.copy(e);let m;for(m=e.count-1;m>=0;){const s=e.findCluster();e.removePointIndex(s),h[s]=m,m--}const p=l*l;for(m=t.count;m<p/2;){const s=t.findVoid();t.addPointIndex(s),h[s]=m,m++}for(t.invert();m<p;){const s=t.findCluster();t.removePointIndex(s),h[s]=m,m++}return{data:h,maxValue:p}}}function En(n){return n>=3?4:n}function Fn(n){switch(n){case 1:return d.RedFormat;case 2:return d.RGFormat;default:return d.RGBAFormat}}class Dn extends d.DataTexture{constructor(e=64,t=1){super(new Float32Array(4),1,1,d.RGBAFormat,d.FloatType),this.minFilter=d.NearestFilter,this.magFilter=d.NearestFilter,this.size=e,this.channels=t,this.update()}update(){const e=this.channels,t=this.size,i=new In;i.channels=e,i.size=t;const r=En(e),l=Fn(r);(this.image.width!==t||l!==this.format)&&(this.image.width=t,this.image.height=t,this.image.data=new Float32Array(t**2*r),this.format=l,this.dispose());const o=this.image.data;for(let c=0,h=e;c<h;c++){const m=i.generate(),p=m.data,s=m.maxValue;for(let a=0,u=p.length;a<u;a++){const g=p[a]/s;o[a*r+c]=g}}this.needsUpdate=!0}}const Bn=`
|
|
274
|
+
|
|
275
|
+
struct PhysicalCamera {
|
|
276
|
+
|
|
277
|
+
float focusDistance;
|
|
278
|
+
float anamorphicRatio;
|
|
279
|
+
float bokehSize;
|
|
280
|
+
int apertureBlades;
|
|
281
|
+
float apertureRotation;
|
|
282
|
+
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
`,Ln=`
|
|
286
|
+
|
|
287
|
+
struct EquirectHdrInfo {
|
|
288
|
+
|
|
289
|
+
sampler2D marginalWeights;
|
|
290
|
+
sampler2D conditionalWeights;
|
|
291
|
+
sampler2D map;
|
|
292
|
+
|
|
293
|
+
float totalSum;
|
|
294
|
+
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
`,kn=`
|
|
298
|
+
|
|
299
|
+
#define RECT_AREA_LIGHT_TYPE 0
|
|
300
|
+
#define CIRC_AREA_LIGHT_TYPE 1
|
|
301
|
+
#define SPOT_LIGHT_TYPE 2
|
|
302
|
+
#define DIR_LIGHT_TYPE 3
|
|
303
|
+
#define POINT_LIGHT_TYPE 4
|
|
304
|
+
|
|
305
|
+
struct LightsInfo {
|
|
306
|
+
|
|
307
|
+
sampler2D tex;
|
|
308
|
+
uint count;
|
|
309
|
+
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
struct Light {
|
|
313
|
+
|
|
314
|
+
vec3 position;
|
|
315
|
+
int type;
|
|
316
|
+
|
|
317
|
+
vec3 color;
|
|
318
|
+
float intensity;
|
|
319
|
+
|
|
320
|
+
vec3 u;
|
|
321
|
+
vec3 v;
|
|
322
|
+
float area;
|
|
323
|
+
|
|
324
|
+
// spot light fields
|
|
325
|
+
float radius;
|
|
326
|
+
float near;
|
|
327
|
+
float decay;
|
|
328
|
+
float distance;
|
|
329
|
+
float coneCos;
|
|
330
|
+
float penumbraCos;
|
|
331
|
+
int iesProfile;
|
|
332
|
+
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
Light readLightInfo( sampler2D tex, uint index ) {
|
|
336
|
+
|
|
337
|
+
uint i = index * 6u;
|
|
338
|
+
|
|
339
|
+
vec4 s0 = texelFetch1D( tex, i + 0u );
|
|
340
|
+
vec4 s1 = texelFetch1D( tex, i + 1u );
|
|
341
|
+
vec4 s2 = texelFetch1D( tex, i + 2u );
|
|
342
|
+
vec4 s3 = texelFetch1D( tex, i + 3u );
|
|
343
|
+
|
|
344
|
+
Light l;
|
|
345
|
+
l.position = s0.rgb;
|
|
346
|
+
l.type = int( round( s0.a ) );
|
|
347
|
+
|
|
348
|
+
l.color = s1.rgb;
|
|
349
|
+
l.intensity = s1.a;
|
|
350
|
+
|
|
351
|
+
l.u = s2.rgb;
|
|
352
|
+
l.v = s3.rgb;
|
|
353
|
+
l.area = s3.a;
|
|
354
|
+
|
|
355
|
+
if ( l.type == SPOT_LIGHT_TYPE || l.type == POINT_LIGHT_TYPE ) {
|
|
356
|
+
|
|
357
|
+
vec4 s4 = texelFetch1D( tex, i + 4u );
|
|
358
|
+
vec4 s5 = texelFetch1D( tex, i + 5u );
|
|
359
|
+
l.radius = s4.r;
|
|
360
|
+
l.decay = s4.g;
|
|
361
|
+
l.distance = s4.b;
|
|
362
|
+
l.coneCos = s4.a;
|
|
363
|
+
|
|
364
|
+
l.penumbraCos = s5.r;
|
|
365
|
+
l.iesProfile = int( round( s5.g ) );
|
|
366
|
+
|
|
367
|
+
} else {
|
|
368
|
+
|
|
369
|
+
l.radius = 0.0;
|
|
370
|
+
l.decay = 0.0;
|
|
371
|
+
l.distance = 0.0;
|
|
372
|
+
|
|
373
|
+
l.coneCos = 0.0;
|
|
374
|
+
l.penumbraCos = 0.0;
|
|
375
|
+
l.iesProfile = - 1;
|
|
376
|
+
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
return l;
|
|
380
|
+
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
`,On=`
|
|
384
|
+
|
|
385
|
+
struct Material {
|
|
386
|
+
|
|
387
|
+
vec3 color;
|
|
388
|
+
int map;
|
|
389
|
+
|
|
390
|
+
float metalness;
|
|
391
|
+
int metalnessMap;
|
|
392
|
+
|
|
393
|
+
float roughness;
|
|
394
|
+
int roughnessMap;
|
|
395
|
+
|
|
396
|
+
float ior;
|
|
397
|
+
float transmission;
|
|
398
|
+
int transmissionMap;
|
|
399
|
+
|
|
400
|
+
float emissiveIntensity;
|
|
401
|
+
vec3 emissive;
|
|
402
|
+
int emissiveMap;
|
|
403
|
+
|
|
404
|
+
int normalMap;
|
|
405
|
+
vec2 normalScale;
|
|
406
|
+
|
|
407
|
+
float clearcoat;
|
|
408
|
+
int clearcoatMap;
|
|
409
|
+
int clearcoatNormalMap;
|
|
410
|
+
vec2 clearcoatNormalScale;
|
|
411
|
+
float clearcoatRoughness;
|
|
412
|
+
int clearcoatRoughnessMap;
|
|
413
|
+
|
|
414
|
+
int iridescenceMap;
|
|
415
|
+
int iridescenceThicknessMap;
|
|
416
|
+
float iridescence;
|
|
417
|
+
float iridescenceIor;
|
|
418
|
+
float iridescenceThicknessMinimum;
|
|
419
|
+
float iridescenceThicknessMaximum;
|
|
420
|
+
|
|
421
|
+
vec3 specularColor;
|
|
422
|
+
int specularColorMap;
|
|
423
|
+
|
|
424
|
+
float specularIntensity;
|
|
425
|
+
int specularIntensityMap;
|
|
426
|
+
bool thinFilm;
|
|
427
|
+
|
|
428
|
+
vec3 attenuationColor;
|
|
429
|
+
float attenuationDistance;
|
|
430
|
+
|
|
431
|
+
int alphaMap;
|
|
432
|
+
|
|
433
|
+
bool castShadow;
|
|
434
|
+
float opacity;
|
|
435
|
+
float alphaTest;
|
|
436
|
+
|
|
437
|
+
float side;
|
|
438
|
+
bool matte;
|
|
439
|
+
|
|
440
|
+
float sheen;
|
|
441
|
+
vec3 sheenColor;
|
|
442
|
+
int sheenColorMap;
|
|
443
|
+
float sheenRoughness;
|
|
444
|
+
int sheenRoughnessMap;
|
|
445
|
+
|
|
446
|
+
bool vertexColors;
|
|
447
|
+
bool flatShading;
|
|
448
|
+
bool transparent;
|
|
449
|
+
bool fogVolume;
|
|
450
|
+
|
|
451
|
+
mat3 mapTransform;
|
|
452
|
+
mat3 metalnessMapTransform;
|
|
453
|
+
mat3 roughnessMapTransform;
|
|
454
|
+
mat3 transmissionMapTransform;
|
|
455
|
+
mat3 emissiveMapTransform;
|
|
456
|
+
mat3 normalMapTransform;
|
|
457
|
+
mat3 clearcoatMapTransform;
|
|
458
|
+
mat3 clearcoatNormalMapTransform;
|
|
459
|
+
mat3 clearcoatRoughnessMapTransform;
|
|
460
|
+
mat3 sheenColorMapTransform;
|
|
461
|
+
mat3 sheenRoughnessMapTransform;
|
|
462
|
+
mat3 iridescenceMapTransform;
|
|
463
|
+
mat3 iridescenceThicknessMapTransform;
|
|
464
|
+
mat3 specularColorMapTransform;
|
|
465
|
+
mat3 specularIntensityMapTransform;
|
|
466
|
+
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
mat3 readTextureTransform( sampler2D tex, uint index ) {
|
|
470
|
+
|
|
471
|
+
mat3 textureTransform;
|
|
472
|
+
|
|
473
|
+
vec4 row1 = texelFetch1D( tex, index );
|
|
474
|
+
vec4 row2 = texelFetch1D( tex, index + 1u );
|
|
475
|
+
|
|
476
|
+
textureTransform[0] = vec3(row1.r, row2.r, 0.0);
|
|
477
|
+
textureTransform[1] = vec3(row1.g, row2.g, 0.0);
|
|
478
|
+
textureTransform[2] = vec3(row1.b, row2.b, 1.0);
|
|
479
|
+
|
|
480
|
+
return textureTransform;
|
|
481
|
+
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
Material readMaterialInfo( sampler2D tex, uint index ) {
|
|
485
|
+
|
|
486
|
+
uint i = index * 45u;
|
|
487
|
+
|
|
488
|
+
vec4 s0 = texelFetch1D( tex, i + 0u );
|
|
489
|
+
vec4 s1 = texelFetch1D( tex, i + 1u );
|
|
490
|
+
vec4 s2 = texelFetch1D( tex, i + 2u );
|
|
491
|
+
vec4 s3 = texelFetch1D( tex, i + 3u );
|
|
492
|
+
vec4 s4 = texelFetch1D( tex, i + 4u );
|
|
493
|
+
vec4 s5 = texelFetch1D( tex, i + 5u );
|
|
494
|
+
vec4 s6 = texelFetch1D( tex, i + 6u );
|
|
495
|
+
vec4 s7 = texelFetch1D( tex, i + 7u );
|
|
496
|
+
vec4 s8 = texelFetch1D( tex, i + 8u );
|
|
497
|
+
vec4 s9 = texelFetch1D( tex, i + 9u );
|
|
498
|
+
vec4 s10 = texelFetch1D( tex, i + 10u );
|
|
499
|
+
vec4 s11 = texelFetch1D( tex, i + 11u );
|
|
500
|
+
vec4 s12 = texelFetch1D( tex, i + 12u );
|
|
501
|
+
vec4 s13 = texelFetch1D( tex, i + 13u );
|
|
502
|
+
vec4 s14 = texelFetch1D( tex, i + 14u );
|
|
503
|
+
|
|
504
|
+
Material m;
|
|
505
|
+
m.color = s0.rgb;
|
|
506
|
+
m.map = int( round( s0.a ) );
|
|
507
|
+
|
|
508
|
+
m.metalness = s1.r;
|
|
509
|
+
m.metalnessMap = int( round( s1.g ) );
|
|
510
|
+
m.roughness = s1.b;
|
|
511
|
+
m.roughnessMap = int( round( s1.a ) );
|
|
512
|
+
|
|
513
|
+
m.ior = s2.r;
|
|
514
|
+
m.transmission = s2.g;
|
|
515
|
+
m.transmissionMap = int( round( s2.b ) );
|
|
516
|
+
m.emissiveIntensity = s2.a;
|
|
517
|
+
|
|
518
|
+
m.emissive = s3.rgb;
|
|
519
|
+
m.emissiveMap = int( round( s3.a ) );
|
|
520
|
+
|
|
521
|
+
m.normalMap = int( round( s4.r ) );
|
|
522
|
+
m.normalScale = s4.gb;
|
|
523
|
+
|
|
524
|
+
m.clearcoat = s4.a;
|
|
525
|
+
m.clearcoatMap = int( round( s5.r ) );
|
|
526
|
+
m.clearcoatRoughness = s5.g;
|
|
527
|
+
m.clearcoatRoughnessMap = int( round( s5.b ) );
|
|
528
|
+
m.clearcoatNormalMap = int( round( s5.a ) );
|
|
529
|
+
m.clearcoatNormalScale = s6.rg;
|
|
530
|
+
|
|
531
|
+
m.sheen = s6.a;
|
|
532
|
+
m.sheenColor = s7.rgb;
|
|
533
|
+
m.sheenColorMap = int( round( s7.a ) );
|
|
534
|
+
m.sheenRoughness = s8.r;
|
|
535
|
+
m.sheenRoughnessMap = int( round( s8.g ) );
|
|
536
|
+
|
|
537
|
+
m.iridescenceMap = int( round( s8.b ) );
|
|
538
|
+
m.iridescenceThicknessMap = int( round( s8.a ) );
|
|
539
|
+
m.iridescence = s9.r;
|
|
540
|
+
m.iridescenceIor = s9.g;
|
|
541
|
+
m.iridescenceThicknessMinimum = s9.b;
|
|
542
|
+
m.iridescenceThicknessMaximum = s9.a;
|
|
543
|
+
|
|
544
|
+
m.specularColor = s10.rgb;
|
|
545
|
+
m.specularColorMap = int( round( s10.a ) );
|
|
546
|
+
|
|
547
|
+
m.specularIntensity = s11.r;
|
|
548
|
+
m.specularIntensityMap = int( round( s11.g ) );
|
|
549
|
+
m.thinFilm = bool( s11.b );
|
|
550
|
+
|
|
551
|
+
m.attenuationColor = s12.rgb;
|
|
552
|
+
m.attenuationDistance = s12.a;
|
|
553
|
+
|
|
554
|
+
m.alphaMap = int( round( s13.r ) );
|
|
555
|
+
|
|
556
|
+
m.opacity = s13.g;
|
|
557
|
+
m.alphaTest = s13.b;
|
|
558
|
+
m.side = s13.a;
|
|
559
|
+
|
|
560
|
+
m.matte = bool( s14.r );
|
|
561
|
+
m.castShadow = bool( s14.g );
|
|
562
|
+
m.vertexColors = bool( int( s14.b ) & 1 );
|
|
563
|
+
m.flatShading = bool( int( s14.b ) & 2 );
|
|
564
|
+
m.fogVolume = bool( int( s14.b ) & 4 );
|
|
565
|
+
m.transparent = bool( s14.a );
|
|
566
|
+
|
|
567
|
+
uint firstTextureTransformIdx = i + 15u;
|
|
568
|
+
|
|
569
|
+
// mat3( 1.0 ) is an identity matrix
|
|
570
|
+
m.mapTransform = m.map == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx );
|
|
571
|
+
m.metalnessMapTransform = m.metalnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 2u );
|
|
572
|
+
m.roughnessMapTransform = m.roughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 4u );
|
|
573
|
+
m.transmissionMapTransform = m.transmissionMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 6u );
|
|
574
|
+
m.emissiveMapTransform = m.emissiveMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 8u );
|
|
575
|
+
m.normalMapTransform = m.normalMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 10u );
|
|
576
|
+
m.clearcoatMapTransform = m.clearcoatMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 12u );
|
|
577
|
+
m.clearcoatNormalMapTransform = m.clearcoatNormalMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 14u );
|
|
578
|
+
m.clearcoatRoughnessMapTransform = m.clearcoatRoughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 16u );
|
|
579
|
+
m.sheenColorMapTransform = m.sheenColorMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 18u );
|
|
580
|
+
m.sheenRoughnessMapTransform = m.sheenRoughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 20u );
|
|
581
|
+
m.iridescenceMapTransform = m.iridescenceMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 22u );
|
|
582
|
+
m.iridescenceThicknessMapTransform = m.iridescenceThicknessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 24u );
|
|
583
|
+
m.specularColorMapTransform = m.specularColorMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 26u );
|
|
584
|
+
m.specularIntensityMapTransform = m.specularIntensityMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 28u );
|
|
585
|
+
|
|
586
|
+
return m;
|
|
587
|
+
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
`,zn=`
|
|
591
|
+
|
|
592
|
+
struct SurfaceRecord {
|
|
593
|
+
|
|
594
|
+
// surface type
|
|
595
|
+
bool volumeParticle;
|
|
596
|
+
|
|
597
|
+
// geometry
|
|
598
|
+
vec3 faceNormal;
|
|
599
|
+
bool frontFace;
|
|
600
|
+
vec3 normal;
|
|
601
|
+
mat3 normalBasis;
|
|
602
|
+
mat3 normalInvBasis;
|
|
603
|
+
|
|
604
|
+
// cached properties
|
|
605
|
+
float eta;
|
|
606
|
+
float f0;
|
|
607
|
+
|
|
608
|
+
// material
|
|
609
|
+
float roughness;
|
|
610
|
+
float filteredRoughness;
|
|
611
|
+
float metalness;
|
|
612
|
+
vec3 color;
|
|
613
|
+
vec3 emission;
|
|
614
|
+
|
|
615
|
+
// transmission
|
|
616
|
+
float ior;
|
|
617
|
+
float transmission;
|
|
618
|
+
bool thinFilm;
|
|
619
|
+
vec3 attenuationColor;
|
|
620
|
+
float attenuationDistance;
|
|
621
|
+
|
|
622
|
+
// clearcoat
|
|
623
|
+
vec3 clearcoatNormal;
|
|
624
|
+
mat3 clearcoatBasis;
|
|
625
|
+
mat3 clearcoatInvBasis;
|
|
626
|
+
float clearcoat;
|
|
627
|
+
float clearcoatRoughness;
|
|
628
|
+
float filteredClearcoatRoughness;
|
|
629
|
+
|
|
630
|
+
// sheen
|
|
631
|
+
float sheen;
|
|
632
|
+
vec3 sheenColor;
|
|
633
|
+
float sheenRoughness;
|
|
634
|
+
|
|
635
|
+
// iridescence
|
|
636
|
+
float iridescence;
|
|
637
|
+
float iridescenceIor;
|
|
638
|
+
float iridescenceThickness;
|
|
639
|
+
|
|
640
|
+
// specular
|
|
641
|
+
vec3 specularColor;
|
|
642
|
+
float specularIntensity;
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
struct ScatterRecord {
|
|
646
|
+
float specularPdf;
|
|
647
|
+
float pdf;
|
|
648
|
+
vec3 direction;
|
|
649
|
+
vec3 color;
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
`,Vn=`
|
|
653
|
+
|
|
654
|
+
// samples the the given environment map in the given direction
|
|
655
|
+
vec3 sampleEquirectColor( sampler2D envMap, vec3 direction ) {
|
|
656
|
+
|
|
657
|
+
return texture2D( envMap, equirectDirectionToUv( direction ) ).rgb;
|
|
658
|
+
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// gets the pdf of the given direction to sample
|
|
662
|
+
float equirectDirectionPdf( vec3 direction ) {
|
|
663
|
+
|
|
664
|
+
vec2 uv = equirectDirectionToUv( direction );
|
|
665
|
+
float theta = uv.y * PI;
|
|
666
|
+
float sinTheta = sin( theta );
|
|
667
|
+
if ( sinTheta == 0.0 ) {
|
|
668
|
+
|
|
669
|
+
return 0.0;
|
|
670
|
+
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
return 1.0 / ( 2.0 * PI * PI * sinTheta );
|
|
674
|
+
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// samples the color given env map with CDF and returns the pdf of the direction
|
|
678
|
+
float sampleEquirect( vec3 direction, inout vec3 color ) {
|
|
679
|
+
|
|
680
|
+
float totalSum = envMapInfo.totalSum;
|
|
681
|
+
if ( totalSum == 0.0 ) {
|
|
682
|
+
|
|
683
|
+
color = vec3( 0.0 );
|
|
684
|
+
return 1.0;
|
|
685
|
+
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
vec2 uv = equirectDirectionToUv( direction );
|
|
689
|
+
color = texture2D( envMapInfo.map, uv ).rgb;
|
|
690
|
+
|
|
691
|
+
float lum = luminance( color );
|
|
692
|
+
ivec2 resolution = textureSize( envMapInfo.map, 0 );
|
|
693
|
+
float pdf = lum / totalSum;
|
|
694
|
+
|
|
695
|
+
return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
|
|
696
|
+
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// samples a direction of the envmap with color and retrieves pdf
|
|
700
|
+
float sampleEquirectProbability( vec2 r, inout vec3 color, inout vec3 direction ) {
|
|
701
|
+
|
|
702
|
+
// sample env map cdf
|
|
703
|
+
float v = texture2D( envMapInfo.marginalWeights, vec2( r.x, 0.0 ) ).x;
|
|
704
|
+
float u = texture2D( envMapInfo.conditionalWeights, vec2( r.y, v ) ).x;
|
|
705
|
+
vec2 uv = vec2( u, v );
|
|
706
|
+
|
|
707
|
+
vec3 derivedDirection = equirectUvToDirection( uv );
|
|
708
|
+
direction = derivedDirection;
|
|
709
|
+
color = texture2D( envMapInfo.map, uv ).rgb;
|
|
710
|
+
|
|
711
|
+
float totalSum = envMapInfo.totalSum;
|
|
712
|
+
float lum = luminance( color );
|
|
713
|
+
ivec2 resolution = textureSize( envMapInfo.map, 0 );
|
|
714
|
+
float pdf = lum / totalSum;
|
|
715
|
+
|
|
716
|
+
return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
|
|
717
|
+
|
|
718
|
+
}
|
|
719
|
+
`,Un=`
|
|
720
|
+
|
|
721
|
+
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
|
|
722
|
+
|
|
723
|
+
return smoothstep( coneCosine, penumbraCosine, angleCosine );
|
|
724
|
+
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
|
|
728
|
+
|
|
729
|
+
// based upon Frostbite 3 Moving to Physically-based Rendering
|
|
730
|
+
// page 32, equation 26: E[window1]
|
|
731
|
+
// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
|
|
732
|
+
float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), EPSILON );
|
|
733
|
+
|
|
734
|
+
if ( cutoffDistance > 0.0 ) {
|
|
735
|
+
|
|
736
|
+
distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
|
|
737
|
+
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
return distanceFalloff;
|
|
741
|
+
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
float getPhotometricAttenuation( sampler2DArray iesProfiles, int iesProfile, vec3 posToLight, vec3 lightDir, vec3 u, vec3 v ) {
|
|
745
|
+
|
|
746
|
+
float cosTheta = dot( posToLight, lightDir );
|
|
747
|
+
float angle = acos( cosTheta ) / PI;
|
|
748
|
+
|
|
749
|
+
return texture2D( iesProfiles, vec3( angle, 0.0, iesProfile ) ).r;
|
|
750
|
+
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
struct LightRecord {
|
|
754
|
+
|
|
755
|
+
float dist;
|
|
756
|
+
vec3 direction;
|
|
757
|
+
float pdf;
|
|
758
|
+
vec3 emission;
|
|
759
|
+
int type;
|
|
760
|
+
|
|
761
|
+
};
|
|
762
|
+
|
|
763
|
+
bool intersectLightAtIndex( sampler2D lights, vec3 rayOrigin, vec3 rayDirection, uint l, inout LightRecord lightRec ) {
|
|
764
|
+
|
|
765
|
+
bool didHit = false;
|
|
766
|
+
Light light = readLightInfo( lights, l );
|
|
767
|
+
|
|
768
|
+
vec3 u = light.u;
|
|
769
|
+
vec3 v = light.v;
|
|
770
|
+
|
|
771
|
+
// check for backface
|
|
772
|
+
vec3 normal = normalize( cross( u, v ) );
|
|
773
|
+
if ( dot( normal, rayDirection ) > 0.0 ) {
|
|
774
|
+
|
|
775
|
+
u *= 1.0 / dot( u, u );
|
|
776
|
+
v *= 1.0 / dot( v, v );
|
|
777
|
+
|
|
778
|
+
float dist;
|
|
779
|
+
|
|
780
|
+
// MIS / light intersection is not supported for punctual lights.
|
|
781
|
+
if(
|
|
782
|
+
( light.type == RECT_AREA_LIGHT_TYPE && intersectsRectangle( light.position, normal, u, v, rayOrigin, rayDirection, dist ) ) ||
|
|
783
|
+
( light.type == CIRC_AREA_LIGHT_TYPE && intersectsCircle( light.position, normal, u, v, rayOrigin, rayDirection, dist ) )
|
|
784
|
+
) {
|
|
785
|
+
|
|
786
|
+
float cosTheta = dot( rayDirection, normal );
|
|
787
|
+
didHit = true;
|
|
788
|
+
lightRec.dist = dist;
|
|
789
|
+
lightRec.pdf = ( dist * dist ) / ( light.area * cosTheta );
|
|
790
|
+
lightRec.emission = light.color * light.intensity;
|
|
791
|
+
lightRec.direction = rayDirection;
|
|
792
|
+
lightRec.type = light.type;
|
|
793
|
+
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
return didHit;
|
|
799
|
+
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
LightRecord randomAreaLightSample( Light light, vec3 rayOrigin, vec2 ruv ) {
|
|
803
|
+
|
|
804
|
+
vec3 randomPos;
|
|
805
|
+
if( light.type == RECT_AREA_LIGHT_TYPE ) {
|
|
806
|
+
|
|
807
|
+
// rectangular area light
|
|
808
|
+
randomPos = light.position + light.u * ( ruv.x - 0.5 ) + light.v * ( ruv.y - 0.5 );
|
|
809
|
+
|
|
810
|
+
} else if( light.type == CIRC_AREA_LIGHT_TYPE ) {
|
|
811
|
+
|
|
812
|
+
// circular area light
|
|
813
|
+
float r = 0.5 * sqrt( ruv.x );
|
|
814
|
+
float theta = ruv.y * 2.0 * PI;
|
|
815
|
+
float x = r * cos( theta );
|
|
816
|
+
float y = r * sin( theta );
|
|
817
|
+
|
|
818
|
+
randomPos = light.position + light.u * x + light.v * y;
|
|
819
|
+
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
vec3 toLight = randomPos - rayOrigin;
|
|
823
|
+
float lightDistSq = dot( toLight, toLight );
|
|
824
|
+
float dist = sqrt( lightDistSq );
|
|
825
|
+
vec3 direction = toLight / dist;
|
|
826
|
+
vec3 lightNormal = normalize( cross( light.u, light.v ) );
|
|
827
|
+
|
|
828
|
+
LightRecord lightRec;
|
|
829
|
+
lightRec.type = light.type;
|
|
830
|
+
lightRec.emission = light.color * light.intensity;
|
|
831
|
+
lightRec.dist = dist;
|
|
832
|
+
lightRec.direction = direction;
|
|
833
|
+
|
|
834
|
+
// TODO: the denominator is potentially zero
|
|
835
|
+
lightRec.pdf = lightDistSq / ( light.area * dot( direction, lightNormal ) );
|
|
836
|
+
|
|
837
|
+
return lightRec;
|
|
838
|
+
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
LightRecord randomSpotLightSample( Light light, sampler2DArray iesProfiles, vec3 rayOrigin, vec2 ruv ) {
|
|
842
|
+
|
|
843
|
+
float radius = light.radius * sqrt( ruv.x );
|
|
844
|
+
float theta = ruv.y * 2.0 * PI;
|
|
845
|
+
float x = radius * cos( theta );
|
|
846
|
+
float y = radius * sin( theta );
|
|
847
|
+
|
|
848
|
+
vec3 u = light.u;
|
|
849
|
+
vec3 v = light.v;
|
|
850
|
+
vec3 normal = normalize( cross( u, v ) );
|
|
851
|
+
|
|
852
|
+
float angle = acos( light.coneCos );
|
|
853
|
+
float angleTan = tan( angle );
|
|
854
|
+
float startDistance = light.radius / max( angleTan, EPSILON );
|
|
855
|
+
|
|
856
|
+
vec3 randomPos = light.position - normal * startDistance + u * x + v * y;
|
|
857
|
+
vec3 toLight = randomPos - rayOrigin;
|
|
858
|
+
float lightDistSq = dot( toLight, toLight );
|
|
859
|
+
float dist = sqrt( lightDistSq );
|
|
860
|
+
|
|
861
|
+
vec3 direction = toLight / max( dist, EPSILON );
|
|
862
|
+
float cosTheta = dot( direction, normal );
|
|
863
|
+
|
|
864
|
+
float spotAttenuation = light.iesProfile != - 1 ?
|
|
865
|
+
getPhotometricAttenuation( iesProfiles, light.iesProfile, direction, normal, u, v ) :
|
|
866
|
+
getSpotAttenuation( light.coneCos, light.penumbraCos, cosTheta );
|
|
867
|
+
|
|
868
|
+
float distanceAttenuation = getDistanceAttenuation( dist, light.distance, light.decay );
|
|
869
|
+
LightRecord lightRec;
|
|
870
|
+
lightRec.type = light.type;
|
|
871
|
+
lightRec.dist = dist;
|
|
872
|
+
lightRec.direction = direction;
|
|
873
|
+
lightRec.emission = light.color * light.intensity * distanceAttenuation * spotAttenuation;
|
|
874
|
+
lightRec.pdf = 1.0;
|
|
875
|
+
|
|
876
|
+
return lightRec;
|
|
877
|
+
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
LightRecord randomLightSample( sampler2D lights, sampler2DArray iesProfiles, uint lightCount, vec3 rayOrigin, vec3 ruv ) {
|
|
881
|
+
|
|
882
|
+
LightRecord result;
|
|
883
|
+
|
|
884
|
+
// pick a random light
|
|
885
|
+
uint l = uint( ruv.x * float( lightCount ) );
|
|
886
|
+
Light light = readLightInfo( lights, l );
|
|
887
|
+
|
|
888
|
+
if ( light.type == SPOT_LIGHT_TYPE ) {
|
|
889
|
+
|
|
890
|
+
result = randomSpotLightSample( light, iesProfiles, rayOrigin, ruv.yz );
|
|
891
|
+
|
|
892
|
+
} else if ( light.type == POINT_LIGHT_TYPE ) {
|
|
893
|
+
|
|
894
|
+
vec3 lightRay = light.u - rayOrigin;
|
|
895
|
+
float lightDist = length( lightRay );
|
|
896
|
+
float cutoffDistance = light.distance;
|
|
897
|
+
float distanceFalloff = 1.0 / max( pow( lightDist, light.decay ), 0.01 );
|
|
898
|
+
if ( cutoffDistance > 0.0 ) {
|
|
899
|
+
|
|
900
|
+
distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDist / cutoffDistance ) ) );
|
|
901
|
+
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
LightRecord rec;
|
|
905
|
+
rec.direction = normalize( lightRay );
|
|
906
|
+
rec.dist = length( lightRay );
|
|
907
|
+
rec.pdf = 1.0;
|
|
908
|
+
rec.emission = light.color * light.intensity * distanceFalloff;
|
|
909
|
+
rec.type = light.type;
|
|
910
|
+
result = rec;
|
|
911
|
+
|
|
912
|
+
} else if ( light.type == DIR_LIGHT_TYPE ) {
|
|
913
|
+
|
|
914
|
+
LightRecord rec;
|
|
915
|
+
rec.dist = 1e10;
|
|
916
|
+
rec.direction = light.u;
|
|
917
|
+
rec.pdf = 1.0;
|
|
918
|
+
rec.emission = light.color * light.intensity;
|
|
919
|
+
rec.type = light.type;
|
|
920
|
+
|
|
921
|
+
result = rec;
|
|
922
|
+
|
|
923
|
+
} else {
|
|
924
|
+
|
|
925
|
+
// sample the light
|
|
926
|
+
result = randomAreaLightSample( light, rayOrigin, ruv.yz );
|
|
927
|
+
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
return result;
|
|
931
|
+
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
`,Hn=`
|
|
935
|
+
|
|
936
|
+
vec3 sampleHemisphere( vec3 n, vec2 uv ) {
|
|
937
|
+
|
|
938
|
+
// https://www.rorydriscoll.com/2009/01/07/better-sampling/
|
|
939
|
+
// https://graphics.pixar.com/library/OrthonormalB/paper.pdf
|
|
940
|
+
float sign = n.z == 0.0 ? 1.0 : sign( n.z );
|
|
941
|
+
float a = - 1.0 / ( sign + n.z );
|
|
942
|
+
float b = n.x * n.y * a;
|
|
943
|
+
vec3 b1 = vec3( 1.0 + sign * n.x * n.x * a, sign * b, - sign * n.x );
|
|
944
|
+
vec3 b2 = vec3( b, sign + n.y * n.y * a, - n.y );
|
|
945
|
+
|
|
946
|
+
float r = sqrt( uv.x );
|
|
947
|
+
float theta = 2.0 * PI * uv.y;
|
|
948
|
+
float x = r * cos( theta );
|
|
949
|
+
float y = r * sin( theta );
|
|
950
|
+
return x * b1 + y * b2 + sqrt( 1.0 - uv.x ) * n;
|
|
951
|
+
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
vec2 sampleTriangle( vec2 a, vec2 b, vec2 c, vec2 r ) {
|
|
955
|
+
|
|
956
|
+
// get the edges of the triangle and the diagonal across the
|
|
957
|
+
// center of the parallelogram
|
|
958
|
+
vec2 e1 = a - b;
|
|
959
|
+
vec2 e2 = c - b;
|
|
960
|
+
vec2 diag = normalize( e1 + e2 );
|
|
961
|
+
|
|
962
|
+
// pick the point in the parallelogram
|
|
963
|
+
if ( r.x + r.y > 1.0 ) {
|
|
964
|
+
|
|
965
|
+
r = vec2( 1.0 ) - r;
|
|
966
|
+
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
return e1 * r.x + e2 * r.y;
|
|
970
|
+
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
vec2 sampleCircle( vec2 uv ) {
|
|
974
|
+
|
|
975
|
+
float angle = 2.0 * PI * uv.x;
|
|
976
|
+
float radius = sqrt( uv.y );
|
|
977
|
+
return vec2( cos( angle ), sin( angle ) ) * radius;
|
|
978
|
+
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
vec3 sampleSphere( vec2 uv ) {
|
|
982
|
+
|
|
983
|
+
float u = ( uv.x - 0.5 ) * 2.0;
|
|
984
|
+
float t = uv.y * PI * 2.0;
|
|
985
|
+
float f = sqrt( 1.0 - u * u );
|
|
986
|
+
|
|
987
|
+
return vec3( f * cos( t ), f * sin( t ), u );
|
|
988
|
+
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
vec2 sampleRegularPolygon( int sides, vec3 uvw ) {
|
|
992
|
+
|
|
993
|
+
sides = max( sides, 3 );
|
|
994
|
+
|
|
995
|
+
vec3 r = uvw;
|
|
996
|
+
float anglePerSegment = 2.0 * PI / float( sides );
|
|
997
|
+
float segment = floor( float( sides ) * r.x );
|
|
998
|
+
|
|
999
|
+
float angle1 = anglePerSegment * segment;
|
|
1000
|
+
float angle2 = angle1 + anglePerSegment;
|
|
1001
|
+
vec2 a = vec2( sin( angle1 ), cos( angle1 ) );
|
|
1002
|
+
vec2 b = vec2( 0.0, 0.0 );
|
|
1003
|
+
vec2 c = vec2( sin( angle2 ), cos( angle2 ) );
|
|
1004
|
+
|
|
1005
|
+
return sampleTriangle( a, b, c, r.yz );
|
|
1006
|
+
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// samples an aperture shape with the given number of sides. 0 means circle
|
|
1010
|
+
vec2 sampleAperture( int blades, vec3 uvw ) {
|
|
1011
|
+
|
|
1012
|
+
return blades == 0 ?
|
|
1013
|
+
sampleCircle( uvw.xy ) :
|
|
1014
|
+
sampleRegularPolygon( blades, uvw );
|
|
1015
|
+
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
|
|
1019
|
+
`,Nn=`
|
|
1020
|
+
|
|
1021
|
+
bool totalInternalReflection( float cosTheta, float eta ) {
|
|
1022
|
+
|
|
1023
|
+
float sinTheta = sqrt( 1.0 - cosTheta * cosTheta );
|
|
1024
|
+
return eta * sinTheta > 1.0;
|
|
1025
|
+
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
// https://google.github.io/filament/Filament.md.html#materialsystem/diffusebrdf
|
|
1029
|
+
float schlickFresnel( float cosine, float f0 ) {
|
|
1030
|
+
|
|
1031
|
+
return f0 + ( 1.0 - f0 ) * pow( 1.0 - cosine, 5.0 );
|
|
1032
|
+
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
vec3 schlickFresnel( float cosine, vec3 f0 ) {
|
|
1036
|
+
|
|
1037
|
+
return f0 + ( 1.0 - f0 ) * pow( 1.0 - cosine, 5.0 );
|
|
1038
|
+
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
vec3 schlickFresnel( float cosine, vec3 f0, vec3 f90 ) {
|
|
1042
|
+
|
|
1043
|
+
return f0 + ( f90 - f0 ) * pow( 1.0 - cosine, 5.0 );
|
|
1044
|
+
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
float dielectricFresnel( float cosThetaI, float eta ) {
|
|
1048
|
+
|
|
1049
|
+
// https://schuttejoe.github.io/post/disneybsdf/
|
|
1050
|
+
float ni = eta;
|
|
1051
|
+
float nt = 1.0;
|
|
1052
|
+
|
|
1053
|
+
// Check for total internal reflection
|
|
1054
|
+
float sinThetaISq = 1.0f - cosThetaI * cosThetaI;
|
|
1055
|
+
float sinThetaTSq = eta * eta * sinThetaISq;
|
|
1056
|
+
if( sinThetaTSq >= 1.0 ) {
|
|
1057
|
+
|
|
1058
|
+
return 1.0;
|
|
1059
|
+
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
float sinThetaT = sqrt( sinThetaTSq );
|
|
1063
|
+
|
|
1064
|
+
float cosThetaT = sqrt( max( 0.0, 1.0f - sinThetaT * sinThetaT ) );
|
|
1065
|
+
float rParallel = ( ( nt * cosThetaI ) - ( ni * cosThetaT ) ) / ( ( nt * cosThetaI ) + ( ni * cosThetaT ) );
|
|
1066
|
+
float rPerpendicular = ( ( ni * cosThetaI ) - ( nt * cosThetaT ) ) / ( ( ni * cosThetaI ) + ( nt * cosThetaT ) );
|
|
1067
|
+
return ( rParallel * rParallel + rPerpendicular * rPerpendicular ) / 2.0;
|
|
1068
|
+
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// https://raytracing.github.io/books/RayTracingInOneWeekend.html#dielectrics/schlickapproximation
|
|
1072
|
+
float iorRatioToF0( float eta ) {
|
|
1073
|
+
|
|
1074
|
+
return pow( ( 1.0 - eta ) / ( 1.0 + eta ), 2.0 );
|
|
1075
|
+
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
vec3 evaluateFresnel( float cosTheta, float eta, vec3 f0, vec3 f90 ) {
|
|
1079
|
+
|
|
1080
|
+
if ( totalInternalReflection( cosTheta, eta ) ) {
|
|
1081
|
+
|
|
1082
|
+
return f90;
|
|
1083
|
+
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
return schlickFresnel( cosTheta, f0, f90 );
|
|
1087
|
+
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
// TODO: disney fresnel was removed and replaced with this fresnel function to better align with
|
|
1091
|
+
// the glTF but is causing blown out pixels. Should be revisited
|
|
1092
|
+
// float evaluateFresnelWeight( float cosTheta, float eta, float f0 ) {
|
|
1093
|
+
|
|
1094
|
+
// if ( totalInternalReflection( cosTheta, eta ) ) {
|
|
1095
|
+
|
|
1096
|
+
// return 1.0;
|
|
1097
|
+
|
|
1098
|
+
// }
|
|
1099
|
+
|
|
1100
|
+
// return schlickFresnel( cosTheta, f0 );
|
|
1101
|
+
|
|
1102
|
+
// }
|
|
1103
|
+
|
|
1104
|
+
// https://schuttejoe.github.io/post/disneybsdf/
|
|
1105
|
+
float disneyFresnel( vec3 wo, vec3 wi, vec3 wh, float f0, float eta, float metalness ) {
|
|
1106
|
+
|
|
1107
|
+
float dotHV = dot( wo, wh );
|
|
1108
|
+
if ( totalInternalReflection( dotHV, eta ) ) {
|
|
1109
|
+
|
|
1110
|
+
return 1.0;
|
|
1111
|
+
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
float dotHL = dot( wi, wh );
|
|
1115
|
+
float dielectricFresnel = dielectricFresnel( abs( dotHV ), eta );
|
|
1116
|
+
float metallicFresnel = schlickFresnel( dotHL, f0 );
|
|
1117
|
+
|
|
1118
|
+
return mix( dielectricFresnel, metallicFresnel, metalness );
|
|
1119
|
+
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
`,Wn=`
|
|
1123
|
+
|
|
1124
|
+
// Fast arccos approximation used to remove banding artifacts caused by numerical errors in acos.
|
|
1125
|
+
// This is a cubic Lagrange interpolating polynomial for x = [-1, -1/2, 0, 1/2, 1].
|
|
1126
|
+
// For more information see: https://github.com/gkjohnson/three-gpu-pathtracer/pull/171#issuecomment-1152275248
|
|
1127
|
+
float acosApprox( float x ) {
|
|
1128
|
+
|
|
1129
|
+
x = clamp( x, -1.0, 1.0 );
|
|
1130
|
+
return ( - 0.69813170079773212 * x * x - 0.87266462599716477 ) * x + 1.5707963267948966;
|
|
1131
|
+
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
// An acos with input values bound to the range [-1, 1].
|
|
1135
|
+
float acosSafe( float x ) {
|
|
1136
|
+
|
|
1137
|
+
return acos( clamp( x, -1.0, 1.0 ) );
|
|
1138
|
+
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
float saturateCos( float val ) {
|
|
1142
|
+
|
|
1143
|
+
return clamp( val, 0.001, 1.0 );
|
|
1144
|
+
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
float square( float t ) {
|
|
1148
|
+
|
|
1149
|
+
return t * t;
|
|
1150
|
+
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
vec2 square( vec2 t ) {
|
|
1154
|
+
|
|
1155
|
+
return t * t;
|
|
1156
|
+
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
vec3 square( vec3 t ) {
|
|
1160
|
+
|
|
1161
|
+
return t * t;
|
|
1162
|
+
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
vec4 square( vec4 t ) {
|
|
1166
|
+
|
|
1167
|
+
return t * t;
|
|
1168
|
+
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
vec2 rotateVector( vec2 v, float t ) {
|
|
1172
|
+
|
|
1173
|
+
float ac = cos( t );
|
|
1174
|
+
float as = sin( t );
|
|
1175
|
+
return vec2(
|
|
1176
|
+
v.x * ac - v.y * as,
|
|
1177
|
+
v.x * as + v.y * ac
|
|
1178
|
+
);
|
|
1179
|
+
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// forms a basis with the normal vector as Z
|
|
1183
|
+
mat3 getBasisFromNormal( vec3 normal ) {
|
|
1184
|
+
|
|
1185
|
+
vec3 other;
|
|
1186
|
+
if ( abs( normal.x ) > 0.5 ) {
|
|
1187
|
+
|
|
1188
|
+
other = vec3( 0.0, 1.0, 0.0 );
|
|
1189
|
+
|
|
1190
|
+
} else {
|
|
1191
|
+
|
|
1192
|
+
other = vec3( 1.0, 0.0, 0.0 );
|
|
1193
|
+
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
vec3 ortho = normalize( cross( normal, other ) );
|
|
1197
|
+
vec3 ortho2 = normalize( cross( normal, ortho ) );
|
|
1198
|
+
return mat3( ortho2, ortho, normal );
|
|
1199
|
+
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
`,Gn=`
|
|
1203
|
+
|
|
1204
|
+
// Finds the point where the ray intersects the plane defined by u and v and checks if this point
|
|
1205
|
+
// falls in the bounds of the rectangle on that same plane.
|
|
1206
|
+
// Plane intersection: https://lousodrome.net/blog/light/2020/07/03/intersection-of-a-ray-and-a-plane/
|
|
1207
|
+
bool intersectsRectangle( vec3 center, vec3 normal, vec3 u, vec3 v, vec3 rayOrigin, vec3 rayDirection, inout float dist ) {
|
|
1208
|
+
|
|
1209
|
+
float t = dot( center - rayOrigin, normal ) / dot( rayDirection, normal );
|
|
1210
|
+
|
|
1211
|
+
if ( t > EPSILON ) {
|
|
1212
|
+
|
|
1213
|
+
vec3 p = rayOrigin + rayDirection * t;
|
|
1214
|
+
vec3 vi = p - center;
|
|
1215
|
+
|
|
1216
|
+
// check if p falls inside the rectangle
|
|
1217
|
+
float a1 = dot( u, vi );
|
|
1218
|
+
if ( abs( a1 ) <= 0.5 ) {
|
|
1219
|
+
|
|
1220
|
+
float a2 = dot( v, vi );
|
|
1221
|
+
if ( abs( a2 ) <= 0.5 ) {
|
|
1222
|
+
|
|
1223
|
+
dist = t;
|
|
1224
|
+
return true;
|
|
1225
|
+
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
return false;
|
|
1233
|
+
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// Finds the point where the ray intersects the plane defined by u and v and checks if this point
|
|
1237
|
+
// falls in the bounds of the circle on that same plane. See above URL for a description of the plane intersection algorithm.
|
|
1238
|
+
bool intersectsCircle( vec3 position, vec3 normal, vec3 u, vec3 v, vec3 rayOrigin, vec3 rayDirection, inout float dist ) {
|
|
1239
|
+
|
|
1240
|
+
float t = dot( position - rayOrigin, normal ) / dot( rayDirection, normal );
|
|
1241
|
+
|
|
1242
|
+
if ( t > EPSILON ) {
|
|
1243
|
+
|
|
1244
|
+
vec3 hit = rayOrigin + rayDirection * t;
|
|
1245
|
+
vec3 vi = hit - position;
|
|
1246
|
+
|
|
1247
|
+
float a1 = dot( u, vi );
|
|
1248
|
+
float a2 = dot( v, vi );
|
|
1249
|
+
|
|
1250
|
+
if( length( vec2( a1, a2 ) ) <= 0.5 ) {
|
|
1251
|
+
|
|
1252
|
+
dist = t;
|
|
1253
|
+
return true;
|
|
1254
|
+
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
return false;
|
|
1260
|
+
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
`,jn=`
|
|
1264
|
+
|
|
1265
|
+
// add texel fetch functions for texture arrays
|
|
1266
|
+
vec4 texelFetch1D( sampler2DArray tex, int layer, uint index ) {
|
|
1267
|
+
|
|
1268
|
+
uint width = uint( textureSize( tex, 0 ).x );
|
|
1269
|
+
uvec2 uv;
|
|
1270
|
+
uv.x = index % width;
|
|
1271
|
+
uv.y = index / width;
|
|
1272
|
+
|
|
1273
|
+
return texelFetch( tex, ivec3( uv, layer ), 0 );
|
|
1274
|
+
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
vec4 textureSampleBarycoord( sampler2DArray tex, int layer, vec3 barycoord, uvec3 faceIndices ) {
|
|
1278
|
+
|
|
1279
|
+
return
|
|
1280
|
+
barycoord.x * texelFetch1D( tex, layer, faceIndices.x ) +
|
|
1281
|
+
barycoord.y * texelFetch1D( tex, layer, faceIndices.y ) +
|
|
1282
|
+
barycoord.z * texelFetch1D( tex, layer, faceIndices.z );
|
|
1283
|
+
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
`,Ws=`
|
|
1287
|
+
|
|
1288
|
+
// TODO: possibly this should be renamed something related to material or path tracing logic
|
|
1289
|
+
|
|
1290
|
+
#ifndef RAY_OFFSET
|
|
1291
|
+
#define RAY_OFFSET 1e-4
|
|
1292
|
+
#endif
|
|
1293
|
+
|
|
1294
|
+
// adjust the hit point by the surface normal by a factor of some offset and the
|
|
1295
|
+
// maximum component-wise value of the current point to accommodate floating point
|
|
1296
|
+
// error as values increase.
|
|
1297
|
+
vec3 stepRayOrigin( vec3 rayOrigin, vec3 rayDirection, vec3 offset, float dist ) {
|
|
1298
|
+
|
|
1299
|
+
vec3 point = rayOrigin + rayDirection * dist;
|
|
1300
|
+
vec3 absPoint = abs( point );
|
|
1301
|
+
float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
|
|
1302
|
+
return point + offset * ( maxPoint + 1.0 ) * RAY_OFFSET;
|
|
1303
|
+
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
// https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md#attenuation
|
|
1307
|
+
vec3 transmissionAttenuation( float dist, vec3 attColor, float attDist ) {
|
|
1308
|
+
|
|
1309
|
+
vec3 ot = - log( attColor ) / attDist;
|
|
1310
|
+
return exp( - ot * dist );
|
|
1311
|
+
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
vec3 getHalfVector( vec3 wi, vec3 wo, float eta ) {
|
|
1315
|
+
|
|
1316
|
+
// get the half vector - assuming if the light incident vector is on the other side
|
|
1317
|
+
// of the that it's transmissive.
|
|
1318
|
+
vec3 h;
|
|
1319
|
+
if ( wi.z > 0.0 ) {
|
|
1320
|
+
|
|
1321
|
+
h = normalize( wi + wo );
|
|
1322
|
+
|
|
1323
|
+
} else {
|
|
1324
|
+
|
|
1325
|
+
// Scale by the ior ratio to retrieve the appropriate half vector
|
|
1326
|
+
// From Section 2.2 on computing the transmission half vector:
|
|
1327
|
+
// https://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf
|
|
1328
|
+
h = normalize( wi + wo * eta );
|
|
1329
|
+
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
h *= sign( h.z );
|
|
1333
|
+
return h;
|
|
1334
|
+
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
vec3 getHalfVector( vec3 a, vec3 b ) {
|
|
1338
|
+
|
|
1339
|
+
return normalize( a + b );
|
|
1340
|
+
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// The discrepancy between interpolated surface normal and geometry normal can cause issues when a ray
|
|
1344
|
+
// is cast that is on the top side of the geometry normal plane but below the surface normal plane. If
|
|
1345
|
+
// we find a ray like that we ignore it to avoid artifacts.
|
|
1346
|
+
// This function returns if the direction is on the same side of both planes.
|
|
1347
|
+
bool isDirectionValid( vec3 direction, vec3 surfaceNormal, vec3 geometryNormal ) {
|
|
1348
|
+
|
|
1349
|
+
bool aboveSurfaceNormal = dot( direction, surfaceNormal ) > 0.0;
|
|
1350
|
+
bool aboveGeometryNormal = dot( direction, geometryNormal ) > 0.0;
|
|
1351
|
+
return aboveSurfaceNormal == aboveGeometryNormal;
|
|
1352
|
+
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
// ray sampling x and z are swapped to align with expected background view
|
|
1356
|
+
vec2 equirectDirectionToUv( vec3 direction ) {
|
|
1357
|
+
|
|
1358
|
+
// from Spherical.setFromCartesianCoords
|
|
1359
|
+
vec2 uv = vec2( atan( direction.z, direction.x ), acos( direction.y ) );
|
|
1360
|
+
uv /= vec2( 2.0 * PI, PI );
|
|
1361
|
+
|
|
1362
|
+
// apply adjustments to get values in range [0, 1] and y right side up
|
|
1363
|
+
uv.x += 0.5;
|
|
1364
|
+
uv.y = 1.0 - uv.y;
|
|
1365
|
+
return uv;
|
|
1366
|
+
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
vec3 equirectUvToDirection( vec2 uv ) {
|
|
1370
|
+
|
|
1371
|
+
// undo above adjustments
|
|
1372
|
+
uv.x -= 0.5;
|
|
1373
|
+
uv.y = 1.0 - uv.y;
|
|
1374
|
+
|
|
1375
|
+
// from Vector3.setFromSphericalCoords
|
|
1376
|
+
float theta = uv.x * 2.0 * PI;
|
|
1377
|
+
float phi = uv.y * PI;
|
|
1378
|
+
|
|
1379
|
+
float sinPhi = sin( phi );
|
|
1380
|
+
|
|
1381
|
+
return vec3( sinPhi * cos( theta ), cos( phi ), sinPhi * sin( theta ) );
|
|
1382
|
+
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
// power heuristic for multiple importance sampling
|
|
1386
|
+
float misHeuristic( float a, float b ) {
|
|
1387
|
+
|
|
1388
|
+
float aa = a * a;
|
|
1389
|
+
float bb = b * b;
|
|
1390
|
+
return aa / ( aa + bb );
|
|
1391
|
+
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
// tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
|
|
1395
|
+
// erichlof/THREE.js-PathTracing-Renderer/
|
|
1396
|
+
float tentFilter( float x ) {
|
|
1397
|
+
|
|
1398
|
+
return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
|
|
1399
|
+
|
|
1400
|
+
}
|
|
1401
|
+
`,ns=`
|
|
1402
|
+
|
|
1403
|
+
// https://www.shadertoy.com/view/wltcRS
|
|
1404
|
+
uvec4 WHITE_NOISE_SEED;
|
|
1405
|
+
|
|
1406
|
+
void rng_initialize( vec2 p, int frame ) {
|
|
1407
|
+
|
|
1408
|
+
// white noise seed
|
|
1409
|
+
WHITE_NOISE_SEED = uvec4( p, uint( frame ), uint( p.x ) + uint( p.y ) );
|
|
1410
|
+
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
// https://www.pcg-random.org/
|
|
1414
|
+
void pcg4d( inout uvec4 v ) {
|
|
1415
|
+
|
|
1416
|
+
v = v * 1664525u + 1013904223u;
|
|
1417
|
+
v.x += v.y * v.w;
|
|
1418
|
+
v.y += v.z * v.x;
|
|
1419
|
+
v.z += v.x * v.y;
|
|
1420
|
+
v.w += v.y * v.z;
|
|
1421
|
+
v = v ^ ( v >> 16u );
|
|
1422
|
+
v.x += v.y*v.w;
|
|
1423
|
+
v.y += v.z*v.x;
|
|
1424
|
+
v.z += v.x*v.y;
|
|
1425
|
+
v.w += v.y*v.z;
|
|
1426
|
+
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
// returns [ 0, 1 ]
|
|
1430
|
+
float pcgRand() {
|
|
1431
|
+
|
|
1432
|
+
pcg4d( WHITE_NOISE_SEED );
|
|
1433
|
+
return float( WHITE_NOISE_SEED.x ) / float( 0xffffffffu );
|
|
1434
|
+
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
vec2 pcgRand2() {
|
|
1438
|
+
|
|
1439
|
+
pcg4d( WHITE_NOISE_SEED );
|
|
1440
|
+
return vec2( WHITE_NOISE_SEED.xy ) / float(0xffffffffu);
|
|
1441
|
+
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
vec3 pcgRand3() {
|
|
1445
|
+
|
|
1446
|
+
pcg4d( WHITE_NOISE_SEED );
|
|
1447
|
+
return vec3( WHITE_NOISE_SEED.xyz ) / float( 0xffffffffu );
|
|
1448
|
+
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
vec4 pcgRand4() {
|
|
1452
|
+
|
|
1453
|
+
pcg4d( WHITE_NOISE_SEED );
|
|
1454
|
+
return vec4( WHITE_NOISE_SEED ) / float( 0xffffffffu );
|
|
1455
|
+
|
|
1456
|
+
}
|
|
1457
|
+
`,qn=`
|
|
1458
|
+
|
|
1459
|
+
uniform sampler2D stratifiedTexture;
|
|
1460
|
+
uniform sampler2D stratifiedOffsetTexture;
|
|
1461
|
+
|
|
1462
|
+
uint sobolPixelIndex = 0u;
|
|
1463
|
+
uint sobolPathIndex = 0u;
|
|
1464
|
+
uint sobolBounceIndex = 0u;
|
|
1465
|
+
vec4 pixelSeed = vec4( 0 );
|
|
1466
|
+
|
|
1467
|
+
vec4 rand4( int v ) {
|
|
1468
|
+
|
|
1469
|
+
ivec2 uv = ivec2( v, sobolBounceIndex );
|
|
1470
|
+
vec4 stratifiedSample = texelFetch( stratifiedTexture, uv, 0 );
|
|
1471
|
+
return fract( stratifiedSample + pixelSeed.r ); // blue noise + stratified samples
|
|
1472
|
+
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
vec3 rand3( int v ) {
|
|
1476
|
+
|
|
1477
|
+
return rand4( v ).xyz;
|
|
1478
|
+
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
vec2 rand2( int v ) {
|
|
1482
|
+
|
|
1483
|
+
return rand4( v ).xy;
|
|
1484
|
+
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
float rand( int v ) {
|
|
1488
|
+
|
|
1489
|
+
return rand4( v ).x;
|
|
1490
|
+
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
void rng_initialize( vec2 screenCoord, int frame ) {
|
|
1494
|
+
|
|
1495
|
+
// tile the small noise texture across the entire screen
|
|
1496
|
+
ivec2 noiseSize = ivec2( textureSize( stratifiedOffsetTexture, 0 ) );
|
|
1497
|
+
ivec2 pixel = ivec2( screenCoord.xy ) % noiseSize;
|
|
1498
|
+
vec2 pixelWidth = 1.0 / vec2( noiseSize );
|
|
1499
|
+
vec2 uv = vec2( pixel ) * pixelWidth + pixelWidth * 0.5;
|
|
1500
|
+
|
|
1501
|
+
// note that using "texelFetch" here seems to break Android for some reason
|
|
1502
|
+
pixelSeed = texture( stratifiedOffsetTexture, uv );
|
|
1503
|
+
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
`,Yn=`
|
|
1507
|
+
|
|
1508
|
+
// diffuse
|
|
1509
|
+
float diffuseEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
|
|
1510
|
+
|
|
1511
|
+
// https://schuttejoe.github.io/post/disneybsdf/
|
|
1512
|
+
float fl = schlickFresnel( wi.z, 0.0 );
|
|
1513
|
+
float fv = schlickFresnel( wo.z, 0.0 );
|
|
1514
|
+
|
|
1515
|
+
float metalFactor = ( 1.0 - surf.metalness );
|
|
1516
|
+
float transFactor = ( 1.0 - surf.transmission );
|
|
1517
|
+
float rr = 0.5 + 2.0 * surf.roughness * fl * fl;
|
|
1518
|
+
float retro = rr * ( fl + fv + fl * fv * ( rr - 1.0f ) );
|
|
1519
|
+
float lambert = ( 1.0f - 0.5f * fl ) * ( 1.0f - 0.5f * fv );
|
|
1520
|
+
|
|
1521
|
+
// TODO: subsurface approx?
|
|
1522
|
+
|
|
1523
|
+
// float F = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
|
|
1524
|
+
float F = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
|
|
1525
|
+
color = ( 1.0 - F ) * transFactor * metalFactor * wi.z * surf.color * ( retro + lambert ) / PI;
|
|
1526
|
+
|
|
1527
|
+
return wi.z / PI;
|
|
1528
|
+
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
vec3 diffuseDirection( vec3 wo, SurfaceRecord surf ) {
|
|
1532
|
+
|
|
1533
|
+
vec3 lightDirection = sampleSphere( rand2( 11 ) );
|
|
1534
|
+
lightDirection.z += 1.0;
|
|
1535
|
+
lightDirection = normalize( lightDirection );
|
|
1536
|
+
|
|
1537
|
+
return lightDirection;
|
|
1538
|
+
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
// specular
|
|
1542
|
+
float specularEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
|
|
1543
|
+
|
|
1544
|
+
// if roughness is set to 0 then D === NaN which results in black pixels
|
|
1545
|
+
float metalness = surf.metalness;
|
|
1546
|
+
float roughness = surf.filteredRoughness;
|
|
1547
|
+
|
|
1548
|
+
float eta = surf.eta;
|
|
1549
|
+
float f0 = surf.f0;
|
|
1550
|
+
|
|
1551
|
+
vec3 f0Color = mix( f0 * surf.specularColor * surf.specularIntensity, surf.color, surf.metalness );
|
|
1552
|
+
vec3 f90Color = vec3( mix( surf.specularIntensity, 1.0, surf.metalness ) );
|
|
1553
|
+
vec3 F = evaluateFresnel( dot( wo, wh ), eta, f0Color, f90Color );
|
|
1554
|
+
|
|
1555
|
+
vec3 iridescenceF = evalIridescence( 1.0, surf.iridescenceIor, dot( wi, wh ), surf.iridescenceThickness, f0Color );
|
|
1556
|
+
F = mix( F, iridescenceF, surf.iridescence );
|
|
1557
|
+
|
|
1558
|
+
// PDF
|
|
1559
|
+
// See 14.1.1 Microfacet BxDFs in https://www.pbr-book.org/
|
|
1560
|
+
float incidentTheta = acos( wo.z );
|
|
1561
|
+
float G = ggxShadowMaskG2( wi, wo, roughness );
|
|
1562
|
+
float D = ggxDistribution( wh, roughness );
|
|
1563
|
+
float G1 = ggxShadowMaskG1( incidentTheta, roughness );
|
|
1564
|
+
float ggxPdf = D * G1 * max( 0.0, abs( dot( wo, wh ) ) ) / abs ( wo.z );
|
|
1565
|
+
|
|
1566
|
+
color = wi.z * F * G * D / ( 4.0 * abs( wi.z * wo.z ) );
|
|
1567
|
+
return ggxPdf / ( 4.0 * dot( wo, wh ) );
|
|
1568
|
+
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
vec3 specularDirection( vec3 wo, SurfaceRecord surf ) {
|
|
1572
|
+
|
|
1573
|
+
// sample ggx vndf distribution which gives a new normal
|
|
1574
|
+
float roughness = surf.filteredRoughness;
|
|
1575
|
+
vec3 halfVector = ggxDirection(
|
|
1576
|
+
wo,
|
|
1577
|
+
vec2( roughness ),
|
|
1578
|
+
rand2( 12 )
|
|
1579
|
+
);
|
|
1580
|
+
|
|
1581
|
+
// apply to new ray by reflecting off the new normal
|
|
1582
|
+
return - reflect( wo, halfVector );
|
|
1583
|
+
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
|
|
1587
|
+
// transmission
|
|
1588
|
+
/*
|
|
1589
|
+
float transmissionEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
|
|
1590
|
+
|
|
1591
|
+
// See section 4.2 in https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
|
|
1592
|
+
|
|
1593
|
+
float filteredRoughness = surf.filteredRoughness;
|
|
1594
|
+
float eta = surf.eta;
|
|
1595
|
+
bool frontFace = surf.frontFace;
|
|
1596
|
+
bool thinFilm = surf.thinFilm;
|
|
1597
|
+
|
|
1598
|
+
color = surf.transmission * surf.color;
|
|
1599
|
+
|
|
1600
|
+
float denom = pow( eta * dot( wi, wh ) + dot( wo, wh ), 2.0 );
|
|
1601
|
+
return ggxPDF( wo, wh, filteredRoughness ) / denom;
|
|
1602
|
+
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
vec3 transmissionDirection( vec3 wo, SurfaceRecord surf ) {
|
|
1606
|
+
|
|
1607
|
+
float filteredRoughness = surf.filteredRoughness;
|
|
1608
|
+
float eta = surf.eta;
|
|
1609
|
+
bool frontFace = surf.frontFace;
|
|
1610
|
+
|
|
1611
|
+
// sample ggx vndf distribution which gives a new normal
|
|
1612
|
+
vec3 halfVector = ggxDirection(
|
|
1613
|
+
wo,
|
|
1614
|
+
vec2( filteredRoughness ),
|
|
1615
|
+
rand2( 13 )
|
|
1616
|
+
);
|
|
1617
|
+
|
|
1618
|
+
vec3 lightDirection = refract( normalize( - wo ), halfVector, eta );
|
|
1619
|
+
if ( surf.thinFilm ) {
|
|
1620
|
+
|
|
1621
|
+
lightDirection = - refract( normalize( - lightDirection ), - vec3( 0.0, 0.0, 1.0 ), 1.0 / eta );
|
|
1622
|
+
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
return normalize( lightDirection );
|
|
1626
|
+
|
|
1627
|
+
}
|
|
1628
|
+
*/
|
|
1629
|
+
|
|
1630
|
+
// TODO: This is just using a basic cosine-weighted specular distribution with an
|
|
1631
|
+
// incorrect PDF value at the moment. Update it to correctly use a GGX distribution
|
|
1632
|
+
float transmissionEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
|
|
1633
|
+
|
|
1634
|
+
color = surf.transmission * surf.color;
|
|
1635
|
+
|
|
1636
|
+
// PDF
|
|
1637
|
+
// float F = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
|
|
1638
|
+
// float F = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
|
|
1639
|
+
// if ( F >= 1.0 ) {
|
|
1640
|
+
|
|
1641
|
+
// return 0.0;
|
|
1642
|
+
|
|
1643
|
+
// }
|
|
1644
|
+
|
|
1645
|
+
// return 1.0 / ( 1.0 - F );
|
|
1646
|
+
|
|
1647
|
+
// reverted to previous to transmission. The above was causing black pixels
|
|
1648
|
+
float eta = surf.eta;
|
|
1649
|
+
float f0 = surf.f0;
|
|
1650
|
+
float cosTheta = min( wo.z, 1.0 );
|
|
1651
|
+
float sinTheta = sqrt( 1.0 - cosTheta * cosTheta );
|
|
1652
|
+
float reflectance = schlickFresnel( cosTheta, f0 );
|
|
1653
|
+
bool cannotRefract = eta * sinTheta > 1.0;
|
|
1654
|
+
if ( cannotRefract ) {
|
|
1655
|
+
|
|
1656
|
+
return 0.0;
|
|
1657
|
+
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
return 1.0 / ( 1.0 - reflectance );
|
|
1661
|
+
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
vec3 transmissionDirection( vec3 wo, SurfaceRecord surf ) {
|
|
1665
|
+
|
|
1666
|
+
float roughness = surf.filteredRoughness;
|
|
1667
|
+
float eta = surf.eta;
|
|
1668
|
+
vec3 halfVector = normalize( vec3( 0.0, 0.0, 1.0 ) + sampleSphere( rand2( 13 ) ) * roughness );
|
|
1669
|
+
vec3 lightDirection = refract( normalize( - wo ), halfVector, eta );
|
|
1670
|
+
|
|
1671
|
+
if ( surf.thinFilm ) {
|
|
1672
|
+
|
|
1673
|
+
lightDirection = - refract( normalize( - lightDirection ), - vec3( 0.0, 0.0, 1.0 ), 1.0 / eta );
|
|
1674
|
+
|
|
1675
|
+
}
|
|
1676
|
+
return normalize( lightDirection );
|
|
1677
|
+
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// clearcoat
|
|
1681
|
+
float clearcoatEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
|
|
1682
|
+
|
|
1683
|
+
float ior = 1.5;
|
|
1684
|
+
float f0 = iorRatioToF0( ior );
|
|
1685
|
+
bool frontFace = surf.frontFace;
|
|
1686
|
+
float roughness = surf.filteredClearcoatRoughness;
|
|
1687
|
+
|
|
1688
|
+
float eta = frontFace ? 1.0 / ior : ior;
|
|
1689
|
+
float G = ggxShadowMaskG2( wi, wo, roughness );
|
|
1690
|
+
float D = ggxDistribution( wh, roughness );
|
|
1691
|
+
float F = schlickFresnel( dot( wi, wh ), f0 );
|
|
1692
|
+
|
|
1693
|
+
float fClearcoat = F * D * G / ( 4.0 * abs( wi.z * wo.z ) );
|
|
1694
|
+
color = color * ( 1.0 - surf.clearcoat * F ) + fClearcoat * surf.clearcoat * wi.z;
|
|
1695
|
+
|
|
1696
|
+
// PDF
|
|
1697
|
+
// See equation (27) in http://jcgt.org/published/0003/02/03/
|
|
1698
|
+
return ggxPDF( wo, wh, roughness ) / ( 4.0 * dot( wi, wh ) );
|
|
1699
|
+
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
vec3 clearcoatDirection( vec3 wo, SurfaceRecord surf ) {
|
|
1703
|
+
|
|
1704
|
+
// sample ggx vndf distribution which gives a new normal
|
|
1705
|
+
float roughness = surf.filteredClearcoatRoughness;
|
|
1706
|
+
vec3 halfVector = ggxDirection(
|
|
1707
|
+
wo,
|
|
1708
|
+
vec2( roughness ),
|
|
1709
|
+
rand2( 14 )
|
|
1710
|
+
);
|
|
1711
|
+
|
|
1712
|
+
// apply to new ray by reflecting off the new normal
|
|
1713
|
+
return - reflect( wo, halfVector );
|
|
1714
|
+
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
// sheen
|
|
1718
|
+
vec3 sheenColor( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf ) {
|
|
1719
|
+
|
|
1720
|
+
float cosThetaO = saturateCos( wo.z );
|
|
1721
|
+
float cosThetaI = saturateCos( wi.z );
|
|
1722
|
+
float cosThetaH = wh.z;
|
|
1723
|
+
|
|
1724
|
+
float D = velvetD( cosThetaH, surf.sheenRoughness );
|
|
1725
|
+
float G = velvetG( cosThetaO, cosThetaI, surf.sheenRoughness );
|
|
1726
|
+
|
|
1727
|
+
// See equation (1) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
|
|
1728
|
+
vec3 color = surf.sheenColor;
|
|
1729
|
+
color *= D * G / ( 4.0 * abs( cosThetaO * cosThetaI ) );
|
|
1730
|
+
color *= wi.z;
|
|
1731
|
+
|
|
1732
|
+
return color;
|
|
1733
|
+
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
// bsdf
|
|
1737
|
+
void getLobeWeights(
|
|
1738
|
+
vec3 wo, vec3 wi, vec3 wh, vec3 clearcoatWo, SurfaceRecord surf,
|
|
1739
|
+
inout float diffuseWeight, inout float specularWeight, inout float transmissionWeight, inout float clearcoatWeight
|
|
1740
|
+
) {
|
|
1741
|
+
|
|
1742
|
+
float metalness = surf.metalness;
|
|
1743
|
+
float transmission = surf.transmission;
|
|
1744
|
+
// float fEstimate = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
|
|
1745
|
+
float fEstimate = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
|
|
1746
|
+
|
|
1747
|
+
float transSpecularProb = mix( max( 0.25, fEstimate ), 1.0, metalness );
|
|
1748
|
+
float diffSpecularProb = 0.5 + 0.5 * metalness;
|
|
1749
|
+
|
|
1750
|
+
diffuseWeight = ( 1.0 - transmission ) * ( 1.0 - diffSpecularProb );
|
|
1751
|
+
specularWeight = transmission * transSpecularProb + ( 1.0 - transmission ) * diffSpecularProb;
|
|
1752
|
+
transmissionWeight = transmission * ( 1.0 - transSpecularProb );
|
|
1753
|
+
clearcoatWeight = surf.clearcoat * schlickFresnel( clearcoatWo.z, 0.04 );
|
|
1754
|
+
|
|
1755
|
+
float totalWeight = diffuseWeight + specularWeight + transmissionWeight + clearcoatWeight;
|
|
1756
|
+
diffuseWeight /= totalWeight;
|
|
1757
|
+
specularWeight /= totalWeight;
|
|
1758
|
+
transmissionWeight /= totalWeight;
|
|
1759
|
+
clearcoatWeight /= totalWeight;
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
float bsdfEval(
|
|
1763
|
+
vec3 wo, vec3 clearcoatWo, vec3 wi, vec3 clearcoatWi, SurfaceRecord surf,
|
|
1764
|
+
float diffuseWeight, float specularWeight, float transmissionWeight, float clearcoatWeight, inout float specularPdf, inout vec3 color
|
|
1765
|
+
) {
|
|
1766
|
+
|
|
1767
|
+
float metalness = surf.metalness;
|
|
1768
|
+
float transmission = surf.transmission;
|
|
1769
|
+
|
|
1770
|
+
float spdf = 0.0;
|
|
1771
|
+
float dpdf = 0.0;
|
|
1772
|
+
float tpdf = 0.0;
|
|
1773
|
+
float cpdf = 0.0;
|
|
1774
|
+
color = vec3( 0.0 );
|
|
1775
|
+
|
|
1776
|
+
vec3 halfVector = getHalfVector( wi, wo, surf.eta );
|
|
1777
|
+
|
|
1778
|
+
// diffuse
|
|
1779
|
+
if ( diffuseWeight > 0.0 && wi.z > 0.0 ) {
|
|
1780
|
+
|
|
1781
|
+
dpdf = diffuseEval( wo, wi, halfVector, surf, color );
|
|
1782
|
+
color *= 1.0 - surf.transmission;
|
|
1783
|
+
|
|
1784
|
+
}
|
|
1785
|
+
|
|
1786
|
+
// ggx specular
|
|
1787
|
+
if ( specularWeight > 0.0 && wi.z > 0.0 ) {
|
|
1788
|
+
|
|
1789
|
+
vec3 outColor;
|
|
1790
|
+
spdf = specularEval( wo, wi, getHalfVector( wi, wo ), surf, outColor );
|
|
1791
|
+
color += outColor;
|
|
1792
|
+
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
// transmission
|
|
1796
|
+
if ( transmissionWeight > 0.0 && wi.z < 0.0 ) {
|
|
1797
|
+
|
|
1798
|
+
tpdf = transmissionEval( wo, wi, halfVector, surf, color );
|
|
1799
|
+
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
// sheen
|
|
1803
|
+
color *= mix( 1.0, sheenAlbedoScaling( wo, wi, surf ), surf.sheen );
|
|
1804
|
+
color += sheenColor( wo, wi, halfVector, surf ) * surf.sheen;
|
|
1805
|
+
|
|
1806
|
+
// clearcoat
|
|
1807
|
+
if ( clearcoatWi.z >= 0.0 && clearcoatWeight > 0.0 ) {
|
|
1808
|
+
|
|
1809
|
+
vec3 clearcoatHalfVector = getHalfVector( clearcoatWo, clearcoatWi );
|
|
1810
|
+
cpdf = clearcoatEval( clearcoatWo, clearcoatWi, clearcoatHalfVector, surf, color );
|
|
1811
|
+
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
float pdf =
|
|
1815
|
+
dpdf * diffuseWeight
|
|
1816
|
+
+ spdf * specularWeight
|
|
1817
|
+
+ tpdf * transmissionWeight
|
|
1818
|
+
+ cpdf * clearcoatWeight;
|
|
1819
|
+
|
|
1820
|
+
// retrieve specular rays for the shadows flag
|
|
1821
|
+
specularPdf = spdf * specularWeight + cpdf * clearcoatWeight;
|
|
1822
|
+
|
|
1823
|
+
return pdf;
|
|
1824
|
+
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
float bsdfResult( vec3 worldWo, vec3 worldWi, SurfaceRecord surf, inout vec3 color ) {
|
|
1828
|
+
|
|
1829
|
+
if ( surf.volumeParticle ) {
|
|
1830
|
+
|
|
1831
|
+
color = surf.color / ( 4.0 * PI );
|
|
1832
|
+
return 1.0 / ( 4.0 * PI );
|
|
1833
|
+
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
vec3 wo = normalize( surf.normalInvBasis * worldWo );
|
|
1837
|
+
vec3 wi = normalize( surf.normalInvBasis * worldWi );
|
|
1838
|
+
|
|
1839
|
+
vec3 clearcoatWo = normalize( surf.clearcoatInvBasis * worldWo );
|
|
1840
|
+
vec3 clearcoatWi = normalize( surf.clearcoatInvBasis * worldWi );
|
|
1841
|
+
|
|
1842
|
+
vec3 wh = getHalfVector( wo, wi, surf.eta );
|
|
1843
|
+
float diffuseWeight;
|
|
1844
|
+
float specularWeight;
|
|
1845
|
+
float transmissionWeight;
|
|
1846
|
+
float clearcoatWeight;
|
|
1847
|
+
getLobeWeights( wo, wi, wh, clearcoatWo, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight );
|
|
1848
|
+
|
|
1849
|
+
float specularPdf;
|
|
1850
|
+
return bsdfEval( wo, clearcoatWo, wi, clearcoatWi, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight, specularPdf, color );
|
|
1851
|
+
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
ScatterRecord bsdfSample( vec3 worldWo, SurfaceRecord surf ) {
|
|
1855
|
+
|
|
1856
|
+
if ( surf.volumeParticle ) {
|
|
1857
|
+
|
|
1858
|
+
ScatterRecord sampleRec;
|
|
1859
|
+
sampleRec.specularPdf = 0.0;
|
|
1860
|
+
sampleRec.pdf = 1.0 / ( 4.0 * PI );
|
|
1861
|
+
sampleRec.direction = sampleSphere( rand2( 16 ) );
|
|
1862
|
+
sampleRec.color = surf.color / ( 4.0 * PI );
|
|
1863
|
+
return sampleRec;
|
|
1864
|
+
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
vec3 wo = normalize( surf.normalInvBasis * worldWo );
|
|
1868
|
+
vec3 clearcoatWo = normalize( surf.clearcoatInvBasis * worldWo );
|
|
1869
|
+
mat3 normalBasis = surf.normalBasis;
|
|
1870
|
+
mat3 invBasis = surf.normalInvBasis;
|
|
1871
|
+
mat3 clearcoatNormalBasis = surf.clearcoatBasis;
|
|
1872
|
+
mat3 clearcoatInvBasis = surf.clearcoatInvBasis;
|
|
1873
|
+
|
|
1874
|
+
float diffuseWeight;
|
|
1875
|
+
float specularWeight;
|
|
1876
|
+
float transmissionWeight;
|
|
1877
|
+
float clearcoatWeight;
|
|
1878
|
+
// using normal and basically-reflected ray since we don't have proper half vector here
|
|
1879
|
+
getLobeWeights( wo, wo, vec3( 0, 0, 1 ), clearcoatWo, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight );
|
|
1880
|
+
|
|
1881
|
+
float pdf[4];
|
|
1882
|
+
pdf[0] = diffuseWeight;
|
|
1883
|
+
pdf[1] = specularWeight;
|
|
1884
|
+
pdf[2] = transmissionWeight;
|
|
1885
|
+
pdf[3] = clearcoatWeight;
|
|
1886
|
+
|
|
1887
|
+
float cdf[4];
|
|
1888
|
+
cdf[0] = pdf[0];
|
|
1889
|
+
cdf[1] = pdf[1] + cdf[0];
|
|
1890
|
+
cdf[2] = pdf[2] + cdf[1];
|
|
1891
|
+
cdf[3] = pdf[3] + cdf[2];
|
|
1892
|
+
|
|
1893
|
+
if( cdf[3] != 0.0 ) {
|
|
1894
|
+
|
|
1895
|
+
float invMaxCdf = 1.0 / cdf[3];
|
|
1896
|
+
cdf[0] *= invMaxCdf;
|
|
1897
|
+
cdf[1] *= invMaxCdf;
|
|
1898
|
+
cdf[2] *= invMaxCdf;
|
|
1899
|
+
cdf[3] *= invMaxCdf;
|
|
1900
|
+
|
|
1901
|
+
} else {
|
|
1902
|
+
|
|
1903
|
+
cdf[0] = 1.0;
|
|
1904
|
+
cdf[1] = 0.0;
|
|
1905
|
+
cdf[2] = 0.0;
|
|
1906
|
+
cdf[3] = 0.0;
|
|
1907
|
+
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
vec3 wi;
|
|
1911
|
+
vec3 clearcoatWi;
|
|
1912
|
+
|
|
1913
|
+
float r = rand( 15 );
|
|
1914
|
+
if ( r <= cdf[0] ) { // diffuse
|
|
1915
|
+
|
|
1916
|
+
wi = diffuseDirection( wo, surf );
|
|
1917
|
+
clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
|
|
1918
|
+
|
|
1919
|
+
} else if ( r <= cdf[1] ) { // specular
|
|
1920
|
+
|
|
1921
|
+
wi = specularDirection( wo, surf );
|
|
1922
|
+
clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
|
|
1923
|
+
|
|
1924
|
+
} else if ( r <= cdf[2] ) { // transmission / refraction
|
|
1925
|
+
|
|
1926
|
+
wi = transmissionDirection( wo, surf );
|
|
1927
|
+
clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
|
|
1928
|
+
|
|
1929
|
+
} else if ( r <= cdf[3] ) { // clearcoat
|
|
1930
|
+
|
|
1931
|
+
clearcoatWi = clearcoatDirection( clearcoatWo, surf );
|
|
1932
|
+
wi = normalize( invBasis * normalize( clearcoatNormalBasis * clearcoatWi ) );
|
|
1933
|
+
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
ScatterRecord result;
|
|
1937
|
+
result.pdf = bsdfEval( wo, clearcoatWo, wi, clearcoatWi, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight, result.specularPdf, result.color );
|
|
1938
|
+
result.direction = normalize( surf.normalBasis * wi );
|
|
1939
|
+
|
|
1940
|
+
return result;
|
|
1941
|
+
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
`,Qn=`
|
|
1945
|
+
|
|
1946
|
+
// returns the hit distance given the material density
|
|
1947
|
+
float intersectFogVolume( Material material, float u ) {
|
|
1948
|
+
|
|
1949
|
+
// https://raytracing.github.io/books/RayTracingTheNextWeek.html#volumes/constantdensitymediums
|
|
1950
|
+
return material.opacity == 0.0 ? INFINITY : ( - 1.0 / material.opacity ) * log( u );
|
|
1951
|
+
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
ScatterRecord sampleFogVolume( SurfaceRecord surf, vec2 uv ) {
|
|
1955
|
+
|
|
1956
|
+
ScatterRecord sampleRec;
|
|
1957
|
+
sampleRec.specularPdf = 0.0;
|
|
1958
|
+
sampleRec.pdf = 1.0 / ( 2.0 * PI );
|
|
1959
|
+
sampleRec.direction = sampleSphere( uv );
|
|
1960
|
+
sampleRec.color = surf.color;
|
|
1961
|
+
return sampleRec;
|
|
1962
|
+
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
`,Zn=`
|
|
1966
|
+
|
|
1967
|
+
// The GGX functions provide sampling and distribution information for normals as output so
|
|
1968
|
+
// in order to get probability of scatter direction the half vector must be computed and provided.
|
|
1969
|
+
// [0] https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
|
|
1970
|
+
// [1] https://hal.archives-ouvertes.fr/hal-01509746/document
|
|
1971
|
+
// [2] http://jcgt.org/published/0007/04/01/
|
|
1972
|
+
// [4] http://jcgt.org/published/0003/02/03/
|
|
1973
|
+
|
|
1974
|
+
// trowbridge-reitz === GGX === GTR
|
|
1975
|
+
|
|
1976
|
+
vec3 ggxDirection( vec3 incidentDir, vec2 roughness, vec2 uv ) {
|
|
1977
|
+
|
|
1978
|
+
// TODO: try GGXVNDF implementation from reference [2], here. Needs to update ggxDistribution
|
|
1979
|
+
// function below, as well
|
|
1980
|
+
|
|
1981
|
+
// Implementation from reference [1]
|
|
1982
|
+
// stretch view
|
|
1983
|
+
vec3 V = normalize( vec3( roughness * incidentDir.xy, incidentDir.z ) );
|
|
1984
|
+
|
|
1985
|
+
// orthonormal basis
|
|
1986
|
+
vec3 T1 = ( V.z < 0.9999 ) ? normalize( cross( V, vec3( 0.0, 0.0, 1.0 ) ) ) : vec3( 1.0, 0.0, 0.0 );
|
|
1987
|
+
vec3 T2 = cross( T1, V );
|
|
1988
|
+
|
|
1989
|
+
// sample point with polar coordinates (r, phi)
|
|
1990
|
+
float a = 1.0 / ( 1.0 + V.z );
|
|
1991
|
+
float r = sqrt( uv.x );
|
|
1992
|
+
float phi = ( uv.y < a ) ? uv.y / a * PI : PI + ( uv.y - a ) / ( 1.0 - a ) * PI;
|
|
1993
|
+
float P1 = r * cos( phi );
|
|
1994
|
+
float P2 = r * sin( phi ) * ( ( uv.y < a ) ? 1.0 : V.z );
|
|
1995
|
+
|
|
1996
|
+
// compute normal
|
|
1997
|
+
vec3 N = P1 * T1 + P2 * T2 + V * sqrt( max( 0.0, 1.0 - P1 * P1 - P2 * P2 ) );
|
|
1998
|
+
|
|
1999
|
+
// unstretch
|
|
2000
|
+
N = normalize( vec3( roughness * N.xy, max( 0.0, N.z ) ) );
|
|
2001
|
+
|
|
2002
|
+
return N;
|
|
2003
|
+
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
// Below are PDF and related functions for use in a Monte Carlo path tracer
|
|
2007
|
+
// as specified in Appendix B of the following paper
|
|
2008
|
+
// See equation (34) from reference [0]
|
|
2009
|
+
float ggxLamda( float theta, float roughness ) {
|
|
2010
|
+
|
|
2011
|
+
float tanTheta = tan( theta );
|
|
2012
|
+
float tanTheta2 = tanTheta * tanTheta;
|
|
2013
|
+
float alpha2 = roughness * roughness;
|
|
2014
|
+
|
|
2015
|
+
float numerator = - 1.0 + sqrt( 1.0 + alpha2 * tanTheta2 );
|
|
2016
|
+
return numerator / 2.0;
|
|
2017
|
+
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
// See equation (34) from reference [0]
|
|
2021
|
+
float ggxShadowMaskG1( float theta, float roughness ) {
|
|
2022
|
+
|
|
2023
|
+
return 1.0 / ( 1.0 + ggxLamda( theta, roughness ) );
|
|
2024
|
+
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
// See equation (125) from reference [4]
|
|
2028
|
+
float ggxShadowMaskG2( vec3 wi, vec3 wo, float roughness ) {
|
|
2029
|
+
|
|
2030
|
+
float incidentTheta = acos( wi.z );
|
|
2031
|
+
float scatterTheta = acos( wo.z );
|
|
2032
|
+
return 1.0 / ( 1.0 + ggxLamda( incidentTheta, roughness ) + ggxLamda( scatterTheta, roughness ) );
|
|
2033
|
+
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
// See equation (33) from reference [0]
|
|
2037
|
+
float ggxDistribution( vec3 halfVector, float roughness ) {
|
|
2038
|
+
|
|
2039
|
+
float a2 = roughness * roughness;
|
|
2040
|
+
a2 = max( EPSILON, a2 );
|
|
2041
|
+
float cosTheta = halfVector.z;
|
|
2042
|
+
float cosTheta4 = pow( cosTheta, 4.0 );
|
|
2043
|
+
|
|
2044
|
+
if ( cosTheta == 0.0 ) return 0.0;
|
|
2045
|
+
|
|
2046
|
+
float theta = acosSafe( halfVector.z );
|
|
2047
|
+
float tanTheta = tan( theta );
|
|
2048
|
+
float tanTheta2 = pow( tanTheta, 2.0 );
|
|
2049
|
+
|
|
2050
|
+
float denom = PI * cosTheta4 * pow( a2 + tanTheta2, 2.0 );
|
|
2051
|
+
return ( a2 / denom );
|
|
2052
|
+
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
// See equation (3) from reference [2]
|
|
2056
|
+
float ggxPDF( vec3 wi, vec3 halfVector, float roughness ) {
|
|
2057
|
+
|
|
2058
|
+
float incidentTheta = acos( wi.z );
|
|
2059
|
+
float D = ggxDistribution( halfVector, roughness );
|
|
2060
|
+
float G1 = ggxShadowMaskG1( incidentTheta, roughness );
|
|
2061
|
+
|
|
2062
|
+
return D * G1 * max( 0.0, dot( wi, halfVector ) ) / wi.z;
|
|
2063
|
+
|
|
2064
|
+
}
|
|
2065
|
+
|
|
2066
|
+
`,Xn=`
|
|
2067
|
+
|
|
2068
|
+
// XYZ to sRGB color space
|
|
2069
|
+
const mat3 XYZ_TO_REC709 = mat3(
|
|
2070
|
+
3.2404542, -0.9692660, 0.0556434,
|
|
2071
|
+
-1.5371385, 1.8760108, -0.2040259,
|
|
2072
|
+
-0.4985314, 0.0415560, 1.0572252
|
|
2073
|
+
);
|
|
2074
|
+
|
|
2075
|
+
vec3 fresnel0ToIor( vec3 fresnel0 ) {
|
|
2076
|
+
|
|
2077
|
+
vec3 sqrtF0 = sqrt( fresnel0 );
|
|
2078
|
+
return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
|
|
2079
|
+
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
// Conversion FO/IOR
|
|
2083
|
+
vec3 iorToFresnel0( vec3 transmittedIor, float incidentIor ) {
|
|
2084
|
+
|
|
2085
|
+
return square( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
|
|
2086
|
+
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
// ior is a value between 1.0 and 3.0. 1.0 is air interface
|
|
2090
|
+
float iorToFresnel0( float transmittedIor, float incidentIor ) {
|
|
2091
|
+
|
|
2092
|
+
return square( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ) );
|
|
2093
|
+
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
// Fresnel equations for dielectric/dielectric interfaces. See https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
|
|
2097
|
+
vec3 evalSensitivity( float OPD, vec3 shift ) {
|
|
2098
|
+
|
|
2099
|
+
float phase = 2.0 * PI * OPD * 1.0e-9;
|
|
2100
|
+
|
|
2101
|
+
vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
|
|
2102
|
+
vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
|
|
2103
|
+
vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
|
|
2104
|
+
|
|
2105
|
+
vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - square( phase ) * var );
|
|
2106
|
+
xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * square( phase ) );
|
|
2107
|
+
xyz /= 1.0685e-7;
|
|
2108
|
+
|
|
2109
|
+
vec3 srgb = XYZ_TO_REC709 * xyz;
|
|
2110
|
+
return srgb;
|
|
2111
|
+
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
// See Section 4. Analytic Spectral Integration, A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence, https://hal.archives-ouvertes.fr/hal-01518344/document
|
|
2115
|
+
vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
|
|
2116
|
+
|
|
2117
|
+
vec3 I;
|
|
2118
|
+
|
|
2119
|
+
// Force iridescenceIor -> outsideIOR when thinFilmThickness -> 0.0
|
|
2120
|
+
float iridescenceIor = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
|
|
2121
|
+
|
|
2122
|
+
// Evaluate the cosTheta on the base layer (Snell law)
|
|
2123
|
+
float sinTheta2Sq = square( outsideIOR / iridescenceIor ) * ( 1.0 - square( cosTheta1 ) );
|
|
2124
|
+
|
|
2125
|
+
// Handle TIR:
|
|
2126
|
+
float cosTheta2Sq = 1.0 - sinTheta2Sq;
|
|
2127
|
+
if ( cosTheta2Sq < 0.0 ) {
|
|
2128
|
+
|
|
2129
|
+
return vec3( 1.0 );
|
|
2130
|
+
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
float cosTheta2 = sqrt( cosTheta2Sq );
|
|
2134
|
+
|
|
2135
|
+
// First interface
|
|
2136
|
+
float R0 = iorToFresnel0( iridescenceIor, outsideIOR );
|
|
2137
|
+
float R12 = schlickFresnel( cosTheta1, R0 );
|
|
2138
|
+
float R21 = R12;
|
|
2139
|
+
float T121 = 1.0 - R12;
|
|
2140
|
+
float phi12 = 0.0;
|
|
2141
|
+
if ( iridescenceIor < outsideIOR ) {
|
|
2142
|
+
|
|
2143
|
+
phi12 = PI;
|
|
2144
|
+
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
float phi21 = PI - phi12;
|
|
2148
|
+
|
|
2149
|
+
// Second interface
|
|
2150
|
+
vec3 baseIOR = fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); // guard against 1.0
|
|
2151
|
+
vec3 R1 = iorToFresnel0( baseIOR, iridescenceIor );
|
|
2152
|
+
vec3 R23 = schlickFresnel( cosTheta2, R1 );
|
|
2153
|
+
vec3 phi23 = vec3( 0.0 );
|
|
2154
|
+
if ( baseIOR[0] < iridescenceIor ) {
|
|
2155
|
+
|
|
2156
|
+
phi23[ 0 ] = PI;
|
|
2157
|
+
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
if ( baseIOR[1] < iridescenceIor ) {
|
|
2161
|
+
|
|
2162
|
+
phi23[ 1 ] = PI;
|
|
2163
|
+
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
if ( baseIOR[2] < iridescenceIor ) {
|
|
2167
|
+
|
|
2168
|
+
phi23[ 2 ] = PI;
|
|
2169
|
+
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
// Phase shift
|
|
2173
|
+
float OPD = 2.0 * iridescenceIor * thinFilmThickness * cosTheta2;
|
|
2174
|
+
vec3 phi = vec3( phi21 ) + phi23;
|
|
2175
|
+
|
|
2176
|
+
// Compound terms
|
|
2177
|
+
vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
|
|
2178
|
+
vec3 r123 = sqrt( R123 );
|
|
2179
|
+
vec3 Rs = square( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
|
|
2180
|
+
|
|
2181
|
+
// Reflectance term for m = 0 (DC term amplitude)
|
|
2182
|
+
vec3 C0 = R12 + Rs;
|
|
2183
|
+
I = C0;
|
|
2184
|
+
|
|
2185
|
+
// Reflectance term for m > 0 (pairs of diracs)
|
|
2186
|
+
vec3 Cm = Rs - T121;
|
|
2187
|
+
for ( int m = 1; m <= 2; ++ m ) {
|
|
2188
|
+
|
|
2189
|
+
Cm *= r123;
|
|
2190
|
+
vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
|
|
2191
|
+
I += Cm * Sm;
|
|
2192
|
+
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
// Since out of gamut colors might be produced, negative color values are clamped to 0.
|
|
2196
|
+
return max( I, vec3( 0.0 ) );
|
|
2197
|
+
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
`,Jn=`
|
|
2201
|
+
|
|
2202
|
+
// See equation (2) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
|
|
2203
|
+
float velvetD( float cosThetaH, float roughness ) {
|
|
2204
|
+
|
|
2205
|
+
float alpha = max( roughness, 0.07 );
|
|
2206
|
+
alpha = alpha * alpha;
|
|
2207
|
+
|
|
2208
|
+
float invAlpha = 1.0 / alpha;
|
|
2209
|
+
|
|
2210
|
+
float sqrCosThetaH = cosThetaH * cosThetaH;
|
|
2211
|
+
float sinThetaH = max( 1.0 - sqrCosThetaH, 0.001 );
|
|
2212
|
+
|
|
2213
|
+
return ( 2.0 + invAlpha ) * pow( sinThetaH, 0.5 * invAlpha ) / ( 2.0 * PI );
|
|
2214
|
+
|
|
2215
|
+
}
|
|
2216
|
+
|
|
2217
|
+
float velvetParamsInterpolate( int i, float oneMinusAlphaSquared ) {
|
|
2218
|
+
|
|
2219
|
+
const float p0[5] = float[5]( 25.3245, 3.32435, 0.16801, -1.27393, -4.85967 );
|
|
2220
|
+
const float p1[5] = float[5]( 21.5473, 3.82987, 0.19823, -1.97760, -4.32054 );
|
|
2221
|
+
|
|
2222
|
+
return mix( p1[i], p0[i], oneMinusAlphaSquared );
|
|
2223
|
+
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
float velvetL( float x, float alpha ) {
|
|
2227
|
+
|
|
2228
|
+
float oneMinusAlpha = 1.0 - alpha;
|
|
2229
|
+
float oneMinusAlphaSquared = oneMinusAlpha * oneMinusAlpha;
|
|
2230
|
+
|
|
2231
|
+
float a = velvetParamsInterpolate( 0, oneMinusAlphaSquared );
|
|
2232
|
+
float b = velvetParamsInterpolate( 1, oneMinusAlphaSquared );
|
|
2233
|
+
float c = velvetParamsInterpolate( 2, oneMinusAlphaSquared );
|
|
2234
|
+
float d = velvetParamsInterpolate( 3, oneMinusAlphaSquared );
|
|
2235
|
+
float e = velvetParamsInterpolate( 4, oneMinusAlphaSquared );
|
|
2236
|
+
|
|
2237
|
+
return a / ( 1.0 + b * pow( abs( x ), c ) ) + d * x + e;
|
|
2238
|
+
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
// See equation (3) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
|
|
2242
|
+
float velvetLambda( float cosTheta, float alpha ) {
|
|
2243
|
+
|
|
2244
|
+
return abs( cosTheta ) < 0.5 ? exp( velvetL( cosTheta, alpha ) ) : exp( 2.0 * velvetL( 0.5, alpha ) - velvetL( 1.0 - cosTheta, alpha ) );
|
|
2245
|
+
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
// See Section 3, Shadowing Term, in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
|
|
2249
|
+
float velvetG( float cosThetaO, float cosThetaI, float roughness ) {
|
|
2250
|
+
|
|
2251
|
+
float alpha = max( roughness, 0.07 );
|
|
2252
|
+
alpha = alpha * alpha;
|
|
2253
|
+
|
|
2254
|
+
return 1.0 / ( 1.0 + velvetLambda( cosThetaO, alpha ) + velvetLambda( cosThetaI, alpha ) );
|
|
2255
|
+
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
float directionalAlbedoSheen( float cosTheta, float alpha ) {
|
|
2259
|
+
|
|
2260
|
+
cosTheta = saturate( cosTheta );
|
|
2261
|
+
|
|
2262
|
+
float c = 1.0 - cosTheta;
|
|
2263
|
+
float c3 = c * c * c;
|
|
2264
|
+
|
|
2265
|
+
return 0.65584461 * c3 + 1.0 / ( 4.16526551 + exp( -7.97291361 * sqrt( alpha ) + 6.33516894 ) );
|
|
2266
|
+
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
float sheenAlbedoScaling( vec3 wo, vec3 wi, SurfaceRecord surf ) {
|
|
2270
|
+
|
|
2271
|
+
float alpha = max( surf.sheenRoughness, 0.07 );
|
|
2272
|
+
alpha = alpha * alpha;
|
|
2273
|
+
|
|
2274
|
+
float maxSheenColor = max( max( surf.sheenColor.r, surf.sheenColor.g ), surf.sheenColor.b );
|
|
2275
|
+
|
|
2276
|
+
float eWo = directionalAlbedoSheen( saturateCos( wo.z ), alpha );
|
|
2277
|
+
float eWi = directionalAlbedoSheen( saturateCos( wi.z ), alpha );
|
|
2278
|
+
|
|
2279
|
+
return min( 1.0 - maxSheenColor * eWo, 1.0 - maxSheenColor * eWi );
|
|
2280
|
+
|
|
2281
|
+
}
|
|
2282
|
+
|
|
2283
|
+
// See Section 5, Layering, in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
|
|
2284
|
+
float sheenAlbedoScaling( vec3 wo, SurfaceRecord surf ) {
|
|
2285
|
+
|
|
2286
|
+
float alpha = max( surf.sheenRoughness, 0.07 );
|
|
2287
|
+
alpha = alpha * alpha;
|
|
2288
|
+
|
|
2289
|
+
float maxSheenColor = max( max( surf.sheenColor.r, surf.sheenColor.g ), surf.sheenColor.b );
|
|
2290
|
+
|
|
2291
|
+
float eWo = directionalAlbedoSheen( saturateCos( wo.z ), alpha );
|
|
2292
|
+
|
|
2293
|
+
return 1.0 - maxSheenColor * eWo;
|
|
2294
|
+
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
`,Kn=`
|
|
2298
|
+
|
|
2299
|
+
#ifndef FOG_CHECK_ITERATIONS
|
|
2300
|
+
#define FOG_CHECK_ITERATIONS 30
|
|
2301
|
+
#endif
|
|
2302
|
+
|
|
2303
|
+
// returns whether the given material is a fog material or not
|
|
2304
|
+
bool isMaterialFogVolume( sampler2D materials, uint materialIndex ) {
|
|
2305
|
+
|
|
2306
|
+
uint i = materialIndex * 45u;
|
|
2307
|
+
vec4 s14 = texelFetch1D( materials, i + 14u );
|
|
2308
|
+
return bool( int( s14.b ) & 4 );
|
|
2309
|
+
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
// returns true if we're within the first fog volume we hit
|
|
2313
|
+
bool bvhIntersectFogVolumeHit(
|
|
2314
|
+
vec3 rayOrigin, vec3 rayDirection,
|
|
2315
|
+
usampler2D materialIndexAttribute, sampler2D materials,
|
|
2316
|
+
inout Material material
|
|
2317
|
+
) {
|
|
2318
|
+
|
|
2319
|
+
material.fogVolume = false;
|
|
2320
|
+
|
|
2321
|
+
for ( int i = 0; i < FOG_CHECK_ITERATIONS; i ++ ) {
|
|
2322
|
+
|
|
2323
|
+
// find nearest hit
|
|
2324
|
+
uvec4 faceIndices = uvec4( 0u );
|
|
2325
|
+
vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
|
|
2326
|
+
vec3 barycoord = vec3( 0.0 );
|
|
2327
|
+
float side = 1.0;
|
|
2328
|
+
float dist = 0.0;
|
|
2329
|
+
bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
|
|
2330
|
+
if ( hit ) {
|
|
2331
|
+
|
|
2332
|
+
// if it's a fog volume return whether we hit the front or back face
|
|
2333
|
+
uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
|
|
2334
|
+
if ( isMaterialFogVolume( materials, materialIndex ) ) {
|
|
2335
|
+
|
|
2336
|
+
material = readMaterialInfo( materials, materialIndex );
|
|
2337
|
+
return side == - 1.0;
|
|
2338
|
+
|
|
2339
|
+
} else {
|
|
2340
|
+
|
|
2341
|
+
// move the ray forward
|
|
2342
|
+
rayOrigin = stepRayOrigin( rayOrigin, rayDirection, - faceNormal, dist );
|
|
2343
|
+
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
} else {
|
|
2347
|
+
|
|
2348
|
+
return false;
|
|
2349
|
+
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
return false;
|
|
2355
|
+
|
|
2356
|
+
}
|
|
2357
|
+
|
|
2358
|
+
`,$n=`
|
|
2359
|
+
|
|
2360
|
+
// step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
|
|
2361
|
+
// returns true if a solid surface was hit
|
|
2362
|
+
bool attenuateHit(
|
|
2363
|
+
RenderState state,
|
|
2364
|
+
Ray ray, float rayDist,
|
|
2365
|
+
out vec3 color
|
|
2366
|
+
) {
|
|
2367
|
+
|
|
2368
|
+
// store the original bounce index so we can reset it after
|
|
2369
|
+
uint originalBounceIndex = sobolBounceIndex;
|
|
2370
|
+
|
|
2371
|
+
int traversals = state.traversals;
|
|
2372
|
+
int transmissiveTraversals = state.transmissiveTraversals;
|
|
2373
|
+
bool isShadowRay = state.isShadowRay;
|
|
2374
|
+
Material fogMaterial = state.fogMaterial;
|
|
2375
|
+
|
|
2376
|
+
vec3 startPoint = ray.origin;
|
|
2377
|
+
|
|
2378
|
+
// hit results
|
|
2379
|
+
SurfaceHit surfaceHit;
|
|
2380
|
+
|
|
2381
|
+
color = vec3( 1.0 );
|
|
2382
|
+
|
|
2383
|
+
bool result = true;
|
|
2384
|
+
for ( int i = 0; i < traversals; i ++ ) {
|
|
2385
|
+
|
|
2386
|
+
sobolBounceIndex ++;
|
|
2387
|
+
|
|
2388
|
+
int hitType = traceScene( ray, fogMaterial, surfaceHit );
|
|
2389
|
+
|
|
2390
|
+
if ( hitType == FOG_HIT ) {
|
|
2391
|
+
|
|
2392
|
+
result = true;
|
|
2393
|
+
break;
|
|
2394
|
+
|
|
2395
|
+
} else if ( hitType == SURFACE_HIT ) {
|
|
2396
|
+
|
|
2397
|
+
float totalDist = distance( startPoint, ray.origin + ray.direction * surfaceHit.dist );
|
|
2398
|
+
if ( totalDist > rayDist ) {
|
|
2399
|
+
|
|
2400
|
+
result = false;
|
|
2401
|
+
break;
|
|
2402
|
+
|
|
2403
|
+
}
|
|
2404
|
+
|
|
2405
|
+
// TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
|
|
2406
|
+
// Should be able to work using the material BSDF functions which will take into account specularity, etc.
|
|
2407
|
+
// TODO: should we account for emissive surfaces here?
|
|
2408
|
+
|
|
2409
|
+
uint materialIndex = uTexelFetch1D( materialIndexAttribute, surfaceHit.faceIndices.x ).r;
|
|
2410
|
+
Material material = readMaterialInfo( materials, materialIndex );
|
|
2411
|
+
|
|
2412
|
+
// adjust the ray to the new surface
|
|
2413
|
+
bool isEntering = surfaceHit.side == 1.0;
|
|
2414
|
+
ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
|
|
2415
|
+
|
|
2416
|
+
#if FEATURE_FOG
|
|
2417
|
+
|
|
2418
|
+
if ( material.fogVolume ) {
|
|
2419
|
+
|
|
2420
|
+
fogMaterial = material;
|
|
2421
|
+
fogMaterial.fogVolume = surfaceHit.side == 1.0;
|
|
2422
|
+
i -= sign( transmissiveTraversals );
|
|
2423
|
+
transmissiveTraversals --;
|
|
2424
|
+
continue;
|
|
2425
|
+
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
#endif
|
|
2429
|
+
|
|
2430
|
+
if ( ! material.castShadow && isShadowRay ) {
|
|
2431
|
+
|
|
2432
|
+
continue;
|
|
2433
|
+
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, surfaceHit.barycoord, surfaceHit.faceIndices.xyz ).xy;
|
|
2437
|
+
vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, surfaceHit.barycoord, surfaceHit.faceIndices.xyz );
|
|
2438
|
+
|
|
2439
|
+
// albedo
|
|
2440
|
+
vec4 albedo = vec4( material.color, material.opacity );
|
|
2441
|
+
if ( material.map != - 1 ) {
|
|
2442
|
+
|
|
2443
|
+
vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
|
|
2444
|
+
albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
|
|
2445
|
+
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
if ( material.vertexColors ) {
|
|
2449
|
+
|
|
2450
|
+
albedo *= vertexColor;
|
|
2451
|
+
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
// alphaMap
|
|
2455
|
+
if ( material.alphaMap != - 1 ) {
|
|
2456
|
+
|
|
2457
|
+
albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
|
|
2458
|
+
|
|
2459
|
+
}
|
|
2460
|
+
|
|
2461
|
+
// transmission
|
|
2462
|
+
float transmission = material.transmission;
|
|
2463
|
+
if ( material.transmissionMap != - 1 ) {
|
|
2464
|
+
|
|
2465
|
+
vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
|
|
2466
|
+
transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
|
|
2467
|
+
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
// metalness
|
|
2471
|
+
float metalness = material.metalness;
|
|
2472
|
+
if ( material.metalnessMap != - 1 ) {
|
|
2473
|
+
|
|
2474
|
+
vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
|
|
2475
|
+
metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
|
|
2476
|
+
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
float alphaTest = material.alphaTest;
|
|
2480
|
+
bool useAlphaTest = alphaTest != 0.0;
|
|
2481
|
+
float transmissionFactor = ( 1.0 - metalness ) * transmission;
|
|
2482
|
+
if (
|
|
2483
|
+
transmissionFactor < rand( 9 ) && ! (
|
|
2484
|
+
// material sidedness
|
|
2485
|
+
material.side != 0.0 && surfaceHit.side == material.side
|
|
2486
|
+
|
|
2487
|
+
// alpha test
|
|
2488
|
+
|| useAlphaTest && albedo.a < alphaTest
|
|
2489
|
+
|
|
2490
|
+
// opacity
|
|
2491
|
+
|| material.transparent && ! useAlphaTest && albedo.a < rand( 10 )
|
|
2492
|
+
)
|
|
2493
|
+
) {
|
|
2494
|
+
|
|
2495
|
+
result = true;
|
|
2496
|
+
break;
|
|
2497
|
+
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
if ( surfaceHit.side == 1.0 && isEntering ) {
|
|
2501
|
+
|
|
2502
|
+
// only attenuate by surface color on the way in
|
|
2503
|
+
color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
|
|
2504
|
+
|
|
2505
|
+
} else if ( surfaceHit.side == - 1.0 ) {
|
|
2506
|
+
|
|
2507
|
+
// attenuate by medium once we hit the opposite side of the model
|
|
2508
|
+
color *= transmissionAttenuation( surfaceHit.dist, material.attenuationColor, material.attenuationDistance );
|
|
2509
|
+
|
|
2510
|
+
}
|
|
2511
|
+
|
|
2512
|
+
bool isTransmissiveRay = dot( ray.direction, surfaceHit.faceNormal * surfaceHit.side ) < 0.0;
|
|
2513
|
+
if ( ( isTransmissiveRay || isEntering ) && transmissiveTraversals > 0 ) {
|
|
2514
|
+
|
|
2515
|
+
i -= sign( transmissiveTraversals );
|
|
2516
|
+
transmissiveTraversals --;
|
|
2517
|
+
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
} else {
|
|
2521
|
+
|
|
2522
|
+
result = false;
|
|
2523
|
+
break;
|
|
2524
|
+
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
}
|
|
2528
|
+
|
|
2529
|
+
// reset the bounce index
|
|
2530
|
+
sobolBounceIndex = originalBounceIndex;
|
|
2531
|
+
return result;
|
|
2532
|
+
|
|
2533
|
+
}
|
|
2534
|
+
|
|
2535
|
+
`,eo=`
|
|
2536
|
+
|
|
2537
|
+
vec3 ndcToRayOrigin( vec2 coord ) {
|
|
2538
|
+
|
|
2539
|
+
vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
|
|
2540
|
+
return rayOrigin4.xyz / rayOrigin4.w;
|
|
2541
|
+
}
|
|
2542
|
+
|
|
2543
|
+
Ray getCameraRay() {
|
|
2544
|
+
|
|
2545
|
+
vec2 ssd = vec2( 1.0 ) / resolution;
|
|
2546
|
+
|
|
2547
|
+
// Jitter the camera ray by finding a uv coordinate at a random sample
|
|
2548
|
+
// around this pixel's UV coordinate for AA
|
|
2549
|
+
vec2 ruv = rand2( 0 );
|
|
2550
|
+
vec2 jitteredUv = vUv + vec2( tentFilter( ruv.x ) * ssd.x, tentFilter( ruv.y ) * ssd.y );
|
|
2551
|
+
Ray ray;
|
|
2552
|
+
|
|
2553
|
+
#if CAMERA_TYPE == 2
|
|
2554
|
+
|
|
2555
|
+
// Equirectangular projection
|
|
2556
|
+
vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
|
|
2557
|
+
vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
|
|
2558
|
+
|
|
2559
|
+
rayDirection4 = cameraWorldMatrix * rayDirection4;
|
|
2560
|
+
rayOrigin4 = cameraWorldMatrix * rayOrigin4;
|
|
2561
|
+
|
|
2562
|
+
ray.direction = normalize( rayDirection4.xyz );
|
|
2563
|
+
ray.origin = rayOrigin4.xyz / rayOrigin4.w;
|
|
2564
|
+
|
|
2565
|
+
#else
|
|
2566
|
+
|
|
2567
|
+
// get [- 1, 1] normalized device coordinates
|
|
2568
|
+
vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
|
|
2569
|
+
ray.origin = ndcToRayOrigin( ndc );
|
|
2570
|
+
|
|
2571
|
+
#if CAMERA_TYPE == 1
|
|
2572
|
+
|
|
2573
|
+
// Orthographic projection
|
|
2574
|
+
ray.direction = ( cameraWorldMatrix * vec4( 0.0, 0.0, - 1.0, 0.0 ) ).xyz;
|
|
2575
|
+
ray.direction = normalize( ray.direction );
|
|
2576
|
+
|
|
2577
|
+
#else
|
|
2578
|
+
|
|
2579
|
+
// Perspective projection
|
|
2580
|
+
ray.direction = normalize( mat3( cameraWorldMatrix ) * ( invProjectionMatrix * vec4( ndc, 0.0, 1.0 ) ).xyz );
|
|
2581
|
+
|
|
2582
|
+
#endif
|
|
2583
|
+
|
|
2584
|
+
#endif
|
|
2585
|
+
|
|
2586
|
+
#if FEATURE_DOF
|
|
2587
|
+
{
|
|
2588
|
+
|
|
2589
|
+
// depth of field
|
|
2590
|
+
vec3 focalPoint = ray.origin + normalize( ray.direction ) * physicalCamera.focusDistance;
|
|
2591
|
+
|
|
2592
|
+
// get the aperture sample
|
|
2593
|
+
// if blades === 0 then we assume a circle
|
|
2594
|
+
vec3 shapeUVW= rand3( 1 );
|
|
2595
|
+
int blades = physicalCamera.apertureBlades;
|
|
2596
|
+
float anamorphicRatio = physicalCamera.anamorphicRatio;
|
|
2597
|
+
vec2 apertureSample = blades == 0 ? sampleCircle( shapeUVW.xy ) : sampleRegularPolygon( blades, shapeUVW );
|
|
2598
|
+
apertureSample *= physicalCamera.bokehSize * 0.5 * 1e-3;
|
|
2599
|
+
|
|
2600
|
+
// rotate the aperture shape
|
|
2601
|
+
apertureSample =
|
|
2602
|
+
rotateVector( apertureSample, physicalCamera.apertureRotation ) *
|
|
2603
|
+
saturate( vec2( anamorphicRatio, 1.0 / anamorphicRatio ) );
|
|
2604
|
+
|
|
2605
|
+
// create the new ray
|
|
2606
|
+
ray.origin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
|
|
2607
|
+
ray.direction = focalPoint - ray.origin;
|
|
2608
|
+
|
|
2609
|
+
}
|
|
2610
|
+
#endif
|
|
2611
|
+
|
|
2612
|
+
ray.direction = normalize( ray.direction );
|
|
2613
|
+
|
|
2614
|
+
return ray;
|
|
2615
|
+
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2618
|
+
`,to=`
|
|
2619
|
+
|
|
2620
|
+
vec3 directLightContribution( vec3 worldWo, SurfaceRecord surf, RenderState state, vec3 rayOrigin ) {
|
|
2621
|
+
|
|
2622
|
+
vec3 result = vec3( 0.0 );
|
|
2623
|
+
|
|
2624
|
+
// uniformly pick a light or environment map
|
|
2625
|
+
if( lightsDenom != 0.0 && rand( 5 ) < float( lights.count ) / lightsDenom ) {
|
|
2626
|
+
|
|
2627
|
+
// sample a light or environment
|
|
2628
|
+
LightRecord lightRec = randomLightSample( lights.tex, iesProfiles, lights.count, rayOrigin, rand3( 6 ) );
|
|
2629
|
+
|
|
2630
|
+
bool isSampleBelowSurface = ! surf.volumeParticle && dot( surf.faceNormal, lightRec.direction ) < 0.0;
|
|
2631
|
+
if ( isSampleBelowSurface ) {
|
|
2632
|
+
|
|
2633
|
+
lightRec.pdf = 0.0;
|
|
2634
|
+
|
|
2635
|
+
}
|
|
2636
|
+
|
|
2637
|
+
// check if a ray could even reach the light area
|
|
2638
|
+
Ray lightRay;
|
|
2639
|
+
lightRay.origin = rayOrigin;
|
|
2640
|
+
lightRay.direction = lightRec.direction;
|
|
2641
|
+
vec3 attenuatedColor;
|
|
2642
|
+
if (
|
|
2643
|
+
lightRec.pdf > 0.0 &&
|
|
2644
|
+
isDirectionValid( lightRec.direction, surf.normal, surf.faceNormal ) &&
|
|
2645
|
+
! attenuateHit( state, lightRay, lightRec.dist, attenuatedColor )
|
|
2646
|
+
) {
|
|
2647
|
+
|
|
2648
|
+
// get the material pdf
|
|
2649
|
+
vec3 sampleColor;
|
|
2650
|
+
float lightMaterialPdf = bsdfResult( worldWo, lightRec.direction, surf, sampleColor );
|
|
2651
|
+
bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
|
|
2652
|
+
if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
|
|
2653
|
+
|
|
2654
|
+
// weight the direct light contribution
|
|
2655
|
+
float lightPdf = lightRec.pdf / lightsDenom;
|
|
2656
|
+
float misWeight = lightRec.type == SPOT_LIGHT_TYPE || lightRec.type == DIR_LIGHT_TYPE || lightRec.type == POINT_LIGHT_TYPE ? 1.0 : misHeuristic( lightPdf, lightMaterialPdf );
|
|
2657
|
+
result = attenuatedColor * lightRec.emission * state.throughputColor * sampleColor * misWeight / lightPdf;
|
|
2658
|
+
|
|
2659
|
+
}
|
|
2660
|
+
|
|
2661
|
+
}
|
|
2662
|
+
|
|
2663
|
+
} else if ( envMapInfo.totalSum != 0.0 && environmentIntensity != 0.0 ) {
|
|
2664
|
+
|
|
2665
|
+
// find a sample in the environment map to include in the contribution
|
|
2666
|
+
vec3 envColor, envDirection;
|
|
2667
|
+
float envPdf = sampleEquirectProbability( rand2( 7 ), envColor, envDirection );
|
|
2668
|
+
envDirection = invEnvRotation3x3 * envDirection;
|
|
2669
|
+
|
|
2670
|
+
// this env sampling is not set up for transmissive sampling and yields overly bright
|
|
2671
|
+
// results so we ignore the sample in this case.
|
|
2672
|
+
// TODO: this should be improved but how? The env samples could traverse a few layers?
|
|
2673
|
+
bool isSampleBelowSurface = ! surf.volumeParticle && dot( surf.faceNormal, envDirection ) < 0.0;
|
|
2674
|
+
if ( isSampleBelowSurface ) {
|
|
2675
|
+
|
|
2676
|
+
envPdf = 0.0;
|
|
2677
|
+
|
|
2678
|
+
}
|
|
2679
|
+
|
|
2680
|
+
// check if a ray could even reach the surface
|
|
2681
|
+
Ray envRay;
|
|
2682
|
+
envRay.origin = rayOrigin;
|
|
2683
|
+
envRay.direction = envDirection;
|
|
2684
|
+
vec3 attenuatedColor;
|
|
2685
|
+
if (
|
|
2686
|
+
envPdf > 0.0 &&
|
|
2687
|
+
isDirectionValid( envDirection, surf.normal, surf.faceNormal ) &&
|
|
2688
|
+
! attenuateHit( state, envRay, INFINITY, attenuatedColor )
|
|
2689
|
+
) {
|
|
2690
|
+
|
|
2691
|
+
// get the material pdf
|
|
2692
|
+
vec3 sampleColor;
|
|
2693
|
+
float envMaterialPdf = bsdfResult( worldWo, envDirection, surf, sampleColor );
|
|
2694
|
+
bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
|
|
2695
|
+
if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
|
|
2696
|
+
|
|
2697
|
+
// weight the direct light contribution
|
|
2698
|
+
envPdf /= lightsDenom;
|
|
2699
|
+
float misWeight = misHeuristic( envPdf, envMaterialPdf );
|
|
2700
|
+
result = attenuatedColor * environmentIntensity * envColor * state.throughputColor * sampleColor * misWeight / envPdf;
|
|
2701
|
+
|
|
2702
|
+
}
|
|
2703
|
+
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2706
|
+
}
|
|
2707
|
+
|
|
2708
|
+
// Function changed to have a single return statement to potentially help with crashes on Mac OS.
|
|
2709
|
+
// See issue #470
|
|
2710
|
+
return result;
|
|
2711
|
+
|
|
2712
|
+
}
|
|
2713
|
+
|
|
2714
|
+
`,io=`
|
|
2715
|
+
|
|
2716
|
+
#define SKIP_SURFACE 0
|
|
2717
|
+
#define HIT_SURFACE 1
|
|
2718
|
+
int getSurfaceRecord(
|
|
2719
|
+
Material material, SurfaceHit surfaceHit, sampler2DArray attributesArray,
|
|
2720
|
+
float accumulatedRoughness,
|
|
2721
|
+
inout SurfaceRecord surf
|
|
2722
|
+
) {
|
|
2723
|
+
|
|
2724
|
+
if ( material.fogVolume ) {
|
|
2725
|
+
|
|
2726
|
+
vec3 normal = vec3( 0, 0, 1 );
|
|
2727
|
+
|
|
2728
|
+
SurfaceRecord fogSurface;
|
|
2729
|
+
fogSurface.volumeParticle = true;
|
|
2730
|
+
fogSurface.color = material.color;
|
|
2731
|
+
fogSurface.emission = material.emissiveIntensity * material.emissive;
|
|
2732
|
+
fogSurface.normal = normal;
|
|
2733
|
+
fogSurface.faceNormal = normal;
|
|
2734
|
+
fogSurface.clearcoatNormal = normal;
|
|
2735
|
+
|
|
2736
|
+
surf = fogSurface;
|
|
2737
|
+
return HIT_SURFACE;
|
|
2738
|
+
|
|
2739
|
+
}
|
|
2740
|
+
|
|
2741
|
+
// uv coord for textures
|
|
2742
|
+
vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, surfaceHit.barycoord, surfaceHit.faceIndices.xyz ).xy;
|
|
2743
|
+
vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, surfaceHit.barycoord, surfaceHit.faceIndices.xyz );
|
|
2744
|
+
|
|
2745
|
+
// albedo
|
|
2746
|
+
vec4 albedo = vec4( material.color, material.opacity );
|
|
2747
|
+
if ( material.map != - 1 ) {
|
|
2748
|
+
|
|
2749
|
+
vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
|
|
2750
|
+
albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
|
|
2751
|
+
|
|
2752
|
+
}
|
|
2753
|
+
|
|
2754
|
+
if ( material.vertexColors ) {
|
|
2755
|
+
|
|
2756
|
+
albedo *= vertexColor;
|
|
2757
|
+
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2760
|
+
// alphaMap
|
|
2761
|
+
if ( material.alphaMap != - 1 ) {
|
|
2762
|
+
|
|
2763
|
+
albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
|
|
2764
|
+
|
|
2765
|
+
}
|
|
2766
|
+
|
|
2767
|
+
// possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
|
|
2768
|
+
// and it's single sided.
|
|
2769
|
+
// - alpha test is disabled when it === 0
|
|
2770
|
+
// - the material sidedness test is complicated because we want light to pass through the back side but still
|
|
2771
|
+
// be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
|
|
2772
|
+
// and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
|
|
2773
|
+
float alphaTest = material.alphaTest;
|
|
2774
|
+
bool useAlphaTest = alphaTest != 0.0;
|
|
2775
|
+
if (
|
|
2776
|
+
// material sidedness
|
|
2777
|
+
material.side != 0.0 && surfaceHit.side != material.side
|
|
2778
|
+
|
|
2779
|
+
// alpha test
|
|
2780
|
+
|| useAlphaTest && albedo.a < alphaTest
|
|
2781
|
+
|
|
2782
|
+
// opacity
|
|
2783
|
+
|| material.transparent && ! useAlphaTest && albedo.a < rand( 3 )
|
|
2784
|
+
) {
|
|
2785
|
+
|
|
2786
|
+
return SKIP_SURFACE;
|
|
2787
|
+
|
|
2788
|
+
}
|
|
2789
|
+
|
|
2790
|
+
// fetch the interpolated smooth normal
|
|
2791
|
+
vec3 normal = normalize( textureSampleBarycoord(
|
|
2792
|
+
attributesArray,
|
|
2793
|
+
ATTR_NORMAL,
|
|
2794
|
+
surfaceHit.barycoord,
|
|
2795
|
+
surfaceHit.faceIndices.xyz
|
|
2796
|
+
).xyz );
|
|
2797
|
+
|
|
2798
|
+
// roughness
|
|
2799
|
+
float roughness = material.roughness;
|
|
2800
|
+
if ( material.roughnessMap != - 1 ) {
|
|
2801
|
+
|
|
2802
|
+
vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
|
|
2803
|
+
roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
|
|
2804
|
+
|
|
2805
|
+
}
|
|
2806
|
+
|
|
2807
|
+
// metalness
|
|
2808
|
+
float metalness = material.metalness;
|
|
2809
|
+
if ( material.metalnessMap != - 1 ) {
|
|
2810
|
+
|
|
2811
|
+
vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
|
|
2812
|
+
metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
|
|
2813
|
+
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
// emission
|
|
2817
|
+
vec3 emission = material.emissiveIntensity * material.emissive;
|
|
2818
|
+
if ( material.emissiveMap != - 1 ) {
|
|
2819
|
+
|
|
2820
|
+
vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
|
|
2821
|
+
emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
|
|
2822
|
+
|
|
2823
|
+
}
|
|
2824
|
+
|
|
2825
|
+
// transmission
|
|
2826
|
+
float transmission = material.transmission;
|
|
2827
|
+
if ( material.transmissionMap != - 1 ) {
|
|
2828
|
+
|
|
2829
|
+
vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
|
|
2830
|
+
transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
|
|
2831
|
+
|
|
2832
|
+
}
|
|
2833
|
+
|
|
2834
|
+
// normal
|
|
2835
|
+
if ( material.flatShading ) {
|
|
2836
|
+
|
|
2837
|
+
// if we're rendering a flat shaded object then use the face normals - the face normal
|
|
2838
|
+
// is provided based on the side the ray hits the mesh so flip it to align with the
|
|
2839
|
+
// interpolated vertex normals.
|
|
2840
|
+
normal = surfaceHit.faceNormal * surfaceHit.side;
|
|
2841
|
+
|
|
2842
|
+
}
|
|
2843
|
+
|
|
2844
|
+
vec3 baseNormal = normal;
|
|
2845
|
+
if ( material.normalMap != - 1 ) {
|
|
2846
|
+
|
|
2847
|
+
vec4 tangentSample = textureSampleBarycoord(
|
|
2848
|
+
attributesArray,
|
|
2849
|
+
ATTR_TANGENT,
|
|
2850
|
+
surfaceHit.barycoord,
|
|
2851
|
+
surfaceHit.faceIndices.xyz
|
|
2852
|
+
);
|
|
2853
|
+
|
|
2854
|
+
// some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
|
|
2855
|
+
// resulting in NaNs and slow path tracing.
|
|
2856
|
+
if ( length( tangentSample.xyz ) > 0.0 ) {
|
|
2857
|
+
|
|
2858
|
+
vec3 tangent = normalize( tangentSample.xyz );
|
|
2859
|
+
vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
|
|
2860
|
+
mat3 vTBN = mat3( tangent, bitangent, normal );
|
|
2861
|
+
|
|
2862
|
+
vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
|
|
2863
|
+
vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
|
|
2864
|
+
texNormal.xy *= material.normalScale;
|
|
2865
|
+
normal = vTBN * texNormal;
|
|
2866
|
+
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
}
|
|
2870
|
+
|
|
2871
|
+
normal *= surfaceHit.side;
|
|
2872
|
+
|
|
2873
|
+
// clearcoat
|
|
2874
|
+
float clearcoat = material.clearcoat;
|
|
2875
|
+
if ( material.clearcoatMap != - 1 ) {
|
|
2876
|
+
|
|
2877
|
+
vec3 uvPrime = material.clearcoatMapTransform * vec3( uv, 1 );
|
|
2878
|
+
clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatMap ) ).r;
|
|
2879
|
+
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
// clearcoatRoughness
|
|
2883
|
+
float clearcoatRoughness = material.clearcoatRoughness;
|
|
2884
|
+
if ( material.clearcoatRoughnessMap != - 1 ) {
|
|
2885
|
+
|
|
2886
|
+
vec3 uvPrime = material.clearcoatRoughnessMapTransform * vec3( uv, 1 );
|
|
2887
|
+
clearcoatRoughness *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatRoughnessMap ) ).g;
|
|
2888
|
+
|
|
2889
|
+
}
|
|
2890
|
+
|
|
2891
|
+
// clearcoatNormal
|
|
2892
|
+
vec3 clearcoatNormal = baseNormal;
|
|
2893
|
+
if ( material.clearcoatNormalMap != - 1 ) {
|
|
2894
|
+
|
|
2895
|
+
vec4 tangentSample = textureSampleBarycoord(
|
|
2896
|
+
attributesArray,
|
|
2897
|
+
ATTR_TANGENT,
|
|
2898
|
+
surfaceHit.barycoord,
|
|
2899
|
+
surfaceHit.faceIndices.xyz
|
|
2900
|
+
);
|
|
2901
|
+
|
|
2902
|
+
// some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
|
|
2903
|
+
// resulting in NaNs and slow path tracing.
|
|
2904
|
+
if ( length( tangentSample.xyz ) > 0.0 ) {
|
|
2905
|
+
|
|
2906
|
+
vec3 tangent = normalize( tangentSample.xyz );
|
|
2907
|
+
vec3 bitangent = normalize( cross( clearcoatNormal, tangent ) * tangentSample.w );
|
|
2908
|
+
mat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );
|
|
2909
|
+
|
|
2910
|
+
vec3 uvPrime = material.clearcoatNormalMapTransform * vec3( uv, 1 );
|
|
2911
|
+
vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.clearcoatNormalMap ) ).xyz * 2.0 - 1.0;
|
|
2912
|
+
texNormal.xy *= material.clearcoatNormalScale;
|
|
2913
|
+
clearcoatNormal = vTBN * texNormal;
|
|
2914
|
+
|
|
2915
|
+
}
|
|
2916
|
+
|
|
2917
|
+
}
|
|
2918
|
+
|
|
2919
|
+
clearcoatNormal *= surfaceHit.side;
|
|
2920
|
+
|
|
2921
|
+
// sheenColor
|
|
2922
|
+
vec3 sheenColor = material.sheenColor;
|
|
2923
|
+
if ( material.sheenColorMap != - 1 ) {
|
|
2924
|
+
|
|
2925
|
+
vec3 uvPrime = material.sheenColorMapTransform * vec3( uv, 1 );
|
|
2926
|
+
sheenColor *= texture2D( textures, vec3( uvPrime.xy, material.sheenColorMap ) ).rgb;
|
|
2927
|
+
|
|
2928
|
+
}
|
|
2929
|
+
|
|
2930
|
+
// sheenRoughness
|
|
2931
|
+
float sheenRoughness = material.sheenRoughness;
|
|
2932
|
+
if ( material.sheenRoughnessMap != - 1 ) {
|
|
2933
|
+
|
|
2934
|
+
vec3 uvPrime = material.sheenRoughnessMapTransform * vec3( uv, 1 );
|
|
2935
|
+
sheenRoughness *= texture2D( textures, vec3( uvPrime.xy, material.sheenRoughnessMap ) ).a;
|
|
2936
|
+
|
|
2937
|
+
}
|
|
2938
|
+
|
|
2939
|
+
// iridescence
|
|
2940
|
+
float iridescence = material.iridescence;
|
|
2941
|
+
if ( material.iridescenceMap != - 1 ) {
|
|
2942
|
+
|
|
2943
|
+
vec3 uvPrime = material.iridescenceMapTransform * vec3( uv, 1 );
|
|
2944
|
+
iridescence *= texture2D( textures, vec3( uvPrime.xy, material.iridescenceMap ) ).r;
|
|
2945
|
+
|
|
2946
|
+
}
|
|
2947
|
+
|
|
2948
|
+
// iridescence thickness
|
|
2949
|
+
float iridescenceThickness = material.iridescenceThicknessMaximum;
|
|
2950
|
+
if ( material.iridescenceThicknessMap != - 1 ) {
|
|
2951
|
+
|
|
2952
|
+
vec3 uvPrime = material.iridescenceThicknessMapTransform * vec3( uv, 1 );
|
|
2953
|
+
float iridescenceThicknessSampled = texture2D( textures, vec3( uvPrime.xy, material.iridescenceThicknessMap ) ).g;
|
|
2954
|
+
iridescenceThickness = mix( material.iridescenceThicknessMinimum, material.iridescenceThicknessMaximum, iridescenceThicknessSampled );
|
|
2955
|
+
|
|
2956
|
+
}
|
|
2957
|
+
|
|
2958
|
+
iridescence = iridescenceThickness == 0.0 ? 0.0 : iridescence;
|
|
2959
|
+
|
|
2960
|
+
// specular color
|
|
2961
|
+
vec3 specularColor = material.specularColor;
|
|
2962
|
+
if ( material.specularColorMap != - 1 ) {
|
|
2963
|
+
|
|
2964
|
+
vec3 uvPrime = material.specularColorMapTransform * vec3( uv, 1 );
|
|
2965
|
+
specularColor *= texture2D( textures, vec3( uvPrime.xy, material.specularColorMap ) ).rgb;
|
|
2966
|
+
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2969
|
+
// specular intensity
|
|
2970
|
+
float specularIntensity = material.specularIntensity;
|
|
2971
|
+
if ( material.specularIntensityMap != - 1 ) {
|
|
2972
|
+
|
|
2973
|
+
vec3 uvPrime = material.specularIntensityMapTransform * vec3( uv, 1 );
|
|
2974
|
+
specularIntensity *= texture2D( textures, vec3( uvPrime.xy, material.specularIntensityMap ) ).a;
|
|
2975
|
+
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2978
|
+
surf.volumeParticle = false;
|
|
2979
|
+
|
|
2980
|
+
surf.faceNormal = surfaceHit.faceNormal;
|
|
2981
|
+
surf.normal = normal;
|
|
2982
|
+
|
|
2983
|
+
surf.metalness = metalness;
|
|
2984
|
+
surf.color = albedo.rgb;
|
|
2985
|
+
surf.emission = emission;
|
|
2986
|
+
|
|
2987
|
+
surf.ior = material.ior;
|
|
2988
|
+
surf.transmission = transmission;
|
|
2989
|
+
surf.thinFilm = material.thinFilm;
|
|
2990
|
+
surf.attenuationColor = material.attenuationColor;
|
|
2991
|
+
surf.attenuationDistance = material.attenuationDistance;
|
|
2992
|
+
|
|
2993
|
+
surf.clearcoatNormal = clearcoatNormal;
|
|
2994
|
+
surf.clearcoat = clearcoat;
|
|
2995
|
+
|
|
2996
|
+
surf.sheen = material.sheen;
|
|
2997
|
+
surf.sheenColor = sheenColor;
|
|
2998
|
+
|
|
2999
|
+
surf.iridescence = iridescence;
|
|
3000
|
+
surf.iridescenceIor = material.iridescenceIor;
|
|
3001
|
+
surf.iridescenceThickness = iridescenceThickness;
|
|
3002
|
+
|
|
3003
|
+
surf.specularColor = specularColor;
|
|
3004
|
+
surf.specularIntensity = specularIntensity;
|
|
3005
|
+
|
|
3006
|
+
// apply perceptual roughness factor from gltf. sheen perceptual roughness is
|
|
3007
|
+
// applied by its brdf function
|
|
3008
|
+
// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces
|
|
3009
|
+
surf.roughness = roughness * roughness;
|
|
3010
|
+
surf.clearcoatRoughness = clearcoatRoughness * clearcoatRoughness;
|
|
3011
|
+
surf.sheenRoughness = sheenRoughness;
|
|
3012
|
+
|
|
3013
|
+
// frontFace is used to determine transmissive properties and PDF. If no transmission is used
|
|
3014
|
+
// then we can just always assume this is a front face.
|
|
3015
|
+
surf.frontFace = surfaceHit.side == 1.0 || transmission == 0.0;
|
|
3016
|
+
surf.eta = material.thinFilm || surf.frontFace ? 1.0 / material.ior : material.ior;
|
|
3017
|
+
surf.f0 = iorRatioToF0( surf.eta );
|
|
3018
|
+
|
|
3019
|
+
// Compute the filtered roughness value to use during specular reflection computations.
|
|
3020
|
+
// The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
|
|
3021
|
+
// If we're exiting something transmissive then scale the factor down significantly so we can retain
|
|
3022
|
+
// sharp internal reflections
|
|
3023
|
+
surf.filteredRoughness = applyFilteredGlossy( surf.roughness, accumulatedRoughness );
|
|
3024
|
+
surf.filteredClearcoatRoughness = applyFilteredGlossy( surf.clearcoatRoughness, accumulatedRoughness );
|
|
3025
|
+
|
|
3026
|
+
// get the normal frames
|
|
3027
|
+
surf.normalBasis = getBasisFromNormal( surf.normal );
|
|
3028
|
+
surf.normalInvBasis = inverse( surf.normalBasis );
|
|
3029
|
+
|
|
3030
|
+
surf.clearcoatBasis = getBasisFromNormal( surf.clearcoatNormal );
|
|
3031
|
+
surf.clearcoatInvBasis = inverse( surf.clearcoatBasis );
|
|
3032
|
+
|
|
3033
|
+
return HIT_SURFACE;
|
|
3034
|
+
|
|
3035
|
+
}
|
|
3036
|
+
`,so=`
|
|
3037
|
+
|
|
3038
|
+
struct Ray {
|
|
3039
|
+
|
|
3040
|
+
vec3 origin;
|
|
3041
|
+
vec3 direction;
|
|
3042
|
+
|
|
3043
|
+
};
|
|
3044
|
+
|
|
3045
|
+
struct SurfaceHit {
|
|
3046
|
+
|
|
3047
|
+
uvec4 faceIndices;
|
|
3048
|
+
vec3 barycoord;
|
|
3049
|
+
vec3 faceNormal;
|
|
3050
|
+
float side;
|
|
3051
|
+
float dist;
|
|
3052
|
+
|
|
3053
|
+
};
|
|
3054
|
+
|
|
3055
|
+
struct RenderState {
|
|
3056
|
+
|
|
3057
|
+
bool firstRay;
|
|
3058
|
+
bool transmissiveRay;
|
|
3059
|
+
bool isShadowRay;
|
|
3060
|
+
float accumulatedRoughness;
|
|
3061
|
+
int transmissiveTraversals;
|
|
3062
|
+
int traversals;
|
|
3063
|
+
uint depth;
|
|
3064
|
+
vec3 throughputColor;
|
|
3065
|
+
Material fogMaterial;
|
|
3066
|
+
|
|
3067
|
+
};
|
|
3068
|
+
|
|
3069
|
+
RenderState initRenderState() {
|
|
3070
|
+
|
|
3071
|
+
RenderState result;
|
|
3072
|
+
result.firstRay = true;
|
|
3073
|
+
result.transmissiveRay = true;
|
|
3074
|
+
result.isShadowRay = false;
|
|
3075
|
+
result.accumulatedRoughness = 0.0;
|
|
3076
|
+
result.transmissiveTraversals = 0;
|
|
3077
|
+
result.traversals = 0;
|
|
3078
|
+
result.throughputColor = vec3( 1.0 );
|
|
3079
|
+
result.depth = 0u;
|
|
3080
|
+
result.fogMaterial.fogVolume = false;
|
|
3081
|
+
return result;
|
|
3082
|
+
|
|
3083
|
+
}
|
|
3084
|
+
|
|
3085
|
+
`,ro=`
|
|
3086
|
+
|
|
3087
|
+
#define NO_HIT 0
|
|
3088
|
+
#define SURFACE_HIT 1
|
|
3089
|
+
#define LIGHT_HIT 2
|
|
3090
|
+
#define FOG_HIT 3
|
|
3091
|
+
|
|
3092
|
+
// Passing the global variable 'lights' into this function caused shader program errors.
|
|
3093
|
+
// So global variables like 'lights' and 'bvh' were moved out of the function parameters.
|
|
3094
|
+
// For more information, refer to: https://github.com/gkjohnson/three-gpu-pathtracer/pull/457
|
|
3095
|
+
int traceScene(
|
|
3096
|
+
Ray ray, Material fogMaterial, inout SurfaceHit surfaceHit
|
|
3097
|
+
) {
|
|
3098
|
+
|
|
3099
|
+
int result = NO_HIT;
|
|
3100
|
+
bool hit = bvhIntersectFirstHit( bvh, ray.origin, ray.direction, surfaceHit.faceIndices, surfaceHit.faceNormal, surfaceHit.barycoord, surfaceHit.side, surfaceHit.dist );
|
|
3101
|
+
|
|
3102
|
+
#if FEATURE_FOG
|
|
3103
|
+
|
|
3104
|
+
if ( fogMaterial.fogVolume ) {
|
|
3105
|
+
|
|
3106
|
+
// offset the distance so we don't run into issues with particles on the same surface
|
|
3107
|
+
// as other objects
|
|
3108
|
+
float particleDist = intersectFogVolume( fogMaterial, rand( 1 ) );
|
|
3109
|
+
if ( particleDist + RAY_OFFSET < surfaceHit.dist ) {
|
|
3110
|
+
|
|
3111
|
+
surfaceHit.side = 1.0;
|
|
3112
|
+
surfaceHit.faceNormal = normalize( - ray.direction );
|
|
3113
|
+
surfaceHit.dist = particleDist;
|
|
3114
|
+
return FOG_HIT;
|
|
3115
|
+
|
|
3116
|
+
}
|
|
3117
|
+
|
|
3118
|
+
}
|
|
3119
|
+
|
|
3120
|
+
#endif
|
|
3121
|
+
|
|
3122
|
+
if ( hit ) {
|
|
3123
|
+
|
|
3124
|
+
result = SURFACE_HIT;
|
|
3125
|
+
|
|
3126
|
+
}
|
|
3127
|
+
|
|
3128
|
+
return result;
|
|
3129
|
+
|
|
3130
|
+
}
|
|
3131
|
+
|
|
3132
|
+
`;class no extends Ii{onBeforeRender(){this.setDefine("FEATURE_DOF",this.physicalCamera.bokehSize===0?0:1),this.setDefine("FEATURE_BACKGROUND_MAP",this.backgroundMap?1:0),this.setDefine("FEATURE_FOG",this.materials.features.isUsed("FOG")?1:0)}constructor(e){super({transparent:!0,depthWrite:!1,defines:{FEATURE_MIS:1,FEATURE_RUSSIAN_ROULETTE:1,FEATURE_DOF:1,FEATURE_BACKGROUND_MAP:0,FEATURE_FOG:1,RANDOM_TYPE:2,CAMERA_TYPE:0,DEBUG_MODE:0,ATTR_NORMAL:0,ATTR_TANGENT:1,ATTR_UV:2,ATTR_COLOR:3},uniforms:{resolution:{value:new d.Vector2},opacity:{value:1},bounces:{value:10},transmissiveBounces:{value:10},filterGlossyFactor:{value:0},physicalCamera:{value:new en},cameraWorldMatrix:{value:new d.Matrix4},invProjectionMatrix:{value:new d.Matrix4},bvh:{value:new ue.MeshBVHUniformStruct},attributesArray:{value:new dn},materialIndexAttribute:{value:new ue.UIntVertexAttributeTexture},materials:{value:new yn},textures:{value:new ss().texture},lights:{value:new un},iesProfiles:{value:new ss(360,180,{type:d.HalfFloatType,wrapS:d.ClampToEdgeWrapping,wrapT:d.ClampToEdgeWrapping}).texture},environmentIntensity:{value:1},environmentRotation:{value:new d.Matrix4},envMapInfo:{value:new rn},backgroundBlur:{value:0},backgroundMap:{value:null},backgroundAlpha:{value:1},backgroundIntensity:{value:1},backgroundRotation:{value:new d.Matrix4},seed:{value:0},sobolTexture:{value:null},stratifiedTexture:{value:new Mn},stratifiedOffsetTexture:{value:new Dn(64,1)}},vertexShader:`
|
|
3133
|
+
|
|
3134
|
+
varying vec2 vUv;
|
|
3135
|
+
void main() {
|
|
3136
|
+
|
|
3137
|
+
vec4 mvPosition = vec4( position, 1.0 );
|
|
3138
|
+
mvPosition = modelViewMatrix * mvPosition;
|
|
3139
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
3140
|
+
|
|
3141
|
+
vUv = uv;
|
|
3142
|
+
|
|
3143
|
+
}
|
|
3144
|
+
|
|
3145
|
+
`,fragmentShader:`
|
|
3146
|
+
#define RAY_OFFSET 1e-4
|
|
3147
|
+
#define INFINITY 1e20
|
|
3148
|
+
|
|
3149
|
+
precision highp isampler2D;
|
|
3150
|
+
precision highp usampler2D;
|
|
3151
|
+
precision highp sampler2DArray;
|
|
3152
|
+
vec4 envMapTexelToLinear( vec4 a ) { return a; }
|
|
3153
|
+
#include <common>
|
|
3154
|
+
|
|
3155
|
+
// bvh intersection
|
|
3156
|
+
${ue.BVHShaderGLSL.common_functions}
|
|
3157
|
+
${ue.BVHShaderGLSL.bvh_struct_definitions}
|
|
3158
|
+
${ue.BVHShaderGLSL.bvh_ray_functions}
|
|
3159
|
+
|
|
3160
|
+
// uniform structs
|
|
3161
|
+
${Bn}
|
|
3162
|
+
${kn}
|
|
3163
|
+
${Ln}
|
|
3164
|
+
${On}
|
|
3165
|
+
${zn}
|
|
3166
|
+
|
|
3167
|
+
// random
|
|
3168
|
+
#if RANDOM_TYPE == 2 // Stratified List
|
|
3169
|
+
|
|
3170
|
+
${qn}
|
|
3171
|
+
|
|
3172
|
+
#elif RANDOM_TYPE == 1 // Sobol
|
|
3173
|
+
|
|
3174
|
+
${ns}
|
|
3175
|
+
${Hs}
|
|
3176
|
+
${Xr}
|
|
3177
|
+
|
|
3178
|
+
#define rand(v) sobol(v)
|
|
3179
|
+
#define rand2(v) sobol2(v)
|
|
3180
|
+
#define rand3(v) sobol3(v)
|
|
3181
|
+
#define rand4(v) sobol4(v)
|
|
3182
|
+
|
|
3183
|
+
#else // PCG
|
|
3184
|
+
|
|
3185
|
+
${ns}
|
|
3186
|
+
|
|
3187
|
+
// Using the sobol functions seems to break the the compiler on MacOS
|
|
3188
|
+
// - specifically the "sobolReverseBits" function.
|
|
3189
|
+
uint sobolPixelIndex = 0u;
|
|
3190
|
+
uint sobolPathIndex = 0u;
|
|
3191
|
+
uint sobolBounceIndex = 0u;
|
|
3192
|
+
|
|
3193
|
+
#define rand(v) pcgRand()
|
|
3194
|
+
#define rand2(v) pcgRand2()
|
|
3195
|
+
#define rand3(v) pcgRand3()
|
|
3196
|
+
#define rand4(v) pcgRand4()
|
|
3197
|
+
|
|
3198
|
+
#endif
|
|
3199
|
+
|
|
3200
|
+
// common
|
|
3201
|
+
${jn}
|
|
3202
|
+
${Nn}
|
|
3203
|
+
${Ws}
|
|
3204
|
+
${Wn}
|
|
3205
|
+
${Gn}
|
|
3206
|
+
|
|
3207
|
+
// environment
|
|
3208
|
+
uniform EquirectHdrInfo envMapInfo;
|
|
3209
|
+
uniform mat4 environmentRotation;
|
|
3210
|
+
uniform float environmentIntensity;
|
|
3211
|
+
|
|
3212
|
+
// lighting
|
|
3213
|
+
uniform sampler2DArray iesProfiles;
|
|
3214
|
+
uniform LightsInfo lights;
|
|
3215
|
+
|
|
3216
|
+
// background
|
|
3217
|
+
uniform float backgroundBlur;
|
|
3218
|
+
uniform float backgroundAlpha;
|
|
3219
|
+
#if FEATURE_BACKGROUND_MAP
|
|
3220
|
+
|
|
3221
|
+
uniform sampler2D backgroundMap;
|
|
3222
|
+
uniform mat4 backgroundRotation;
|
|
3223
|
+
uniform float backgroundIntensity;
|
|
3224
|
+
|
|
3225
|
+
#endif
|
|
3226
|
+
|
|
3227
|
+
// camera
|
|
3228
|
+
uniform mat4 cameraWorldMatrix;
|
|
3229
|
+
uniform mat4 invProjectionMatrix;
|
|
3230
|
+
#if FEATURE_DOF
|
|
3231
|
+
|
|
3232
|
+
uniform PhysicalCamera physicalCamera;
|
|
3233
|
+
|
|
3234
|
+
#endif
|
|
3235
|
+
|
|
3236
|
+
// geometry
|
|
3237
|
+
uniform sampler2DArray attributesArray;
|
|
3238
|
+
uniform usampler2D materialIndexAttribute;
|
|
3239
|
+
uniform sampler2D materials;
|
|
3240
|
+
uniform sampler2DArray textures;
|
|
3241
|
+
uniform BVH bvh;
|
|
3242
|
+
|
|
3243
|
+
// path tracer
|
|
3244
|
+
uniform int bounces;
|
|
3245
|
+
uniform int transmissiveBounces;
|
|
3246
|
+
uniform float filterGlossyFactor;
|
|
3247
|
+
uniform int seed;
|
|
3248
|
+
|
|
3249
|
+
// image
|
|
3250
|
+
uniform vec2 resolution;
|
|
3251
|
+
uniform float opacity;
|
|
3252
|
+
|
|
3253
|
+
varying vec2 vUv;
|
|
3254
|
+
|
|
3255
|
+
// globals
|
|
3256
|
+
mat3 envRotation3x3;
|
|
3257
|
+
mat3 invEnvRotation3x3;
|
|
3258
|
+
float lightsDenom;
|
|
3259
|
+
|
|
3260
|
+
// sampling
|
|
3261
|
+
${Hn}
|
|
3262
|
+
${Vn}
|
|
3263
|
+
${Un}
|
|
3264
|
+
|
|
3265
|
+
${Kn}
|
|
3266
|
+
${Zn}
|
|
3267
|
+
${Jn}
|
|
3268
|
+
${Xn}
|
|
3269
|
+
${Qn}
|
|
3270
|
+
${Yn}
|
|
3271
|
+
|
|
3272
|
+
float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
|
|
3273
|
+
|
|
3274
|
+
return clamp(
|
|
3275
|
+
max(
|
|
3276
|
+
roughness,
|
|
3277
|
+
accumulatedRoughness * filterGlossyFactor * 5.0 ),
|
|
3278
|
+
0.0,
|
|
3279
|
+
1.0
|
|
3280
|
+
);
|
|
3281
|
+
|
|
3282
|
+
}
|
|
3283
|
+
|
|
3284
|
+
vec3 sampleBackground( vec3 direction, vec2 uv ) {
|
|
3285
|
+
|
|
3286
|
+
vec3 sampleDir = sampleHemisphere( direction, uv ) * 0.5 * backgroundBlur;
|
|
3287
|
+
|
|
3288
|
+
#if FEATURE_BACKGROUND_MAP
|
|
3289
|
+
|
|
3290
|
+
sampleDir = normalize( mat3( backgroundRotation ) * direction + sampleDir );
|
|
3291
|
+
return backgroundIntensity * sampleEquirectColor( backgroundMap, sampleDir );
|
|
3292
|
+
|
|
3293
|
+
#else
|
|
3294
|
+
|
|
3295
|
+
sampleDir = normalize( envRotation3x3 * direction + sampleDir );
|
|
3296
|
+
return environmentIntensity * sampleEquirectColor( envMapInfo.map, sampleDir );
|
|
3297
|
+
|
|
3298
|
+
#endif
|
|
3299
|
+
|
|
3300
|
+
}
|
|
3301
|
+
|
|
3302
|
+
${so}
|
|
3303
|
+
${eo}
|
|
3304
|
+
${ro}
|
|
3305
|
+
${$n}
|
|
3306
|
+
${to}
|
|
3307
|
+
${io}
|
|
3308
|
+
|
|
3309
|
+
void main() {
|
|
3310
|
+
|
|
3311
|
+
// init
|
|
3312
|
+
rng_initialize( gl_FragCoord.xy, seed );
|
|
3313
|
+
sobolPixelIndex = ( uint( gl_FragCoord.x ) << 16 ) | uint( gl_FragCoord.y );
|
|
3314
|
+
sobolPathIndex = uint( seed );
|
|
3315
|
+
|
|
3316
|
+
// get camera ray
|
|
3317
|
+
Ray ray = getCameraRay();
|
|
3318
|
+
|
|
3319
|
+
// inverse environment rotation
|
|
3320
|
+
envRotation3x3 = mat3( environmentRotation );
|
|
3321
|
+
invEnvRotation3x3 = inverse( envRotation3x3 );
|
|
3322
|
+
lightsDenom =
|
|
3323
|
+
( environmentIntensity == 0.0 || envMapInfo.totalSum == 0.0 ) && lights.count != 0u ?
|
|
3324
|
+
float( lights.count ) :
|
|
3325
|
+
float( lights.count + 1u );
|
|
3326
|
+
|
|
3327
|
+
// final color
|
|
3328
|
+
gl_FragColor = vec4( 0, 0, 0, 1 );
|
|
3329
|
+
|
|
3330
|
+
// surface results
|
|
3331
|
+
SurfaceHit surfaceHit;
|
|
3332
|
+
ScatterRecord scatterRec;
|
|
3333
|
+
|
|
3334
|
+
// path tracing state
|
|
3335
|
+
RenderState state = initRenderState();
|
|
3336
|
+
state.transmissiveTraversals = transmissiveBounces;
|
|
3337
|
+
#if FEATURE_FOG
|
|
3338
|
+
|
|
3339
|
+
state.fogMaterial.fogVolume = bvhIntersectFogVolumeHit(
|
|
3340
|
+
ray.origin, - ray.direction,
|
|
3341
|
+
materialIndexAttribute, materials,
|
|
3342
|
+
state.fogMaterial
|
|
3343
|
+
);
|
|
3344
|
+
|
|
3345
|
+
#endif
|
|
3346
|
+
|
|
3347
|
+
for ( int i = 0; i < bounces; i ++ ) {
|
|
3348
|
+
|
|
3349
|
+
sobolBounceIndex ++;
|
|
3350
|
+
|
|
3351
|
+
state.depth ++;
|
|
3352
|
+
state.traversals = bounces - i;
|
|
3353
|
+
state.firstRay = i == 0 && state.transmissiveTraversals == transmissiveBounces;
|
|
3354
|
+
|
|
3355
|
+
int hitType = traceScene( ray, state.fogMaterial, surfaceHit );
|
|
3356
|
+
|
|
3357
|
+
// check if we intersect any lights and accumulate the light contribution
|
|
3358
|
+
// TODO: we can add support for light surface rendering in the else condition if we
|
|
3359
|
+
// add the ability to toggle visibility of the the light
|
|
3360
|
+
if ( ! state.firstRay && ! state.transmissiveRay ) {
|
|
3361
|
+
|
|
3362
|
+
LightRecord lightRec;
|
|
3363
|
+
float lightDist = hitType == NO_HIT ? INFINITY : surfaceHit.dist;
|
|
3364
|
+
for ( uint i = 0u; i < lights.count; i ++ ) {
|
|
3365
|
+
|
|
3366
|
+
if (
|
|
3367
|
+
intersectLightAtIndex( lights.tex, ray.origin, ray.direction, i, lightRec ) &&
|
|
3368
|
+
lightRec.dist < lightDist
|
|
3369
|
+
) {
|
|
3370
|
+
|
|
3371
|
+
#if FEATURE_MIS
|
|
3372
|
+
|
|
3373
|
+
// weight the contribution
|
|
3374
|
+
// NOTE: Only area lights are supported for forward sampling and can be hit
|
|
3375
|
+
float misWeight = misHeuristic( scatterRec.pdf, lightRec.pdf / lightsDenom );
|
|
3376
|
+
gl_FragColor.rgb += lightRec.emission * state.throughputColor * misWeight;
|
|
3377
|
+
|
|
3378
|
+
#else
|
|
3379
|
+
|
|
3380
|
+
gl_FragColor.rgb += lightRec.emission * state.throughputColor;
|
|
3381
|
+
|
|
3382
|
+
#endif
|
|
3383
|
+
|
|
3384
|
+
}
|
|
3385
|
+
|
|
3386
|
+
}
|
|
3387
|
+
|
|
3388
|
+
}
|
|
3389
|
+
|
|
3390
|
+
if ( hitType == NO_HIT ) {
|
|
3391
|
+
|
|
3392
|
+
if ( state.firstRay || state.transmissiveRay ) {
|
|
3393
|
+
|
|
3394
|
+
gl_FragColor.rgb += sampleBackground( ray.direction, rand2( 2 ) ) * state.throughputColor;
|
|
3395
|
+
gl_FragColor.a = backgroundAlpha;
|
|
3396
|
+
|
|
3397
|
+
} else {
|
|
3398
|
+
|
|
3399
|
+
#if FEATURE_MIS
|
|
3400
|
+
|
|
3401
|
+
// get the PDF of the hit envmap point
|
|
3402
|
+
vec3 envColor;
|
|
3403
|
+
float envPdf = sampleEquirect( envRotation3x3 * ray.direction, envColor );
|
|
3404
|
+
envPdf /= lightsDenom;
|
|
3405
|
+
|
|
3406
|
+
// and weight the contribution
|
|
3407
|
+
float misWeight = misHeuristic( scatterRec.pdf, envPdf );
|
|
3408
|
+
gl_FragColor.rgb += environmentIntensity * envColor * state.throughputColor * misWeight;
|
|
3409
|
+
|
|
3410
|
+
#else
|
|
3411
|
+
|
|
3412
|
+
gl_FragColor.rgb +=
|
|
3413
|
+
environmentIntensity *
|
|
3414
|
+
sampleEquirectColor( envMapInfo.map, envRotation3x3 * ray.direction ) *
|
|
3415
|
+
state.throughputColor;
|
|
3416
|
+
|
|
3417
|
+
#endif
|
|
3418
|
+
|
|
3419
|
+
}
|
|
3420
|
+
break;
|
|
3421
|
+
|
|
3422
|
+
}
|
|
3423
|
+
|
|
3424
|
+
uint materialIndex = uTexelFetch1D( materialIndexAttribute, surfaceHit.faceIndices.x ).r;
|
|
3425
|
+
Material material = readMaterialInfo( materials, materialIndex );
|
|
3426
|
+
|
|
3427
|
+
#if FEATURE_FOG
|
|
3428
|
+
|
|
3429
|
+
if ( hitType == FOG_HIT ) {
|
|
3430
|
+
|
|
3431
|
+
material = state.fogMaterial;
|
|
3432
|
+
state.accumulatedRoughness += 0.2;
|
|
3433
|
+
|
|
3434
|
+
} else if ( material.fogVolume ) {
|
|
3435
|
+
|
|
3436
|
+
state.fogMaterial = material;
|
|
3437
|
+
state.fogMaterial.fogVolume = surfaceHit.side == 1.0;
|
|
3438
|
+
|
|
3439
|
+
ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
|
|
3440
|
+
|
|
3441
|
+
i -= sign( state.transmissiveTraversals );
|
|
3442
|
+
state.transmissiveTraversals -= sign( state.transmissiveTraversals );
|
|
3443
|
+
continue;
|
|
3444
|
+
|
|
3445
|
+
}
|
|
3446
|
+
|
|
3447
|
+
#endif
|
|
3448
|
+
|
|
3449
|
+
// early out if this is a matte material
|
|
3450
|
+
if ( material.matte && state.firstRay ) {
|
|
3451
|
+
|
|
3452
|
+
gl_FragColor = vec4( 0.0 );
|
|
3453
|
+
break;
|
|
3454
|
+
|
|
3455
|
+
}
|
|
3456
|
+
|
|
3457
|
+
// if we've determined that this is a shadow ray and we've hit an item with no shadow casting
|
|
3458
|
+
// then skip it
|
|
3459
|
+
if ( ! material.castShadow && state.isShadowRay ) {
|
|
3460
|
+
|
|
3461
|
+
ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
|
|
3462
|
+
continue;
|
|
3463
|
+
|
|
3464
|
+
}
|
|
3465
|
+
|
|
3466
|
+
SurfaceRecord surf;
|
|
3467
|
+
if (
|
|
3468
|
+
getSurfaceRecord(
|
|
3469
|
+
material, surfaceHit, attributesArray, state.accumulatedRoughness,
|
|
3470
|
+
surf
|
|
3471
|
+
) == SKIP_SURFACE
|
|
3472
|
+
) {
|
|
3473
|
+
|
|
3474
|
+
// only allow a limited number of transparency discards otherwise we could
|
|
3475
|
+
// crash the context with too long a loop.
|
|
3476
|
+
i -= sign( state.transmissiveTraversals );
|
|
3477
|
+
state.transmissiveTraversals -= sign( state.transmissiveTraversals );
|
|
3478
|
+
|
|
3479
|
+
ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
|
|
3480
|
+
continue;
|
|
3481
|
+
|
|
3482
|
+
}
|
|
3483
|
+
|
|
3484
|
+
scatterRec = bsdfSample( - ray.direction, surf );
|
|
3485
|
+
state.isShadowRay = scatterRec.specularPdf < rand( 4 );
|
|
3486
|
+
|
|
3487
|
+
bool isBelowSurface = ! surf.volumeParticle && dot( scatterRec.direction, surf.faceNormal ) < 0.0;
|
|
3488
|
+
vec3 hitPoint = stepRayOrigin( ray.origin, ray.direction, isBelowSurface ? - surf.faceNormal : surf.faceNormal, surfaceHit.dist );
|
|
3489
|
+
|
|
3490
|
+
// next event estimation
|
|
3491
|
+
#if FEATURE_MIS
|
|
3492
|
+
|
|
3493
|
+
gl_FragColor.rgb += directLightContribution( - ray.direction, surf, state, hitPoint );
|
|
3494
|
+
|
|
3495
|
+
#endif
|
|
3496
|
+
|
|
3497
|
+
// accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
|
|
3498
|
+
// to a single pixel resulting in fireflies
|
|
3499
|
+
// TODO: handle transmissive surfaces
|
|
3500
|
+
if ( ! surf.volumeParticle && ! isBelowSurface ) {
|
|
3501
|
+
|
|
3502
|
+
// determine if this is a rough normal or not by checking how far off straight up it is
|
|
3503
|
+
vec3 halfVector = normalize( - ray.direction + scatterRec.direction );
|
|
3504
|
+
state.accumulatedRoughness += max(
|
|
3505
|
+
sin( acosApprox( dot( halfVector, surf.normal ) ) ),
|
|
3506
|
+
sin( acosApprox( dot( halfVector, surf.clearcoatNormal ) ) )
|
|
3507
|
+
);
|
|
3508
|
+
|
|
3509
|
+
state.transmissiveRay = false;
|
|
3510
|
+
|
|
3511
|
+
}
|
|
3512
|
+
|
|
3513
|
+
// accumulate emissive color
|
|
3514
|
+
gl_FragColor.rgb += ( surf.emission * state.throughputColor );
|
|
3515
|
+
|
|
3516
|
+
// skip the sample if our PDF or ray is impossible
|
|
3517
|
+
if ( scatterRec.pdf <= 0.0 || ! isDirectionValid( scatterRec.direction, surf.normal, surf.faceNormal ) ) {
|
|
3518
|
+
|
|
3519
|
+
break;
|
|
3520
|
+
|
|
3521
|
+
}
|
|
3522
|
+
|
|
3523
|
+
// if we're bouncing around the inside a transmissive material then decrement
|
|
3524
|
+
// perform this separate from a bounce
|
|
3525
|
+
bool isTransmissiveRay = ! surf.volumeParticle && dot( scatterRec.direction, surf.faceNormal * surfaceHit.side ) < 0.0;
|
|
3526
|
+
if ( ( isTransmissiveRay || isBelowSurface ) && state.transmissiveTraversals > 0 ) {
|
|
3527
|
+
|
|
3528
|
+
state.transmissiveTraversals --;
|
|
3529
|
+
i --;
|
|
3530
|
+
|
|
3531
|
+
}
|
|
3532
|
+
|
|
3533
|
+
//
|
|
3534
|
+
|
|
3535
|
+
// handle throughput color transformation
|
|
3536
|
+
// attenuate the throughput color by the medium color
|
|
3537
|
+
if ( ! surf.frontFace ) {
|
|
3538
|
+
|
|
3539
|
+
state.throughputColor *= transmissionAttenuation( surfaceHit.dist, surf.attenuationColor, surf.attenuationDistance );
|
|
3540
|
+
|
|
3541
|
+
}
|
|
3542
|
+
|
|
3543
|
+
#if FEATURE_RUSSIAN_ROULETTE
|
|
3544
|
+
|
|
3545
|
+
// russian roulette path termination
|
|
3546
|
+
// https://www.arnoldrenderer.com/research/physically_based_shader_design_in_arnold.pdf
|
|
3547
|
+
uint minBounces = 3u;
|
|
3548
|
+
float depthProb = float( state.depth < minBounces );
|
|
3549
|
+
|
|
3550
|
+
float rrProb = luminance( state.throughputColor * scatterRec.color / scatterRec.pdf );
|
|
3551
|
+
rrProb /= luminance( state.throughputColor );
|
|
3552
|
+
rrProb = sqrt( rrProb );
|
|
3553
|
+
rrProb = max( rrProb, depthProb );
|
|
3554
|
+
rrProb = min( rrProb, 1.0 );
|
|
3555
|
+
if ( rand( 8 ) > rrProb ) {
|
|
3556
|
+
|
|
3557
|
+
break;
|
|
3558
|
+
|
|
3559
|
+
}
|
|
3560
|
+
|
|
3561
|
+
// perform sample clamping here to avoid bright pixels
|
|
3562
|
+
state.throughputColor *= min( 1.0 / rrProb, 20.0 );
|
|
3563
|
+
|
|
3564
|
+
#endif
|
|
3565
|
+
|
|
3566
|
+
// adjust the throughput and discard and exit if we find discard the sample if there are any NaNs
|
|
3567
|
+
state.throughputColor *= scatterRec.color / scatterRec.pdf;
|
|
3568
|
+
if ( any( isnan( state.throughputColor ) ) || any( isinf( state.throughputColor ) ) ) {
|
|
3569
|
+
|
|
3570
|
+
break;
|
|
3571
|
+
|
|
3572
|
+
}
|
|
3573
|
+
|
|
3574
|
+
//
|
|
3575
|
+
|
|
3576
|
+
// prepare for next ray
|
|
3577
|
+
ray.direction = scatterRec.direction;
|
|
3578
|
+
ray.origin = hitPoint;
|
|
3579
|
+
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
gl_FragColor.a *= opacity;
|
|
3583
|
+
|
|
3584
|
+
#if DEBUG_MODE == 1
|
|
3585
|
+
|
|
3586
|
+
// output the number of rays checked in the path and number of
|
|
3587
|
+
// transmissive rays encountered.
|
|
3588
|
+
gl_FragColor.rgb = vec3(
|
|
3589
|
+
float( state.depth ),
|
|
3590
|
+
transmissiveBounces - state.transmissiveTraversals,
|
|
3591
|
+
0.0
|
|
3592
|
+
);
|
|
3593
|
+
gl_FragColor.a = 1.0;
|
|
3594
|
+
|
|
3595
|
+
#endif
|
|
3596
|
+
|
|
3597
|
+
}
|
|
3598
|
+
|
|
3599
|
+
`}),this.setValues(e)}}function*oo(){const{_renderer:n,_fsQuad:e,_blendQuad:t,_primaryTarget:i,_blendTargets:r,_sobolTarget:l,_subframe:o,alpha:c,material:h}=this,m=new d.Vector4,p=new d.Vector4,s=t.material;let[a,u]=r;for(;;){c?(s.opacity=this._opacityFactor/(this.samples+1),h.blending=d.NoBlending,h.opacity=1):(h.opacity=this._opacityFactor/(this.samples+1),h.blending=d.NormalBlending);const[g,_,f,v]=o,y=i.width,x=i.height;h.resolution.set(y*f,x*v),h.sobolTexture=l.texture,h.stratifiedTexture.init(20,h.bounces+h.transmissiveBounces+5),h.stratifiedTexture.next(),h.seed++;const w=this.tiles.x||1,b=this.tiles.y||1,C=w*b,T=Math.ceil(y*f),S=Math.ceil(x*v),A=Math.floor(g*y),P=Math.floor(_*x),I=Math.ceil(T/w),M=Math.ceil(S/b);for(let R=0;R<b;R++)for(let E=0;E<w;E++){const F=n.getRenderTarget(),D=n.autoClear,L=n.getScissorTest();n.getScissor(m),n.getViewport(p);let V=E,z=R;if(!this.stableTiles){const Y=this._currentTile%(w*b);V=Y%w,z=~~(Y/w),this._currentTile=Y+1}const G=b-z-1;i.scissor.set(A+V*I,P+G*M,Math.min(I,T-V*I),Math.min(M,S-G*M)),i.viewport.set(A,P,T,S),n.setRenderTarget(i),n.setScissorTest(!0),n.autoClear=!1,e.render(n),n.setViewport(p),n.setScissor(m),n.setScissorTest(L),n.setRenderTarget(F),n.autoClear=D,c&&(s.target1=a.texture,s.target2=i.texture,n.setRenderTarget(u),t.render(n),n.setRenderTarget(F)),this.samples+=1/C,E===w-1&&R===b-1&&(this.samples=Math.round(this.samples)),yield}[a,u]=[u,a]}}const os=new d.Color;class as{get material(){return this._fsQuad.material}set material(e){this._fsQuad.material.removeEventListener("recompilation",this._compileFunction),e.addEventListener("recompilation",this._compileFunction),this._fsQuad.material=e}get target(){return this._alpha?this._blendTargets[1]:this._primaryTarget}set alpha(e){this._alpha!==e&&(e||(this._blendTargets[0].dispose(),this._blendTargets[1].dispose()),this._alpha=e,this.reset())}get alpha(){return this._alpha}get isCompiling(){return!!this._compilePromise}constructor(e){this.camera=null,this.tiles=new d.Vector2(3,3),this.stableNoise=!1,this.stableTiles=!0,this.samples=0,this._subframe=new d.Vector4(0,0,1,1),this._opacityFactor=1,this._renderer=e,this._alpha=!1,this._fsQuad=new Ge.FullScreenQuad(new no),this._blendQuad=new Ge.FullScreenQuad(new Qr),this._task=null,this._currentTile=0,this._compilePromise=null,this._sobolTarget=new Kr().generate(e),this._primaryTarget=new d.WebGLRenderTarget(1,1,{format:d.RGBAFormat,type:d.FloatType,magFilter:d.NearestFilter,minFilter:d.NearestFilter}),this._blendTargets=[new d.WebGLRenderTarget(1,1,{format:d.RGBAFormat,type:d.FloatType,magFilter:d.NearestFilter,minFilter:d.NearestFilter}),new d.WebGLRenderTarget(1,1,{format:d.RGBAFormat,type:d.FloatType,magFilter:d.NearestFilter,minFilter:d.NearestFilter})],this._compileFunction=()=>{const t=this.compileMaterial(this._fsQuad._mesh);t.then(()=>{this._compilePromise===t&&(this._compilePromise=null)}),this._compilePromise=t},this.material.addEventListener("recompilation",this._compileFunction)}compileMaterial(){return this._renderer.compileAsync(this._fsQuad._mesh)}setCamera(e){const{material:t}=this;t.cameraWorldMatrix.copy(e.matrixWorld),t.invProjectionMatrix.copy(e.projectionMatrixInverse),t.physicalCamera.updateFrom(e);let i=0;e.projectionMatrix.elements[15]>0&&(i=1),e.isEquirectCamera&&(i=2),t.setDefine("CAMERA_TYPE",i),this.camera=e}setSize(e,t){e=Math.ceil(e),t=Math.ceil(t),!(this._primaryTarget.width===e&&this._primaryTarget.height===t)&&(this._primaryTarget.setSize(e,t),this._blendTargets[0].setSize(e,t),this._blendTargets[1].setSize(e,t),this.reset())}getSize(e){e.x=this._primaryTarget.width,e.y=this._primaryTarget.height}dispose(){this._primaryTarget.dispose(),this._blendTargets[0].dispose(),this._blendTargets[1].dispose(),this._sobolTarget.dispose(),this._fsQuad.dispose(),this._blendQuad.dispose(),this._task=null}reset(){const{_renderer:e,_primaryTarget:t,_blendTargets:i}=this,r=e.getRenderTarget(),l=e.getClearAlpha();e.getClearColor(os),e.setRenderTarget(t),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(i[0]),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(i[1]),e.setClearColor(0,0),e.clearColor(),e.setClearColor(os,l),e.setRenderTarget(r),this.samples=0,this._task=null,this.material.stratifiedTexture.stableNoise=this.stableNoise,this.stableNoise&&(this.material.seed=0,this.material.stratifiedTexture.reset())}update(){this.material.onBeforeRender(),!this.isCompiling&&(this._task||(this._task=oo.call(this)),this._task.next())}}const ye=new d.Vector2,ls=new d.Vector2,gt=new d.Spherical,vt=new d.Color;class ao extends d.DataTexture{constructor(e=512,t=512){super(new Float32Array(e*t*4),e,t,d.RGBAFormat,d.FloatType,d.EquirectangularReflectionMapping,d.RepeatWrapping,d.ClampToEdgeWrapping,d.LinearFilter,d.LinearFilter),this.generationCallback=null}update(){this.dispose(),this.needsUpdate=!0;const{data:e,width:t,height:i}=this.image;for(let r=0;r<t;r++)for(let l=0;l<i;l++){ls.set(t,i),ye.set(r/t,l/i),ye.x-=.5,ye.y=1-ye.y,gt.theta=ye.x*2*Math.PI,gt.phi=ye.y*Math.PI,gt.radius=1,this.generationCallback(gt,ye,ls,vt);const c=4*(l*t+r);e[c+0]=vt.r,e[c+1]=vt.g,e[c+2]=vt.b,e[c+3]=1}}copy(e){return super.copy(e),this.generationCallback=e.generationCallback,this}}const cs=new d.Vector3;class lo extends ao{constructor(e=512){super(e,e),this.topColor=new d.Color().set(16777215),this.bottomColor=new d.Color().set(0),this.exponent=2,this.generationCallback=(t,i,r,l)=>{cs.setFromSpherical(t);const o=cs.y*.5+.5;l.lerpColors(this.bottomColor,this.topColor,o**this.exponent)}}copy(e){return super.copy(e),this.topColor.copy(e.topColor),this.bottomColor.copy(e.bottomColor),this}}class co extends d.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}constructor(e){super({uniforms:{map:{value:null},opacity:{value:1}},vertexShader:`
|
|
3600
|
+
varying vec2 vUv;
|
|
3601
|
+
void main() {
|
|
3602
|
+
|
|
3603
|
+
vUv = uv;
|
|
3604
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
3605
|
+
|
|
3606
|
+
}
|
|
3607
|
+
`,fragmentShader:`
|
|
3608
|
+
uniform sampler2D map;
|
|
3609
|
+
uniform float opacity;
|
|
3610
|
+
varying vec2 vUv;
|
|
3611
|
+
|
|
3612
|
+
vec4 clampedTexelFatch( sampler2D map, ivec2 px, int lod ) {
|
|
3613
|
+
|
|
3614
|
+
vec4 res = texelFetch( map, ivec2( px.x, px.y ), 0 );
|
|
3615
|
+
|
|
3616
|
+
#if defined( TONE_MAPPING )
|
|
3617
|
+
|
|
3618
|
+
res.xyz = toneMapping( res.xyz );
|
|
3619
|
+
|
|
3620
|
+
#endif
|
|
3621
|
+
|
|
3622
|
+
return linearToOutputTexel( res );
|
|
3623
|
+
|
|
3624
|
+
}
|
|
3625
|
+
|
|
3626
|
+
void main() {
|
|
3627
|
+
|
|
3628
|
+
vec2 size = vec2( textureSize( map, 0 ) );
|
|
3629
|
+
vec2 pxUv = vUv * size;
|
|
3630
|
+
vec2 pxCurr = floor( pxUv );
|
|
3631
|
+
vec2 pxFrac = fract( pxUv ) - 0.5;
|
|
3632
|
+
vec2 pxOffset;
|
|
3633
|
+
pxOffset.x = pxFrac.x > 0.0 ? 1.0 : - 1.0;
|
|
3634
|
+
pxOffset.y = pxFrac.y > 0.0 ? 1.0 : - 1.0;
|
|
3635
|
+
|
|
3636
|
+
vec2 pxNext = clamp( pxOffset + pxCurr, vec2( 0.0 ), size - 1.0 );
|
|
3637
|
+
vec2 alpha = abs( pxFrac );
|
|
3638
|
+
|
|
3639
|
+
vec4 p1 = mix(
|
|
3640
|
+
clampedTexelFatch( map, ivec2( pxCurr.x, pxCurr.y ), 0 ),
|
|
3641
|
+
clampedTexelFatch( map, ivec2( pxNext.x, pxCurr.y ), 0 ),
|
|
3642
|
+
alpha.x
|
|
3643
|
+
);
|
|
3644
|
+
|
|
3645
|
+
vec4 p2 = mix(
|
|
3646
|
+
clampedTexelFatch( map, ivec2( pxCurr.x, pxNext.y ), 0 ),
|
|
3647
|
+
clampedTexelFatch( map, ivec2( pxNext.x, pxNext.y ), 0 ),
|
|
3648
|
+
alpha.x
|
|
3649
|
+
);
|
|
3650
|
+
|
|
3651
|
+
gl_FragColor = mix( p1, p2, alpha.y );
|
|
3652
|
+
gl_FragColor.a *= opacity;
|
|
3653
|
+
#include <premultiplied_alpha_fragment>
|
|
3654
|
+
|
|
3655
|
+
}
|
|
3656
|
+
`}),this.setValues(e)}}class ho extends d.ShaderMaterial{constructor(){super({uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:`
|
|
3657
|
+
varying vec2 vUv;
|
|
3658
|
+
void main() {
|
|
3659
|
+
|
|
3660
|
+
vUv = uv;
|
|
3661
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
3662
|
+
|
|
3663
|
+
}`,fragmentShader:`
|
|
3664
|
+
#define ENVMAP_TYPE_CUBE_UV
|
|
3665
|
+
|
|
3666
|
+
uniform samplerCube envMap;
|
|
3667
|
+
uniform float flipEnvMap;
|
|
3668
|
+
varying vec2 vUv;
|
|
3669
|
+
|
|
3670
|
+
#include <common>
|
|
3671
|
+
#include <cube_uv_reflection_fragment>
|
|
3672
|
+
|
|
3673
|
+
${Ws}
|
|
3674
|
+
|
|
3675
|
+
void main() {
|
|
3676
|
+
|
|
3677
|
+
vec3 rayDirection = equirectUvToDirection( vUv );
|
|
3678
|
+
rayDirection.x *= flipEnvMap;
|
|
3679
|
+
gl_FragColor = textureCube( envMap, rayDirection );
|
|
3680
|
+
|
|
3681
|
+
}`}),this.depthWrite=!1,this.depthTest=!1}}class hs{constructor(e){this._renderer=e,this._quad=new Ge.FullScreenQuad(new ho)}generate(e,t=null,i=null){if(!e.isCubeTexture)throw new Error("CubeToEquirectMaterial: Source can only be cube textures.");const r=e.images[0],l=this._renderer,o=this._quad;t===null&&(t=4*r.height),i===null&&(i=2*r.height);const c=new d.WebGLRenderTarget(t,i,{type:d.FloatType,colorSpace:r.colorSpace}),h=r.height,m=Math.log2(h)-2,p=1/h,s=1/(3*Math.max(Math.pow(2,m),7*16));o.material.defines.CUBEUV_MAX_MIP=`${m}.0`,o.material.defines.CUBEUV_TEXEL_WIDTH=s,o.material.defines.CUBEUV_TEXEL_HEIGHT=p,o.material.uniforms.envMap.value=e,o.material.uniforms.flipEnvMap.value=e.isRenderTargetTexture?1:-1,o.material.needsUpdate=!0;const a=l.getRenderTarget(),u=l.autoClear;l.autoClear=!0,l.setRenderTarget(c),o.render(l),l.setRenderTarget(a),l.autoClear=u;const g=new Uint16Array(t*i*4),_=new Float32Array(t*i*4);l.readRenderTargetPixels(c,0,0,t,i,_),c.dispose();for(let v=0,y=_.length;v<y;v++)g[v]=d.DataUtils.toHalfFloat(_[v]);const f=new d.DataTexture(g,t,i,d.RGBAFormat,d.HalfFloatType);return f.minFilter=d.LinearMipMapLinearFilter,f.magFilter=d.LinearFilter,f.wrapS=d.RepeatWrapping,f.wrapT=d.RepeatWrapping,f.mapping=d.EquirectangularReflectionMapping,f.needsUpdate=!0,f}dispose(){this._quad.dispose()}}function uo(n){return n.extensions.get("EXT_float_blend")}const Me=new d.Vector2;class fo{get multipleImportanceSampling(){return!!this._pathTracer.material.defines.FEATURE_MIS}set multipleImportanceSampling(e){this._pathTracer.material.setDefine("FEATURE_MIS",e?1:0)}get transmissiveBounces(){return this._pathTracer.material.transmissiveBounces}set transmissiveBounces(e){this._pathTracer.material.transmissiveBounces=e}get bounces(){return this._pathTracer.material.bounces}set bounces(e){this._pathTracer.material.bounces=e}get filterGlossyFactor(){return this._pathTracer.material.filterGlossyFactor}set filterGlossyFactor(e){this._pathTracer.material.filterGlossyFactor=e}get samples(){return this._pathTracer.samples}get target(){return this._pathTracer.target}get tiles(){return this._pathTracer.tiles}get stableNoise(){return this._pathTracer.stableNoise}set stableNoise(e){this._pathTracer.stableNoise=e}get isCompiling(){return!!this._pathTracer.isCompiling}constructor(e){this._renderer=e,this._generator=new Yr,this._pathTracer=new as(e),this._queueReset=!1,this._clock=new d.Clock,this._compilePromise=null,this._lowResPathTracer=new as(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new Ge.FullScreenQuad(new co({map:null,transparent:!0,blending:d.NoBlending,premultipliedAlpha:e.getContextAttributes().premultipliedAlpha})),this._materials=null,this._previousEnvironment=null,this._previousBackground=null,this._internalBackground=null,this.renderDelay=100,this.minSamples=5,this.fadeDuration=500,this.enablePathTracing=!0,this.pausePathTracing=!1,this.dynamicLowRes=!1,this.lowResScale=.25,this.renderScale=1,this.synchronizeRenderSize=!0,this.rasterizeScene=!0,this.renderToCanvas=!0,this.textureSize=new d.Vector2(1024,1024),this.rasterizeSceneCallback=(t,i)=>{this._renderer.render(t,i)},this.renderToCanvasCallback=(t,i,r)=>{const l=i.autoClear;i.autoClear=!1,r.render(i),i.autoClear=l},this.setScene(new d.Scene,new d.PerspectiveCamera)}setBVHWorker(e){this._generator.setBVHWorker(e)}setScene(e,t,i={}){e.updateMatrixWorld(!0),t.updateMatrixWorld();const r=this._generator;if(r.setObjects(e),this._buildAsync)return r.generateAsync(i.onProgress).then(l=>this._updateFromResults(e,t,l));{const l=r.generate();return this._updateFromResults(e,t,l)}}setSceneAsync(...e){this._buildAsync=!0;const t=this.setScene(...e);return this._buildAsync=!1,t}setCamera(e){this.camera=e,this.updateCamera()}updateCamera(){const e=this.camera;e.updateMatrixWorld(),this._pathTracer.setCamera(e),this._lowResPathTracer.setCamera(e),this.reset()}updateMaterials(){const e=this._pathTracer.material,t=this._renderer,i=this._materials,r=this.textureSize,l=gn(i);e.textures.setTextures(t,l,r.x,r.y),e.materials.updateFrom(i,l),this.reset()}updateLights(){const e=this.scene,t=this._renderer,i=this._pathTracer.material,r=vn(e),l=mn(r);i.lights.updateFrom(r,l),i.iesProfiles.setTextures(t,l),this.reset()}updateEnvironment(){const e=this.scene,t=this._pathTracer.material;if(this._internalBackground&&(this._internalBackground.dispose(),this._internalBackground=null),t.backgroundBlur=e.backgroundBlurriness,t.backgroundIntensity=e.backgroundIntensity??1,t.backgroundRotation.makeRotationFromEuler(e.backgroundRotation).invert(),e.background===null)t.backgroundMap=null,t.backgroundAlpha=0;else if(e.background.isColor){this._colorBackground=this._colorBackground||new lo(16);const i=this._colorBackground;i.topColor.equals(e.background)||(i.topColor.set(e.background),i.bottomColor.set(e.background),i.update()),t.backgroundMap=i,t.backgroundAlpha=1}else if(e.background.isCubeTexture){if(e.background!==this._previousBackground){const i=new hs(this._renderer).generate(e.background);this._internalBackground=i,t.backgroundMap=i,t.backgroundAlpha=1}}else t.backgroundMap=e.background,t.backgroundAlpha=1;if(t.environmentIntensity=e.environmentIntensity??1,t.environmentRotation.makeRotationFromEuler(e.environmentRotation).invert(),this._previousEnvironment!==e.environment)if(e.environment!==null)if(e.environment.isCubeTexture){const i=new hs(this._renderer).generate(e.environment);t.envMapInfo.updateFrom(i)}else t.envMapInfo.updateFrom(e.environment);else t.environmentIntensity=0;this._previousEnvironment=e.environment,this._previousBackground=e.background,this.reset()}_updateFromResults(e,t,i){const{materials:r,geometry:l,bvh:o,bvhChanged:c}=i;this._materials=r;const m=this._pathTracer.material;return c&&(m.bvh.updateFrom(o),m.attributesArray.updateFrom(l.attributes.normal,l.attributes.tangent,l.attributes.uv,l.attributes.color),m.materialIndexAttribute.updateFrom(l.attributes.materialIndex)),this._previousScene=e,this.scene=e,this.camera=t,this.updateCamera(),this.updateMaterials(),this.updateEnvironment(),this.updateLights(),i}renderSample(){const e=this._lowResPathTracer,t=this._pathTracer,i=this._renderer,r=this._clock,l=this._quad;this._updateScale(),this._queueReset&&(t.reset(),e.reset(),this._queueReset=!1,l.material.opacity=0,r.start());const o=r.getDelta()*1e3,c=r.getElapsedTime()*1e3;if(!this.pausePathTracing&&this.enablePathTracing&&this.renderDelay<=c&&!this.isCompiling&&t.update(),t.alpha=t.material.backgroundAlpha!==1||!uo(i),e.alpha=t.alpha,this.renderToCanvas){const h=this._renderer,m=this.minSamples;if(c>=this.renderDelay&&this.samples>=this.minSamples&&(this.fadeDuration!==0?l.material.opacity=Math.min(l.material.opacity+o/this.fadeDuration,1):l.material.opacity=1),!this.enablePathTracing||this.samples<m||l.material.opacity<1){if(this.dynamicLowRes&&!this.isCompiling){e.samples<1&&(e.material=t.material,e.update());const p=l.material.opacity;l.material.opacity=1-l.material.opacity,l.material.map=e.target.texture,l.render(h),l.material.opacity=p}(!this.dynamicLowRes&&this.rasterizeScene||this.dynamicLowRes&&this.isCompiling)&&this.rasterizeSceneCallback(this.scene,this.camera)}this.enablePathTracing&&l.material.opacity>0&&(l.material.opacity<1&&(l.material.blending=this.dynamicLowRes?d.AdditiveBlending:d.NormalBlending),l.material.map=t.target.texture,this.renderToCanvasCallback(t.target,h,l),l.material.blending=d.NoBlending)}}reset(){this._queueReset=!0,this._pathTracer.samples=0}dispose(){this._renderQuad.dispose(),this._renderQuad.material.dispose(),this._pathTracer.dispose()}_updateScale(){if(this.synchronizeRenderSize){this._renderer.getDrawingBufferSize(Me);const e=Math.floor(this.renderScale*Me.x),t=Math.floor(this.renderScale*Me.y);if(this._pathTracer.getSize(Me),Me.x!==e||Me.y!==t){const i=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*i),Math.floor(t*i))}}}}var Ne=Object.freeze({Linear:Object.freeze({None:function(n){return n},In:function(n){return n},Out:function(n){return n},InOut:function(n){return n}}),Quadratic:Object.freeze({In:function(n){return n*n},Out:function(n){return n*(2-n)},InOut:function(n){return(n*=2)<1?.5*n*n:-.5*(--n*(n-2)-1)}}),Cubic:Object.freeze({In:function(n){return n*n*n},Out:function(n){return--n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n:.5*((n-=2)*n*n+2)}}),Quartic:Object.freeze({In:function(n){return n*n*n*n},Out:function(n){return 1- --n*n*n*n},InOut:function(n){return(n*=2)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2)}}),Quintic:Object.freeze({In:function(n){return n*n*n*n*n},Out:function(n){return--n*n*n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2)}}),Sinusoidal:Object.freeze({In:function(n){return 1-Math.sin((1-n)*Math.PI/2)},Out:function(n){return Math.sin(n*Math.PI/2)},InOut:function(n){return .5*(1-Math.sin(Math.PI*(.5-n)))}}),Exponential:Object.freeze({In:function(n){return n===0?0:Math.pow(1024,n-1)},Out:function(n){return n===1?1:1-Math.pow(2,-10*n)},InOut:function(n){return n===0?0:n===1?1:(n*=2)<1?.5*Math.pow(1024,n-1):.5*(-Math.pow(2,-10*(n-1))+2)}}),Circular:Object.freeze({In:function(n){return 1-Math.sqrt(1-n*n)},Out:function(n){return Math.sqrt(1- --n*n)},InOut:function(n){return(n*=2)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1)}}),Elastic:Object.freeze({In:function(n){return n===0?0:n===1?1:-Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI)},Out:function(n){return n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n-.1)*5*Math.PI)+1},InOut:function(n){return n===0?0:n===1?1:(n*=2,n<1?-.5*Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI):.5*Math.pow(2,-10*(n-1))*Math.sin((n-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(n){var e=1.70158;return n===1?1:n*n*((e+1)*n-e)},Out:function(n){var e=1.70158;return n===0?0:--n*n*((e+1)*n+e)+1},InOut:function(n){var e=2.5949095;return(n*=2)<1?.5*(n*n*((e+1)*n-e)):.5*((n-=2)*n*((e+1)*n+e)+2)}}),Bounce:Object.freeze({In:function(n){return 1-Ne.Bounce.Out(1-n)},Out:function(n){return n<1/2.75?7.5625*n*n:n<2/2.75?7.5625*(n-=1.5/2.75)*n+.75:n<2.5/2.75?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375},InOut:function(n){return n<.5?Ne.Bounce.In(n*2)*.5:Ne.Bounce.Out(n*2-1)*.5+.5}}),generatePow:function(n){return n===void 0&&(n=4),n=n<Number.EPSILON?Number.EPSILON:n,n=n>1e4?1e4:n,{In:function(e){return Math.pow(e,n)},Out:function(e){return 1-Math.pow(1-e,n)},InOut:function(e){return e<.5?Math.pow(e*2,n)/2:(1-Math.pow(2-e*2,n))/2+.5}}}}),Ue=function(){return performance.now()},Gs=function(){function n(){this._tweens={},this._tweensAddedDuringUpdate={}}return n.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},n.prototype.removeAll=function(){this._tweens={}},n.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},n.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},n.prototype.update=function(e,t){e===void 0&&(e=Ue()),t===void 0&&(t=!1);var i=Object.keys(this._tweens);if(i.length===0)return!1;for(;i.length>0;){this._tweensAddedDuringUpdate={};for(var r=0;r<i.length;r++){var l=this._tweens[i[r]],o=!t;l&&l.update(e,o)===!1&&!t&&delete this._tweens[i[r]]}i=Object.keys(this._tweensAddedDuringUpdate)}return!0},n}(),xe={Linear:function(n,e){var t=n.length-1,i=t*e,r=Math.floor(i),l=xe.Utils.Linear;return e<0?l(n[0],n[1],i):e>1?l(n[t],n[t-1],t-i):l(n[r],n[r+1>t?t:r+1],i-r)},Bezier:function(n,e){for(var t=0,i=n.length-1,r=Math.pow,l=xe.Utils.Bernstein,o=0;o<=i;o++)t+=r(1-e,i-o)*r(e,o)*n[o]*l(i,o);return t},CatmullRom:function(n,e){var t=n.length-1,i=t*e,r=Math.floor(i),l=xe.Utils.CatmullRom;return n[0]===n[t]?(e<0&&(r=Math.floor(i=t*(1+e))),l(n[(r-1+t)%t],n[r],n[(r+1)%t],n[(r+2)%t],i-r)):e<0?n[0]-(l(n[0],n[0],n[1],n[1],-i)-n[0]):e>1?n[t]-(l(n[t],n[t],n[t-1],n[t-1],i-t)-n[t]):l(n[r?r-1:0],n[r],n[t<r+1?t:r+1],n[t<r+2?t:r+2],i-r)},Utils:{Linear:function(n,e,t){return(e-n)*t+n},Bernstein:function(n,e){var t=xe.Utils.Factorial;return t(n)/t(e)/t(n-e)},Factorial:function(){var n=[1];return function(e){var t=1;if(n[e])return n[e];for(var i=e;i>1;i--)t*=i;return n[e]=t,t}}(),CatmullRom:function(n,e,t,i,r){var l=(t-n)*.5,o=(i-e)*.5,c=r*r,h=r*c;return(2*e-2*t+l+o)*h+(-3*e+3*t-2*l-o)*c+l*r+e}}},Fi=function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n}(),di=new Gs,zt=function(){function n(e,t){t===void 0&&(t=di),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=Ne.Linear.None,this._interpolationFunction=xe.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Fi.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return n.prototype.getId=function(){return this._id},n.prototype.isPlaying=function(){return this._isPlaying},n.prototype.isPaused=function(){return this._isPaused},n.prototype.getDuration=function(){return this._duration},n.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},n.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e<0?0:e,this},n.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},n.prototype.start=function(e,t){if(e===void 0&&(e=Ue()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var i in this._valuesStartRepeat)this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var r={};for(var l in this._valuesEnd)r[l]=this._valuesEnd[l];this._valuesEnd=r}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},n.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},n.prototype._setupProperties=function(e,t,i,r,l){for(var o in i){var c=e[o],h=Array.isArray(c),m=h?"array":typeof c,p=!h&&Array.isArray(i[o]);if(!(m==="undefined"||m==="function")){if(p){var s=i[o];if(s.length===0)continue;for(var a=[c],u=0,g=s.length;u<g;u+=1){var _=this._handleRelativeValue(c,s[u]);if(isNaN(_)){p=!1,console.warn("Found invalid interpolation list. Skipping.");break}a.push(_)}p&&(i[o]=a)}if((m==="object"||h)&&c&&!p){t[o]=h?[]:{};var f=c;for(var v in f)t[o][v]=f[v];r[o]=h?[]:{};var s=i[o];if(!this._isDynamic){var y={};for(var v in s)y[v]=s[v];i[o]=s=y}this._setupProperties(f,t[o],s,r[o],l)}else(typeof t[o]>"u"||l)&&(t[o]=c),h||(t[o]*=1),p?r[o]=i[o].slice().reverse():r[o]=t[o]||0}}},n.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},n.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},n.prototype.pause=function(e){return e===void 0&&(e=Ue()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},n.prototype.resume=function(e){return e===void 0&&(e=Ue()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},n.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},n.prototype.group=function(e){return e===void 0&&(e=di),this._group=e,this},n.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},n.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},n.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},n.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},n.prototype.easing=function(e){return e===void 0&&(e=Ne.Linear.None),this._easingFunction=e,this},n.prototype.interpolation=function(e){return e===void 0&&(e=xe.Linear),this._interpolationFunction=e,this},n.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},n.prototype.onStart=function(e){return this._onStartCallback=e,this},n.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},n.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},n.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},n.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},n.prototype.onStop=function(e){return this._onStopCallback=e,this},n.prototype.update=function(e,t){var i=this,r;if(e===void 0&&(e=Ue()),t===void 0&&(t=!0),this._isPaused)return!0;var l,o=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>o)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var c=e-this._startTime,h=this._duration+((r=this._repeatDelayTime)!==null&&r!==void 0?r:this._delayTime),m=this._duration+this._repeat*h,p=function(){if(i._duration===0||c>m)return 1;var f=Math.trunc(c/h),v=c-f*h,y=Math.min(v/i._duration,1);return y===0&&c===i._duration?1:y},s=p(),a=this._easingFunction(s);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,a),this._onUpdateCallback&&this._onUpdateCallback(this._object,s),this._duration===0||c>=this._duration)if(this._repeat>0){var u=Math.min(Math.trunc((c-this._duration)/h)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=u);for(l in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[l]=="string"&&(this._valuesStartRepeat[l]=this._valuesStartRepeat[l]+parseFloat(this._valuesEnd[l])),this._yoyo&&this._swapEndStartRepeatValues(l),this._valuesStart[l]=this._valuesStartRepeat[l];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=h*u,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var g=0,_=this._chainedTweens.length;g<_;g++)this._chainedTweens[g].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},n.prototype._updateProperties=function(e,t,i,r){for(var l in i)if(t[l]!==void 0){var o=t[l]||0,c=i[l],h=Array.isArray(e[l]),m=Array.isArray(c),p=!h&&m;p?e[l]=this._interpolationFunction(c,r):typeof c=="object"&&c?this._updateProperties(e[l],o,c,r):(c=this._handleRelativeValue(o,c),typeof c=="number"&&(e[l]=o+(c-o)*r))}},n.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},n.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],i=this._valuesEnd[e];typeof i=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(i):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},n}(),po="23.1.3",mo=Fi.nextId,re=di,go=re.getAll.bind(re),vo=re.removeAll.bind(re),_o=re.add.bind(re),yo=re.remove.bind(re),xo=re.update.bind(re),ie={Easing:Ne,Group:Gs,Interpolation:xe,now:Ue,Sequence:Fi,nextId:mo,Tween:zt,VERSION:po,getAll:go,removeAll:vo,add:_o,remove:yo,update:xo},Ze=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function wo(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var js={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(h,m,p){this.fn=h,this.context=m,this.once=p||!1}function l(h,m,p,s,a){if(typeof p!="function")throw new TypeError("The listener must be a function");var u=new r(p,s||h,a),g=t?t+m:m;return h._events[g]?h._events[g].fn?h._events[g]=[h._events[g],u]:h._events[g].push(u):(h._events[g]=u,h._eventsCount++),h}function o(h,m){--h._eventsCount===0?h._events=new i:delete h._events[m]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var m=[],p,s;if(this._eventsCount===0)return m;for(s in p=this._events)e.call(p,s)&&m.push(t?s.slice(1):s);return Object.getOwnPropertySymbols?m.concat(Object.getOwnPropertySymbols(p)):m},c.prototype.listeners=function(m){var p=t?t+m:m,s=this._events[p];if(!s)return[];if(s.fn)return[s.fn];for(var a=0,u=s.length,g=new Array(u);a<u;a++)g[a]=s[a].fn;return g},c.prototype.listenerCount=function(m){var p=t?t+m:m,s=this._events[p];return s?s.fn?1:s.length:0},c.prototype.emit=function(m,p,s,a,u,g){var _=t?t+m:m;if(!this._events[_])return!1;var f=this._events[_],v=arguments.length,y,x;if(f.fn){switch(f.once&&this.removeListener(m,f.fn,void 0,!0),v){case 1:return f.fn.call(f.context),!0;case 2:return f.fn.call(f.context,p),!0;case 3:return f.fn.call(f.context,p,s),!0;case 4:return f.fn.call(f.context,p,s,a),!0;case 5:return f.fn.call(f.context,p,s,a,u),!0;case 6:return f.fn.call(f.context,p,s,a,u,g),!0}for(x=1,y=new Array(v-1);x<v;x++)y[x-1]=arguments[x];f.fn.apply(f.context,y)}else{var w=f.length,b;for(x=0;x<w;x++)switch(f[x].once&&this.removeListener(m,f[x].fn,void 0,!0),v){case 1:f[x].fn.call(f[x].context);break;case 2:f[x].fn.call(f[x].context,p);break;case 3:f[x].fn.call(f[x].context,p,s);break;case 4:f[x].fn.call(f[x].context,p,s,a);break;default:if(!y)for(b=1,y=new Array(v-1);b<v;b++)y[b-1]=arguments[b];f[x].fn.apply(f[x].context,y)}}return!0},c.prototype.on=function(m,p,s){return l(this,m,p,s,!1)},c.prototype.once=function(m,p,s){return l(this,m,p,s,!0)},c.prototype.removeListener=function(m,p,s,a){var u=t?t+m:m;if(!this._events[u])return this;if(!p)return o(this,u),this;var g=this._events[u];if(g.fn)g.fn===p&&(!a||g.once)&&(!s||g.context===s)&&o(this,u);else{for(var _=0,f=[],v=g.length;_<v;_++)(g[_].fn!==p||a&&!g[_].once||s&&g[_].context!==s)&&f.push(g[_]);f.length?this._events[u]=f.length===1?f[0]:f:o(this,u)}return this},c.prototype.removeAllListeners=function(m){var p;return m?(p=t?t+m:m,this._events[p]&&o(this,p)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=t,c.EventEmitter=c,n.exports=c})(js);var bo=js.exports;const je=wo(bo);var at=function(){var n=0,e=document.createElement("div");e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",function(s){s.preventDefault(),i(++n%e.children.length)},!1);function t(s){return e.appendChild(s.dom),s}function i(s){for(var a=0;a<e.children.length;a++)e.children[a].style.display=a===s?"block":"none";n=s}var r=(performance||Date).now(),l=r,o=0,c=t(new at.Panel("FPS","#0ff","#002")),h=t(new at.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var m=t(new at.Panel("MB","#f08","#201"));i(0);var p=0;return{REVISION:16,dom:e,fps:function(){return p&&parseInt(p.toFixed(0))},addPanel:t,showPanel:i,begin:function(){r=(performance||Date).now()},end:function(){o++;var s=(performance||Date).now();if(h.update(s-r,200),s>=l+1e3&&(p=o*1e3/(s-l),c.update(p,100),l=s,o=0,m)){var a=performance.memory;m.update(a.usedJSHeapSize/1048576,a.jsHeapSizeLimit/1048576)}return s},update:function(){r=this.end()},domElement:e,setMode:i}};at.Panel=function(n,e,t){var i=1/0,r=0,l=Math.round,o=l(window.devicePixelRatio||1),c=80*o,h=48*o,m=3*o,p=2*o,s=3*o,a=15*o,u=74*o,g=30*o,_=document.createElement("canvas");_.width=c,_.height=h,_.style.cssText="width:80px;height:48px";var f=_.getContext("2d");return f.font="bold "+9*o+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=t,f.fillRect(0,0,c,h),f.fillStyle=e,f.fillText(n,m,p),f.fillRect(s,a,u,g),f.fillStyle=t,f.globalAlpha=.9,f.fillRect(s,a,u,g),{dom:_,update:function(v,y){i=Math.min(i,v),r=Math.max(r,v),f.fillStyle=t,f.globalAlpha=1,f.fillRect(0,0,c,a),f.fillStyle=e,f.fillText(l(v)+" "+n+" ("+l(i)+"-"+l(r)+")",m,p),f.drawImage(_,s+o,a,u-o,g,s,a,u-o,g),f.fillRect(s+u-o,a,o,g),f.fillStyle=t,f.globalAlpha=.9,f.fillRect(s+u-o,a,o,l((1-v/y)*g))}}};function Ao(n,e){const t=URL.createObjectURL(n),i=document.createElement("a");i.href=t,i.download=e,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}function qs(n){return n.length===0?0:n.reduce((t,i)=>t+i,0)/n.length}function pi(n,e){const t=new Blob([n],{type:e});return URL.createObjectURL(t)}function Ys(){return/Mac|iPod|iPhone|iPad/.test(navigator==null?void 0:navigator.platform)||/Mac OS|iOS/.test(navigator==null?void 0:navigator.userAgent)}function mi(n){let e=document.createElement("canvas");const t=e.getContext("2d");return e.width=n.width,e.height=n.height,t?(t.drawImage(n,0,0),e.toDataURL("image/png",.75)):void 0}function To(n,e=43){const t=n*Math.PI/180;return e/(2*Math.tan(t/2))}var Qs={};/*!
|
|
3682
|
+
* howler.js v2.2.4
|
|
3683
|
+
* howlerjs.com
|
|
3684
|
+
*
|
|
3685
|
+
* (c) 2013-2020, James Simpson of GoldFire Studios
|
|
3686
|
+
* goldfirestudios.com
|
|
3687
|
+
*
|
|
3688
|
+
* MIT License
|
|
3689
|
+
*/(function(n){(function(){var e=function(){this.init()};e.prototype={init:function(){var s=this||t;return s._counter=1e3,s._html5AudioPool=[],s.html5PoolSize=10,s._codecs={},s._howls=[],s._muted=!1,s._volume=1,s._canPlayEvent="canplaythrough",s._navigator=typeof window<"u"&&window.navigator?window.navigator:null,s.masterGain=null,s.noAudio=!1,s.usingWebAudio=!0,s.autoSuspend=!0,s.ctx=null,s.autoUnlock=!0,s._setup(),s},volume:function(s){var a=this||t;if(s=parseFloat(s),a.ctx||p(),typeof s<"u"&&s>=0&&s<=1){if(a._volume=s,a._muted)return a;a.usingWebAudio&&a.masterGain.gain.setValueAtTime(s,t.ctx.currentTime);for(var u=0;u<a._howls.length;u++)if(!a._howls[u]._webAudio)for(var g=a._howls[u]._getSoundIds(),_=0;_<g.length;_++){var f=a._howls[u]._soundById(g[_]);f&&f._node&&(f._node.volume=f._volume*s)}return a}return a._volume},mute:function(s){var a=this||t;a.ctx||p(),a._muted=s,a.usingWebAudio&&a.masterGain.gain.setValueAtTime(s?0:a._volume,t.ctx.currentTime);for(var u=0;u<a._howls.length;u++)if(!a._howls[u]._webAudio)for(var g=a._howls[u]._getSoundIds(),_=0;_<g.length;_++){var f=a._howls[u]._soundById(g[_]);f&&f._node&&(f._node.muted=s?!0:f._muted)}return a},stop:function(){for(var s=this||t,a=0;a<s._howls.length;a++)s._howls[a].stop();return s},unload:function(){for(var s=this||t,a=s._howls.length-1;a>=0;a--)s._howls[a].unload();return s.usingWebAudio&&s.ctx&&typeof s.ctx.close<"u"&&(s.ctx.close(),s.ctx=null,p()),s},codecs:function(s){return(this||t)._codecs[s.replace(/^x-/,"")]},_setup:function(){var s=this||t;if(s.state=s.ctx&&s.ctx.state||"suspended",s._autoSuspend(),!s.usingWebAudio)if(typeof Audio<"u")try{var a=new Audio;typeof a.oncanplaythrough>"u"&&(s._canPlayEvent="canplay")}catch{s.noAudio=!0}else s.noAudio=!0;try{var a=new Audio;a.muted&&(s.noAudio=!0)}catch{}return s.noAudio||s._setupCodecs(),s},_setupCodecs:function(){var s=this||t,a=null;try{a=typeof Audio<"u"?new Audio:null}catch{return s}if(!a||typeof a.canPlayType!="function")return s;var u=a.canPlayType("audio/mpeg;").replace(/^no$/,""),g=s._navigator?s._navigator.userAgent:"",_=g.match(/OPR\/(\d+)/g),f=_&&parseInt(_[0].split("/")[1],10)<33,v=g.indexOf("Safari")!==-1&&g.indexOf("Chrome")===-1,y=g.match(/Version\/(.*?) /),x=v&&y&&parseInt(y[1],10)<15;return s._codecs={mp3:!!(!f&&(u||a.canPlayType("audio/mp3;").replace(/^no$/,""))),mpeg:!!u,opus:!!a.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(a.canPlayType('audio/wav; codecs="1"')||a.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!a.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!a.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(a.canPlayType("audio/x-m4b;")||a.canPlayType("audio/m4b;")||a.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(a.canPlayType("audio/x-mp4;")||a.canPlayType("audio/mp4;")||a.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!(!x&&a.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!!(!x&&a.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!a.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(a.canPlayType("audio/x-flac;")||a.canPlayType("audio/flac;")).replace(/^no$/,"")},s},_unlockAudio:function(){var s=this||t;if(!(s._audioUnlocked||!s.ctx)){s._audioUnlocked=!1,s.autoUnlock=!1,!s._mobileUnloaded&&s.ctx.sampleRate!==44100&&(s._mobileUnloaded=!0,s.unload()),s._scratchBuffer=s.ctx.createBuffer(1,1,22050);var a=function(u){for(;s._html5AudioPool.length<s.html5PoolSize;)try{var g=new Audio;g._unlocked=!0,s._releaseHtml5Audio(g)}catch{s.noAudio=!0;break}for(var _=0;_<s._howls.length;_++)if(!s._howls[_]._webAudio)for(var f=s._howls[_]._getSoundIds(),v=0;v<f.length;v++){var y=s._howls[_]._soundById(f[v]);y&&y._node&&!y._node._unlocked&&(y._node._unlocked=!0,y._node.load())}s._autoResume();var x=s.ctx.createBufferSource();x.buffer=s._scratchBuffer,x.connect(s.ctx.destination),typeof x.start>"u"?x.noteOn(0):x.start(0),typeof s.ctx.resume=="function"&&s.ctx.resume(),x.onended=function(){x.disconnect(0),s._audioUnlocked=!0,document.removeEventListener("touchstart",a,!0),document.removeEventListener("touchend",a,!0),document.removeEventListener("click",a,!0),document.removeEventListener("keydown",a,!0);for(var w=0;w<s._howls.length;w++)s._howls[w]._emit("unlock")}};return document.addEventListener("touchstart",a,!0),document.addEventListener("touchend",a,!0),document.addEventListener("click",a,!0),document.addEventListener("keydown",a,!0),s}},_obtainHtml5Audio:function(){var s=this||t;if(s._html5AudioPool.length)return s._html5AudioPool.pop();var a=new Audio().play();return a&&typeof Promise<"u"&&(a instanceof Promise||typeof a.then=="function")&&a.catch(function(){console.warn("HTML5 Audio pool exhausted, returning potentially locked audio object.")}),new Audio},_releaseHtml5Audio:function(s){var a=this||t;return s._unlocked&&a._html5AudioPool.push(s),a},_autoSuspend:function(){var s=this;if(!(!s.autoSuspend||!s.ctx||typeof s.ctx.suspend>"u"||!t.usingWebAudio)){for(var a=0;a<s._howls.length;a++)if(s._howls[a]._webAudio){for(var u=0;u<s._howls[a]._sounds.length;u++)if(!s._howls[a]._sounds[u]._paused)return s}return s._suspendTimer&&clearTimeout(s._suspendTimer),s._suspendTimer=setTimeout(function(){if(s.autoSuspend){s._suspendTimer=null,s.state="suspending";var g=function(){s.state="suspended",s._resumeAfterSuspend&&(delete s._resumeAfterSuspend,s._autoResume())};s.ctx.suspend().then(g,g)}},3e4),s}},_autoResume:function(){var s=this;if(!(!s.ctx||typeof s.ctx.resume>"u"||!t.usingWebAudio))return s.state==="running"&&s.ctx.state!=="interrupted"&&s._suspendTimer?(clearTimeout(s._suspendTimer),s._suspendTimer=null):s.state==="suspended"||s.state==="running"&&s.ctx.state==="interrupted"?(s.ctx.resume().then(function(){s.state="running";for(var a=0;a<s._howls.length;a++)s._howls[a]._emit("resume")}),s._suspendTimer&&(clearTimeout(s._suspendTimer),s._suspendTimer=null)):s.state==="suspending"&&(s._resumeAfterSuspend=!0),s}};var t=new e,i=function(s){var a=this;if(!s.src||s.src.length===0){console.error("An array of source files must be passed with any new Howl.");return}a.init(s)};i.prototype={init:function(s){var a=this;return t.ctx||p(),a._autoplay=s.autoplay||!1,a._format=typeof s.format!="string"?s.format:[s.format],a._html5=s.html5||!1,a._muted=s.mute||!1,a._loop=s.loop||!1,a._pool=s.pool||5,a._preload=typeof s.preload=="boolean"||s.preload==="metadata"?s.preload:!0,a._rate=s.rate||1,a._sprite=s.sprite||{},a._src=typeof s.src!="string"?s.src:[s.src],a._volume=s.volume!==void 0?s.volume:1,a._xhr={method:s.xhr&&s.xhr.method?s.xhr.method:"GET",headers:s.xhr&&s.xhr.headers?s.xhr.headers:null,withCredentials:s.xhr&&s.xhr.withCredentials?s.xhr.withCredentials:!1},a._duration=0,a._state="unloaded",a._sounds=[],a._endTimers={},a._queue=[],a._playLock=!1,a._onend=s.onend?[{fn:s.onend}]:[],a._onfade=s.onfade?[{fn:s.onfade}]:[],a._onload=s.onload?[{fn:s.onload}]:[],a._onloaderror=s.onloaderror?[{fn:s.onloaderror}]:[],a._onplayerror=s.onplayerror?[{fn:s.onplayerror}]:[],a._onpause=s.onpause?[{fn:s.onpause}]:[],a._onplay=s.onplay?[{fn:s.onplay}]:[],a._onstop=s.onstop?[{fn:s.onstop}]:[],a._onmute=s.onmute?[{fn:s.onmute}]:[],a._onvolume=s.onvolume?[{fn:s.onvolume}]:[],a._onrate=s.onrate?[{fn:s.onrate}]:[],a._onseek=s.onseek?[{fn:s.onseek}]:[],a._onunlock=s.onunlock?[{fn:s.onunlock}]:[],a._onresume=[],a._webAudio=t.usingWebAudio&&!a._html5,typeof t.ctx<"u"&&t.ctx&&t.autoUnlock&&t._unlockAudio(),t._howls.push(a),a._autoplay&&a._queue.push({event:"play",action:function(){a.play()}}),a._preload&&a._preload!=="none"&&a.load(),a},load:function(){var s=this,a=null;if(t.noAudio){s._emit("loaderror",null,"No audio support.");return}typeof s._src=="string"&&(s._src=[s._src]);for(var u=0;u<s._src.length;u++){var g,_;if(s._format&&s._format[u])g=s._format[u];else{if(_=s._src[u],typeof _!="string"){s._emit("loaderror",null,"Non-string found in selected audio sources - ignoring.");continue}g=/^data:audio\/([^;,]+);/i.exec(_),g||(g=/\.([^.]+)$/.exec(_.split("?",1)[0])),g&&(g=g[1].toLowerCase())}if(g||console.warn('No file extension was found. Consider using the "format" property or specify an extension.'),g&&t.codecs(g)){a=s._src[u];break}}if(!a){s._emit("loaderror",null,"No codec support for selected audio sources.");return}return s._src=a,s._state="loading",window.location.protocol==="https:"&&a.slice(0,5)==="http:"&&(s._html5=!0,s._webAudio=!1),new r(s),s._webAudio&&o(s),s},play:function(s,a){var u=this,g=null;if(typeof s=="number")g=s,s=null;else{if(typeof s=="string"&&u._state==="loaded"&&!u._sprite[s])return null;if(typeof s>"u"&&(s="__default",!u._playLock)){for(var _=0,f=0;f<u._sounds.length;f++)u._sounds[f]._paused&&!u._sounds[f]._ended&&(_++,g=u._sounds[f]._id);_===1?s=null:g=null}}var v=g?u._soundById(g):u._inactiveSound();if(!v)return null;if(g&&!s&&(s=v._sprite||"__default"),u._state!=="loaded"){v._sprite=s,v._ended=!1;var y=v._id;return u._queue.push({event:"play",action:function(){u.play(y)}}),y}if(g&&!v._paused)return a||u._loadQueue("play"),v._id;u._webAudio&&t._autoResume();var x=Math.max(0,v._seek>0?v._seek:u._sprite[s][0]/1e3),w=Math.max(0,(u._sprite[s][0]+u._sprite[s][1])/1e3-x),b=w*1e3/Math.abs(v._rate),C=u._sprite[s][0]/1e3,T=(u._sprite[s][0]+u._sprite[s][1])/1e3;v._sprite=s,v._ended=!1;var S=function(){v._paused=!1,v._seek=x,v._start=C,v._stop=T,v._loop=!!(v._loop||u._sprite[s][2])};if(x>=T){u._ended(v);return}var A=v._node;if(u._webAudio){var P=function(){u._playLock=!1,S(),u._refreshBuffer(v);var E=v._muted||u._muted?0:v._volume;A.gain.setValueAtTime(E,t.ctx.currentTime),v._playStart=t.ctx.currentTime,typeof A.bufferSource.start>"u"?v._loop?A.bufferSource.noteGrainOn(0,x,86400):A.bufferSource.noteGrainOn(0,x,w):v._loop?A.bufferSource.start(0,x,86400):A.bufferSource.start(0,x,w),b!==1/0&&(u._endTimers[v._id]=setTimeout(u._ended.bind(u,v),b)),a||setTimeout(function(){u._emit("play",v._id),u._loadQueue()},0)};t.state==="running"&&t.ctx.state!=="interrupted"?P():(u._playLock=!0,u.once("resume",P),u._clearTimer(v._id))}else{var I=function(){A.currentTime=x,A.muted=v._muted||u._muted||t._muted||A.muted,A.volume=v._volume*t.volume(),A.playbackRate=v._rate;try{var E=A.play();if(E&&typeof Promise<"u"&&(E instanceof Promise||typeof E.then=="function")?(u._playLock=!0,S(),E.then(function(){u._playLock=!1,A._unlocked=!0,a?u._loadQueue():u._emit("play",v._id)}).catch(function(){u._playLock=!1,u._emit("playerror",v._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),v._ended=!0,v._paused=!0})):a||(u._playLock=!1,S(),u._emit("play",v._id)),A.playbackRate=v._rate,A.paused){u._emit("playerror",v._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");return}s!=="__default"||v._loop?u._endTimers[v._id]=setTimeout(u._ended.bind(u,v),b):(u._endTimers[v._id]=function(){u._ended(v),A.removeEventListener("ended",u._endTimers[v._id],!1)},A.addEventListener("ended",u._endTimers[v._id],!1))}catch(F){u._emit("playerror",v._id,F)}};A.src==="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"&&(A.src=u._src,A.load());var M=window&&window.ejecta||!A.readyState&&t._navigator.isCocoonJS;if(A.readyState>=3||M)I();else{u._playLock=!0,u._state="loading";var R=function(){u._state="loaded",I(),A.removeEventListener(t._canPlayEvent,R,!1)};A.addEventListener(t._canPlayEvent,R,!1),u._clearTimer(v._id)}}return v._id},pause:function(s){var a=this;if(a._state!=="loaded"||a._playLock)return a._queue.push({event:"pause",action:function(){a.pause(s)}}),a;for(var u=a._getSoundIds(s),g=0;g<u.length;g++){a._clearTimer(u[g]);var _=a._soundById(u[g]);if(_&&!_._paused&&(_._seek=a.seek(u[g]),_._rateSeek=0,_._paused=!0,a._stopFade(u[g]),_._node))if(a._webAudio){if(!_._node.bufferSource)continue;typeof _._node.bufferSource.stop>"u"?_._node.bufferSource.noteOff(0):_._node.bufferSource.stop(0),a._cleanBuffer(_._node)}else(!isNaN(_._node.duration)||_._node.duration===1/0)&&_._node.pause();arguments[1]||a._emit("pause",_?_._id:null)}return a},stop:function(s,a){var u=this;if(u._state!=="loaded"||u._playLock)return u._queue.push({event:"stop",action:function(){u.stop(s)}}),u;for(var g=u._getSoundIds(s),_=0;_<g.length;_++){u._clearTimer(g[_]);var f=u._soundById(g[_]);f&&(f._seek=f._start||0,f._rateSeek=0,f._paused=!0,f._ended=!0,u._stopFade(g[_]),f._node&&(u._webAudio?f._node.bufferSource&&(typeof f._node.bufferSource.stop>"u"?f._node.bufferSource.noteOff(0):f._node.bufferSource.stop(0),u._cleanBuffer(f._node)):(!isNaN(f._node.duration)||f._node.duration===1/0)&&(f._node.currentTime=f._start||0,f._node.pause(),f._node.duration===1/0&&u._clearSound(f._node))),a||u._emit("stop",f._id))}return u},mute:function(s,a){var u=this;if(u._state!=="loaded"||u._playLock)return u._queue.push({event:"mute",action:function(){u.mute(s,a)}}),u;if(typeof a>"u")if(typeof s=="boolean")u._muted=s;else return u._muted;for(var g=u._getSoundIds(a),_=0;_<g.length;_++){var f=u._soundById(g[_]);f&&(f._muted=s,f._interval&&u._stopFade(f._id),u._webAudio&&f._node?f._node.gain.setValueAtTime(s?0:f._volume,t.ctx.currentTime):f._node&&(f._node.muted=t._muted?!0:s),u._emit("mute",f._id))}return u},volume:function(){var s=this,a=arguments,u,g;if(a.length===0)return s._volume;if(a.length===1||a.length===2&&typeof a[1]>"u"){var _=s._getSoundIds(),f=_.indexOf(a[0]);f>=0?g=parseInt(a[0],10):u=parseFloat(a[0])}else a.length>=2&&(u=parseFloat(a[0]),g=parseInt(a[1],10));var v;if(typeof u<"u"&&u>=0&&u<=1){if(s._state!=="loaded"||s._playLock)return s._queue.push({event:"volume",action:function(){s.volume.apply(s,a)}}),s;typeof g>"u"&&(s._volume=u),g=s._getSoundIds(g);for(var y=0;y<g.length;y++)v=s._soundById(g[y]),v&&(v._volume=u,a[2]||s._stopFade(g[y]),s._webAudio&&v._node&&!v._muted?v._node.gain.setValueAtTime(u,t.ctx.currentTime):v._node&&!v._muted&&(v._node.volume=u*t.volume()),s._emit("volume",v._id))}else return v=g?s._soundById(g):s._sounds[0],v?v._volume:0;return s},fade:function(s,a,u,g){var _=this;if(_._state!=="loaded"||_._playLock)return _._queue.push({event:"fade",action:function(){_.fade(s,a,u,g)}}),_;s=Math.min(Math.max(0,parseFloat(s)),1),a=Math.min(Math.max(0,parseFloat(a)),1),u=parseFloat(u),_.volume(s,g);for(var f=_._getSoundIds(g),v=0;v<f.length;v++){var y=_._soundById(f[v]);if(y){if(g||_._stopFade(f[v]),_._webAudio&&!y._muted){var x=t.ctx.currentTime,w=x+u/1e3;y._volume=s,y._node.gain.setValueAtTime(s,x),y._node.gain.linearRampToValueAtTime(a,w)}_._startFadeInterval(y,s,a,u,f[v],typeof g>"u")}}return _},_startFadeInterval:function(s,a,u,g,_,f){var v=this,y=a,x=u-a,w=Math.abs(x/.01),b=Math.max(4,w>0?g/w:g),C=Date.now();s._fadeTo=u,s._interval=setInterval(function(){var T=(Date.now()-C)/g;C=Date.now(),y+=x*T,y=Math.round(y*100)/100,x<0?y=Math.max(u,y):y=Math.min(u,y),v._webAudio?s._volume=y:v.volume(y,s._id,!0),f&&(v._volume=y),(u<a&&y<=u||u>a&&y>=u)&&(clearInterval(s._interval),s._interval=null,s._fadeTo=null,v.volume(u,s._id),v._emit("fade",s._id))},b)},_stopFade:function(s){var a=this,u=a._soundById(s);return u&&u._interval&&(a._webAudio&&u._node.gain.cancelScheduledValues(t.ctx.currentTime),clearInterval(u._interval),u._interval=null,a.volume(u._fadeTo,s),u._fadeTo=null,a._emit("fade",s)),a},loop:function(){var s=this,a=arguments,u,g,_;if(a.length===0)return s._loop;if(a.length===1)if(typeof a[0]=="boolean")u=a[0],s._loop=u;else return _=s._soundById(parseInt(a[0],10)),_?_._loop:!1;else a.length===2&&(u=a[0],g=parseInt(a[1],10));for(var f=s._getSoundIds(g),v=0;v<f.length;v++)_=s._soundById(f[v]),_&&(_._loop=u,s._webAudio&&_._node&&_._node.bufferSource&&(_._node.bufferSource.loop=u,u&&(_._node.bufferSource.loopStart=_._start||0,_._node.bufferSource.loopEnd=_._stop,s.playing(f[v])&&(s.pause(f[v],!0),s.play(f[v],!0)))));return s},rate:function(){var s=this,a=arguments,u,g;if(a.length===0)g=s._sounds[0]._id;else if(a.length===1){var _=s._getSoundIds(),f=_.indexOf(a[0]);f>=0?g=parseInt(a[0],10):u=parseFloat(a[0])}else a.length===2&&(u=parseFloat(a[0]),g=parseInt(a[1],10));var v;if(typeof u=="number"){if(s._state!=="loaded"||s._playLock)return s._queue.push({event:"rate",action:function(){s.rate.apply(s,a)}}),s;typeof g>"u"&&(s._rate=u),g=s._getSoundIds(g);for(var y=0;y<g.length;y++)if(v=s._soundById(g[y]),v){s.playing(g[y])&&(v._rateSeek=s.seek(g[y]),v._playStart=s._webAudio?t.ctx.currentTime:v._playStart),v._rate=u,s._webAudio&&v._node&&v._node.bufferSource?v._node.bufferSource.playbackRate.setValueAtTime(u,t.ctx.currentTime):v._node&&(v._node.playbackRate=u);var x=s.seek(g[y]),w=(s._sprite[v._sprite][0]+s._sprite[v._sprite][1])/1e3-x,b=w*1e3/Math.abs(v._rate);(s._endTimers[g[y]]||!v._paused)&&(s._clearTimer(g[y]),s._endTimers[g[y]]=setTimeout(s._ended.bind(s,v),b)),s._emit("rate",v._id)}}else return v=s._soundById(g),v?v._rate:s._rate;return s},seek:function(){var s=this,a=arguments,u,g;if(a.length===0)s._sounds.length&&(g=s._sounds[0]._id);else if(a.length===1){var _=s._getSoundIds(),f=_.indexOf(a[0]);f>=0?g=parseInt(a[0],10):s._sounds.length&&(g=s._sounds[0]._id,u=parseFloat(a[0]))}else a.length===2&&(u=parseFloat(a[0]),g=parseInt(a[1],10));if(typeof g>"u")return 0;if(typeof u=="number"&&(s._state!=="loaded"||s._playLock))return s._queue.push({event:"seek",action:function(){s.seek.apply(s,a)}}),s;var v=s._soundById(g);if(v)if(typeof u=="number"&&u>=0){var y=s.playing(g);y&&s.pause(g,!0),v._seek=u,v._ended=!1,s._clearTimer(g),!s._webAudio&&v._node&&!isNaN(v._node.duration)&&(v._node.currentTime=u);var x=function(){y&&s.play(g,!0),s._emit("seek",g)};if(y&&!s._webAudio){var w=function(){s._playLock?setTimeout(w,0):x()};setTimeout(w,0)}else x()}else if(s._webAudio){var b=s.playing(g)?t.ctx.currentTime-v._playStart:0,C=v._rateSeek?v._rateSeek-v._seek:0;return v._seek+(C+b*Math.abs(v._rate))}else return v._node.currentTime;return s},playing:function(s){var a=this;if(typeof s=="number"){var u=a._soundById(s);return u?!u._paused:!1}for(var g=0;g<a._sounds.length;g++)if(!a._sounds[g]._paused)return!0;return!1},duration:function(s){var a=this,u=a._duration,g=a._soundById(s);return g&&(u=a._sprite[g._sprite][1]/1e3),u},state:function(){return this._state},unload:function(){for(var s=this,a=s._sounds,u=0;u<a.length;u++)a[u]._paused||s.stop(a[u]._id),s._webAudio||(s._clearSound(a[u]._node),a[u]._node.removeEventListener("error",a[u]._errorFn,!1),a[u]._node.removeEventListener(t._canPlayEvent,a[u]._loadFn,!1),a[u]._node.removeEventListener("ended",a[u]._endFn,!1),t._releaseHtml5Audio(a[u]._node)),delete a[u]._node,s._clearTimer(a[u]._id);var g=t._howls.indexOf(s);g>=0&&t._howls.splice(g,1);var _=!0;for(u=0;u<t._howls.length;u++)if(t._howls[u]._src===s._src||s._src.indexOf(t._howls[u]._src)>=0){_=!1;break}return l&&_&&delete l[s._src],t.noAudio=!1,s._state="unloaded",s._sounds=[],s=null,null},on:function(s,a,u,g){var _=this,f=_["_on"+s];return typeof a=="function"&&f.push(g?{id:u,fn:a,once:g}:{id:u,fn:a}),_},off:function(s,a,u){var g=this,_=g["_on"+s],f=0;if(typeof a=="number"&&(u=a,a=null),a||u)for(f=0;f<_.length;f++){var v=u===_[f].id;if(a===_[f].fn&&v||!a&&v){_.splice(f,1);break}}else if(s)g["_on"+s]=[];else{var y=Object.keys(g);for(f=0;f<y.length;f++)y[f].indexOf("_on")===0&&Array.isArray(g[y[f]])&&(g[y[f]]=[])}return g},once:function(s,a,u){var g=this;return g.on(s,a,u,1),g},_emit:function(s,a,u){for(var g=this,_=g["_on"+s],f=_.length-1;f>=0;f--)(!_[f].id||_[f].id===a||s==="load")&&(setTimeout((function(v){v.call(this,a,u)}).bind(g,_[f].fn),0),_[f].once&&g.off(s,_[f].fn,_[f].id));return g._loadQueue(s),g},_loadQueue:function(s){var a=this;if(a._queue.length>0){var u=a._queue[0];u.event===s&&(a._queue.shift(),a._loadQueue()),s||u.action()}return a},_ended:function(s){var a=this,u=s._sprite;if(!a._webAudio&&s._node&&!s._node.paused&&!s._node.ended&&s._node.currentTime<s._stop)return setTimeout(a._ended.bind(a,s),100),a;var g=!!(s._loop||a._sprite[u][2]);if(a._emit("end",s._id),!a._webAudio&&g&&a.stop(s._id,!0).play(s._id),a._webAudio&&g){a._emit("play",s._id),s._seek=s._start||0,s._rateSeek=0,s._playStart=t.ctx.currentTime;var _=(s._stop-s._start)*1e3/Math.abs(s._rate);a._endTimers[s._id]=setTimeout(a._ended.bind(a,s),_)}return a._webAudio&&!g&&(s._paused=!0,s._ended=!0,s._seek=s._start||0,s._rateSeek=0,a._clearTimer(s._id),a._cleanBuffer(s._node),t._autoSuspend()),!a._webAudio&&!g&&a.stop(s._id,!0),a},_clearTimer:function(s){var a=this;if(a._endTimers[s]){if(typeof a._endTimers[s]!="function")clearTimeout(a._endTimers[s]);else{var u=a._soundById(s);u&&u._node&&u._node.removeEventListener("ended",a._endTimers[s],!1)}delete a._endTimers[s]}return a},_soundById:function(s){for(var a=this,u=0;u<a._sounds.length;u++)if(s===a._sounds[u]._id)return a._sounds[u];return null},_inactiveSound:function(){var s=this;s._drain();for(var a=0;a<s._sounds.length;a++)if(s._sounds[a]._ended)return s._sounds[a].reset();return new r(s)},_drain:function(){var s=this,a=s._pool,u=0,g=0;if(!(s._sounds.length<a)){for(g=0;g<s._sounds.length;g++)s._sounds[g]._ended&&u++;for(g=s._sounds.length-1;g>=0;g--){if(u<=a)return;s._sounds[g]._ended&&(s._webAudio&&s._sounds[g]._node&&s._sounds[g]._node.disconnect(0),s._sounds.splice(g,1),u--)}}},_getSoundIds:function(s){var a=this;if(typeof s>"u"){for(var u=[],g=0;g<a._sounds.length;g++)u.push(a._sounds[g]._id);return u}else return[s]},_refreshBuffer:function(s){var a=this;return s._node.bufferSource=t.ctx.createBufferSource(),s._node.bufferSource.buffer=l[a._src],s._panner?s._node.bufferSource.connect(s._panner):s._node.bufferSource.connect(s._node),s._node.bufferSource.loop=s._loop,s._loop&&(s._node.bufferSource.loopStart=s._start||0,s._node.bufferSource.loopEnd=s._stop||0),s._node.bufferSource.playbackRate.setValueAtTime(s._rate,t.ctx.currentTime),a},_cleanBuffer:function(s){var a=this,u=t._navigator&&t._navigator.vendor.indexOf("Apple")>=0;if(!s.bufferSource)return a;if(t._scratchBuffer&&s.bufferSource&&(s.bufferSource.onended=null,s.bufferSource.disconnect(0),u))try{s.bufferSource.buffer=t._scratchBuffer}catch{}return s.bufferSource=null,a},_clearSound:function(s){var a=/MSIE |Trident\//.test(t._navigator&&t._navigator.userAgent);a||(s.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var r=function(s){this._parent=s,this.init()};r.prototype={init:function(){var s=this,a=s._parent;return s._muted=a._muted,s._loop=a._loop,s._volume=a._volume,s._rate=a._rate,s._seek=0,s._paused=!0,s._ended=!0,s._sprite="__default",s._id=++t._counter,a._sounds.push(s),s.create(),s},create:function(){var s=this,a=s._parent,u=t._muted||s._muted||s._parent._muted?0:s._volume;return a._webAudio?(s._node=typeof t.ctx.createGain>"u"?t.ctx.createGainNode():t.ctx.createGain(),s._node.gain.setValueAtTime(u,t.ctx.currentTime),s._node.paused=!0,s._node.connect(t.masterGain)):t.noAudio||(s._node=t._obtainHtml5Audio(),s._errorFn=s._errorListener.bind(s),s._node.addEventListener("error",s._errorFn,!1),s._loadFn=s._loadListener.bind(s),s._node.addEventListener(t._canPlayEvent,s._loadFn,!1),s._endFn=s._endListener.bind(s),s._node.addEventListener("ended",s._endFn,!1),s._node.src=a._src,s._node.preload=a._preload===!0?"auto":a._preload,s._node.volume=u*t.volume(),s._node.load()),s},reset:function(){var s=this,a=s._parent;return s._muted=a._muted,s._loop=a._loop,s._volume=a._volume,s._rate=a._rate,s._seek=0,s._rateSeek=0,s._paused=!0,s._ended=!0,s._sprite="__default",s._id=++t._counter,s},_errorListener:function(){var s=this;s._parent._emit("loaderror",s._id,s._node.error?s._node.error.code:0),s._node.removeEventListener("error",s._errorFn,!1)},_loadListener:function(){var s=this,a=s._parent;a._duration=Math.ceil(s._node.duration*10)/10,Object.keys(a._sprite).length===0&&(a._sprite={__default:[0,a._duration*1e3]}),a._state!=="loaded"&&(a._state="loaded",a._emit("load"),a._loadQueue()),s._node.removeEventListener(t._canPlayEvent,s._loadFn,!1)},_endListener:function(){var s=this,a=s._parent;a._duration===1/0&&(a._duration=Math.ceil(s._node.duration*10)/10,a._sprite.__default[1]===1/0&&(a._sprite.__default[1]=a._duration*1e3),a._ended(s)),s._node.removeEventListener("ended",s._endFn,!1)}};var l={},o=function(s){var a=s._src;if(l[a]){s._duration=l[a].duration,m(s);return}if(/^data:[^;]+;base64,/.test(a)){for(var u=atob(a.split(",")[1]),g=new Uint8Array(u.length),_=0;_<u.length;++_)g[_]=u.charCodeAt(_);h(g.buffer,s)}else{var f=new XMLHttpRequest;f.open(s._xhr.method,a,!0),f.withCredentials=s._xhr.withCredentials,f.responseType="arraybuffer",s._xhr.headers&&Object.keys(s._xhr.headers).forEach(function(v){f.setRequestHeader(v,s._xhr.headers[v])}),f.onload=function(){var v=(f.status+"")[0];if(v!=="0"&&v!=="2"&&v!=="3"){s._emit("loaderror",null,"Failed loading audio file with status: "+f.status+".");return}h(f.response,s)},f.onerror=function(){s._webAudio&&(s._html5=!0,s._webAudio=!1,s._sounds=[],delete l[a],s.load())},c(f)}},c=function(s){try{s.send()}catch{s.onerror()}},h=function(s,a){var u=function(){a._emit("loaderror",null,"Decoding audio data failed.")},g=function(_){_&&a._sounds.length>0?(l[a._src]=_,m(a,_)):u()};typeof Promise<"u"&&t.ctx.decodeAudioData.length===1?t.ctx.decodeAudioData(s).then(g).catch(u):t.ctx.decodeAudioData(s,g,u)},m=function(s,a){a&&!s._duration&&(s._duration=a.duration),Object.keys(s._sprite).length===0&&(s._sprite={__default:[0,s._duration*1e3]}),s._state!=="loaded"&&(s._state="loaded",s._emit("load"),s._loadQueue())},p=function(){if(t.usingWebAudio){try{typeof AudioContext<"u"?t.ctx=new AudioContext:typeof webkitAudioContext<"u"?t.ctx=new webkitAudioContext:t.usingWebAudio=!1}catch{t.usingWebAudio=!1}t.ctx||(t.usingWebAudio=!1);var s=/iP(hone|od|ad)/.test(t._navigator&&t._navigator.platform),a=t._navigator&&t._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),u=a?parseInt(a[1],10):null;if(s&&u&&u<9){var g=/safari/.test(t._navigator&&t._navigator.userAgent.toLowerCase());t._navigator&&!g&&(t.usingWebAudio=!1)}t.usingWebAudio&&(t.masterGain=typeof t.ctx.createGain>"u"?t.ctx.createGainNode():t.ctx.createGain(),t.masterGain.gain.setValueAtTime(t._muted?0:t._volume,t.ctx.currentTime),t.masterGain.connect(t.ctx.destination)),t._setup()}};n.Howler=t,n.Howl=i,typeof Ze<"u"?(Ze.HowlerGlobal=e,Ze.Howler=t,Ze.Howl=i,Ze.Sound=r):typeof window<"u"&&(window.HowlerGlobal=e,window.Howler=t,window.Howl=i,window.Sound=r)})();/*!
|
|
3690
|
+
* Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported.
|
|
3691
|
+
*
|
|
3692
|
+
* howler.js v2.2.4
|
|
3693
|
+
* howlerjs.com
|
|
3694
|
+
*
|
|
3695
|
+
* (c) 2013-2020, James Simpson of GoldFire Studios
|
|
3696
|
+
* goldfirestudios.com
|
|
3697
|
+
*
|
|
3698
|
+
* MIT License
|
|
3699
|
+
*/(function(){HowlerGlobal.prototype._pos=[0,0,0],HowlerGlobal.prototype._orientation=[0,0,-1,0,1,0],HowlerGlobal.prototype.stereo=function(t){var i=this;if(!i.ctx||!i.ctx.listener)return i;for(var r=i._howls.length-1;r>=0;r--)i._howls[r].stereo(t);return i},HowlerGlobal.prototype.pos=function(t,i,r){var l=this;if(!l.ctx||!l.ctx.listener)return l;if(i=typeof i!="number"?l._pos[1]:i,r=typeof r!="number"?l._pos[2]:r,typeof t=="number")l._pos=[t,i,r],typeof l.ctx.listener.positionX<"u"?(l.ctx.listener.positionX.setTargetAtTime(l._pos[0],Howler.ctx.currentTime,.1),l.ctx.listener.positionY.setTargetAtTime(l._pos[1],Howler.ctx.currentTime,.1),l.ctx.listener.positionZ.setTargetAtTime(l._pos[2],Howler.ctx.currentTime,.1)):l.ctx.listener.setPosition(l._pos[0],l._pos[1],l._pos[2]);else return l._pos;return l},HowlerGlobal.prototype.orientation=function(t,i,r,l,o,c){var h=this;if(!h.ctx||!h.ctx.listener)return h;var m=h._orientation;if(i=typeof i!="number"?m[1]:i,r=typeof r!="number"?m[2]:r,l=typeof l!="number"?m[3]:l,o=typeof o!="number"?m[4]:o,c=typeof c!="number"?m[5]:c,typeof t=="number")h._orientation=[t,i,r,l,o,c],typeof h.ctx.listener.forwardX<"u"?(h.ctx.listener.forwardX.setTargetAtTime(t,Howler.ctx.currentTime,.1),h.ctx.listener.forwardY.setTargetAtTime(i,Howler.ctx.currentTime,.1),h.ctx.listener.forwardZ.setTargetAtTime(r,Howler.ctx.currentTime,.1),h.ctx.listener.upX.setTargetAtTime(l,Howler.ctx.currentTime,.1),h.ctx.listener.upY.setTargetAtTime(o,Howler.ctx.currentTime,.1),h.ctx.listener.upZ.setTargetAtTime(c,Howler.ctx.currentTime,.1)):h.ctx.listener.setOrientation(t,i,r,l,o,c);else return m;return h},Howl.prototype.init=function(t){return function(i){var r=this;return r._orientation=i.orientation||[1,0,0],r._stereo=i.stereo||null,r._pos=i.pos||null,r._pannerAttr={coneInnerAngle:typeof i.coneInnerAngle<"u"?i.coneInnerAngle:360,coneOuterAngle:typeof i.coneOuterAngle<"u"?i.coneOuterAngle:360,coneOuterGain:typeof i.coneOuterGain<"u"?i.coneOuterGain:0,distanceModel:typeof i.distanceModel<"u"?i.distanceModel:"inverse",maxDistance:typeof i.maxDistance<"u"?i.maxDistance:1e4,panningModel:typeof i.panningModel<"u"?i.panningModel:"HRTF",refDistance:typeof i.refDistance<"u"?i.refDistance:1,rolloffFactor:typeof i.rolloffFactor<"u"?i.rolloffFactor:1},r._onstereo=i.onstereo?[{fn:i.onstereo}]:[],r._onpos=i.onpos?[{fn:i.onpos}]:[],r._onorientation=i.onorientation?[{fn:i.onorientation}]:[],t.call(this,i)}}(Howl.prototype.init),Howl.prototype.stereo=function(t,i){var r=this;if(!r._webAudio)return r;if(r._state!=="loaded")return r._queue.push({event:"stereo",action:function(){r.stereo(t,i)}}),r;var l=typeof Howler.ctx.createStereoPanner>"u"?"spatial":"stereo";if(typeof i>"u")if(typeof t=="number")r._stereo=t,r._pos=[t,0,0];else return r._stereo;for(var o=r._getSoundIds(i),c=0;c<o.length;c++){var h=r._soundById(o[c]);if(h)if(typeof t=="number")h._stereo=t,h._pos=[t,0,0],h._node&&(h._pannerAttr.panningModel="equalpower",(!h._panner||!h._panner.pan)&&e(h,l),l==="spatial"?typeof h._panner.positionX<"u"?(h._panner.positionX.setValueAtTime(t,Howler.ctx.currentTime),h._panner.positionY.setValueAtTime(0,Howler.ctx.currentTime),h._panner.positionZ.setValueAtTime(0,Howler.ctx.currentTime)):h._panner.setPosition(t,0,0):h._panner.pan.setValueAtTime(t,Howler.ctx.currentTime)),r._emit("stereo",h._id);else return h._stereo}return r},Howl.prototype.pos=function(t,i,r,l){var o=this;if(!o._webAudio)return o;if(o._state!=="loaded")return o._queue.push({event:"pos",action:function(){o.pos(t,i,r,l)}}),o;if(i=typeof i!="number"?0:i,r=typeof r!="number"?-.5:r,typeof l>"u")if(typeof t=="number")o._pos=[t,i,r];else return o._pos;for(var c=o._getSoundIds(l),h=0;h<c.length;h++){var m=o._soundById(c[h]);if(m)if(typeof t=="number")m._pos=[t,i,r],m._node&&((!m._panner||m._panner.pan)&&e(m,"spatial"),typeof m._panner.positionX<"u"?(m._panner.positionX.setValueAtTime(t,Howler.ctx.currentTime),m._panner.positionY.setValueAtTime(i,Howler.ctx.currentTime),m._panner.positionZ.setValueAtTime(r,Howler.ctx.currentTime)):m._panner.setPosition(t,i,r)),o._emit("pos",m._id);else return m._pos}return o},Howl.prototype.orientation=function(t,i,r,l){var o=this;if(!o._webAudio)return o;if(o._state!=="loaded")return o._queue.push({event:"orientation",action:function(){o.orientation(t,i,r,l)}}),o;if(i=typeof i!="number"?o._orientation[1]:i,r=typeof r!="number"?o._orientation[2]:r,typeof l>"u")if(typeof t=="number")o._orientation=[t,i,r];else return o._orientation;for(var c=o._getSoundIds(l),h=0;h<c.length;h++){var m=o._soundById(c[h]);if(m)if(typeof t=="number")m._orientation=[t,i,r],m._node&&(m._panner||(m._pos||(m._pos=o._pos||[0,0,-.5]),e(m,"spatial")),typeof m._panner.orientationX<"u"?(m._panner.orientationX.setValueAtTime(t,Howler.ctx.currentTime),m._panner.orientationY.setValueAtTime(i,Howler.ctx.currentTime),m._panner.orientationZ.setValueAtTime(r,Howler.ctx.currentTime)):m._panner.setOrientation(t,i,r)),o._emit("orientation",m._id);else return m._orientation}return o},Howl.prototype.pannerAttr=function(){var t=this,i=arguments,r,l,o;if(!t._webAudio)return t;if(i.length===0)return t._pannerAttr;if(i.length===1)if(typeof i[0]=="object")r=i[0],typeof l>"u"&&(r.pannerAttr||(r.pannerAttr={coneInnerAngle:r.coneInnerAngle,coneOuterAngle:r.coneOuterAngle,coneOuterGain:r.coneOuterGain,distanceModel:r.distanceModel,maxDistance:r.maxDistance,refDistance:r.refDistance,rolloffFactor:r.rolloffFactor,panningModel:r.panningModel}),t._pannerAttr={coneInnerAngle:typeof r.pannerAttr.coneInnerAngle<"u"?r.pannerAttr.coneInnerAngle:t._coneInnerAngle,coneOuterAngle:typeof r.pannerAttr.coneOuterAngle<"u"?r.pannerAttr.coneOuterAngle:t._coneOuterAngle,coneOuterGain:typeof r.pannerAttr.coneOuterGain<"u"?r.pannerAttr.coneOuterGain:t._coneOuterGain,distanceModel:typeof r.pannerAttr.distanceModel<"u"?r.pannerAttr.distanceModel:t._distanceModel,maxDistance:typeof r.pannerAttr.maxDistance<"u"?r.pannerAttr.maxDistance:t._maxDistance,refDistance:typeof r.pannerAttr.refDistance<"u"?r.pannerAttr.refDistance:t._refDistance,rolloffFactor:typeof r.pannerAttr.rolloffFactor<"u"?r.pannerAttr.rolloffFactor:t._rolloffFactor,panningModel:typeof r.pannerAttr.panningModel<"u"?r.pannerAttr.panningModel:t._panningModel});else return o=t._soundById(parseInt(i[0],10)),o?o._pannerAttr:t._pannerAttr;else i.length===2&&(r=i[0],l=parseInt(i[1],10));for(var c=t._getSoundIds(l),h=0;h<c.length;h++)if(o=t._soundById(c[h]),o){var m=o._pannerAttr;m={coneInnerAngle:typeof r.coneInnerAngle<"u"?r.coneInnerAngle:m.coneInnerAngle,coneOuterAngle:typeof r.coneOuterAngle<"u"?r.coneOuterAngle:m.coneOuterAngle,coneOuterGain:typeof r.coneOuterGain<"u"?r.coneOuterGain:m.coneOuterGain,distanceModel:typeof r.distanceModel<"u"?r.distanceModel:m.distanceModel,maxDistance:typeof r.maxDistance<"u"?r.maxDistance:m.maxDistance,refDistance:typeof r.refDistance<"u"?r.refDistance:m.refDistance,rolloffFactor:typeof r.rolloffFactor<"u"?r.rolloffFactor:m.rolloffFactor,panningModel:typeof r.panningModel<"u"?r.panningModel:m.panningModel};var p=o._panner;p||(o._pos||(o._pos=t._pos||[0,0,-.5]),e(o,"spatial"),p=o._panner),p.coneInnerAngle=m.coneInnerAngle,p.coneOuterAngle=m.coneOuterAngle,p.coneOuterGain=m.coneOuterGain,p.distanceModel=m.distanceModel,p.maxDistance=m.maxDistance,p.refDistance=m.refDistance,p.rolloffFactor=m.rolloffFactor,p.panningModel=m.panningModel}return t},Sound.prototype.init=function(t){return function(){var i=this,r=i._parent;i._orientation=r._orientation,i._stereo=r._stereo,i._pos=r._pos,i._pannerAttr=r._pannerAttr,t.call(this),i._stereo?r.stereo(i._stereo):i._pos&&r.pos(i._pos[0],i._pos[1],i._pos[2],i._id)}}(Sound.prototype.init),Sound.prototype.reset=function(t){return function(){var i=this,r=i._parent;return i._orientation=r._orientation,i._stereo=r._stereo,i._pos=r._pos,i._pannerAttr=r._pannerAttr,i._stereo?r.stereo(i._stereo):i._pos?r.pos(i._pos[0],i._pos[1],i._pos[2],i._id):i._panner&&(i._panner.disconnect(0),i._panner=void 0,r._refreshBuffer(i)),t.call(this)}}(Sound.prototype.reset);var e=function(t,i){i=i||"spatial",i==="spatial"?(t._panner=Howler.ctx.createPanner(),t._panner.coneInnerAngle=t._pannerAttr.coneInnerAngle,t._panner.coneOuterAngle=t._pannerAttr.coneOuterAngle,t._panner.coneOuterGain=t._pannerAttr.coneOuterGain,t._panner.distanceModel=t._pannerAttr.distanceModel,t._panner.maxDistance=t._pannerAttr.maxDistance,t._panner.refDistance=t._pannerAttr.refDistance,t._panner.rolloffFactor=t._pannerAttr.rolloffFactor,t._panner.panningModel=t._pannerAttr.panningModel,typeof t._panner.positionX<"u"?(t._panner.positionX.setValueAtTime(t._pos[0],Howler.ctx.currentTime),t._panner.positionY.setValueAtTime(t._pos[1],Howler.ctx.currentTime),t._panner.positionZ.setValueAtTime(t._pos[2],Howler.ctx.currentTime)):t._panner.setPosition(t._pos[0],t._pos[1],t._pos[2]),typeof t._panner.orientationX<"u"?(t._panner.orientationX.setValueAtTime(t._orientation[0],Howler.ctx.currentTime),t._panner.orientationY.setValueAtTime(t._orientation[1],Howler.ctx.currentTime),t._panner.orientationZ.setValueAtTime(t._orientation[2],Howler.ctx.currentTime)):t._panner.setOrientation(t._orientation[0],t._orientation[1],t._orientation[2])):(t._panner=Howler.ctx.createStereoPanner(),t._panner.pan.setValueAtTime(t._stereo,Howler.ctx.currentTime)),t._panner.connect(t._node),t._paused||t._parent.pause(t._id,!0).play(t._id,!0)}})()})(Qs);const So="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjQxLjEwMAAAAAAAAAAAAAAA//NwwAAAAAAAAAAAAEluZm8AAAAPAAAAFAAACOAAICAgICwsLCwsNzc3NzdDQ0NDQ09PT09PW1tbW1tmZmZmZnJycnJyfn5+fn6KioqKipWVlZWVoaGhoaGtra2trbm5ubm5xcXFxcXQ0NDQ0Nzc3Nzc6Ojo6Oj09PT09P//////AAAAAExhdmM1OC43NQAAAAAAAAAAAAAAACQCwAAAAAAAAAjgTZykiAAAAAAAAAAAAAAAAAD/80DEABJhFmQCwwYUIDsKrsHAWBMRyeJYliQJBg5RYsWU/W3z/8OLc/3AAAQiIAIjv+7vUCJXd4jucQABAE3lwffiDBD+JC58oCH8H/1h/WH//1HPwTUMFrULH9ELKxULyTodFKYbO//zQsQRFFkScKDSRhyGWpIFpG91I7Fi/F6D2RWwN6TN/t9CiVSG5wMw74ogYcHoEwTFyMmTf4KkxEwmRfjXIYv1tpIOZRv/3O9ibtjR6gYmbGCgQ+Fk0mfSmybOX1cf78g7D6nP6qxCgf/zQMQbF+EacktaSABfy+3JKszHdMgcwwcl/kNFIuAo0I0DD1fWVs/crTSTTRInof3cmIwyLBwGQqCSLq7hyvtRPBB4aFyyXHov9X///7UXKqoIIcgcHict89/0y+n+nf/C0DIjB/+P//NCxBYZU9q0AYpoAHNyXSLn/+EjEbJclC4eJT//8e5aMAWeE4////wvAyAvYjZLjAD0Lg9D0kCU/////zwwBdJcYAehKBIwtYyx6FyXC4XP//////x7l83NDpfqd6gAcA/+wu9A2FGg//NAxAwXCnsq/5M4AhQKAOwmRvQRhjhOe5S8UkAmVHpU8IVU3lwejjIcayXOOceGwjf+D05I8oAu2x382o1ZHHV//31NU4441lmqcv///+RNGrUJKImnTf//iVYK1UZquoZESSy3egH/80LEChchBtMfyzAAk191v20qimbuNqavb211BthJKSJAG2aucbdLeVFVmRjZEVvzOggIwuUFDgvEZA7UeuUqNMLOraDQ5CVCk5m9BsmT3kbNrBdolcFSsqXGwQTWyYUX2wEDEgKkvZb/80DECRYRUpWsikYY1HXLbDZksYxtCHBShdHt/DgYCOM6r8AmUSpfGZYzH7ARMBCj1JtmY/hmwoGio0XBUShoklC5GsNeDR38RQ6d01DyrENtqp6mCJ5GJUckmpUBaIgYK6C0fPjmUf/zQsQLFil+cajTBhydxPRO4mLMWWSGQF2qa1f3PPlHQDJdzCxnwgkzB1SQohrpNRYRgtobv07tBLUFc27jQdWoQY0JNpiMJy654enBVoqnQR571uq/i9rpL1oAqAupJATLLk5L+QT3Kf/zQMQOE9D2bWFaGACZyWQZdt1rd3OVY8s/y2dBlg0m12PFzdFSlYrboY6gMOE1hJp7iFqmDcopF8F2OKEPnktdThRLoy9iuyj//0vD4+qf///++38OsIIFFhpEFZMC4s+gZmilJz1X//NCxBkaW8allZI4AWPWKBoLFWrwfuYvukbk4Rt9tBuJYOBoWpfzfjQaNMp//+OGEzzzDIif3+n/4PBIEt5hjDc9zxv/////nseeNDHGg0MQwxBEFn//////4TpB9d/s9thcHddpssFg//NAxAsVCT8GX5BAAigUAPBBdOBaKEIpaajR1VyCNH/gAwAfjRX8G7B4zfx0HANA8BpjQ6FhfqKxRBQURleGbrufzJywVGVfRdOzp5///ERCxhb//8wqijBAwUYMBCjVWZsv26uwYU3/80LEERRTIuTLwxABmdQgEBGKFNo9amfRWcpnayOUsKJ/UpWo/qyL////sj1b+pc3oarStSWpf/VP+hlotDN/0MVjKMKDAZGL/Ar8QWpCR0msAoVgrMoeT3xHIZd3qARkQge7hzlejQD/80DEGxPQ5sryeYYUBCI58AEvohe5nAMDcPxAbUxN6VCB4xCid97iaTyonF0l4upInmIpD//V0f/OllFls0vEBipVlYYRWhuzlHgpEiJSRmYJQaiptezfqvKm1PBRJKiq7M3s1yoqKv/zQsQmFBEGuojBkAQdCzTSpHY0FSwdboEQKi7pZN986g7UVOkf5ZR6VdbbQwZ+79PW6VoWdwZqA4VT2QGoxuuO0VZgbATjSNkSqqresUZ4lDGM5tfbuZzGHYfri5YKg0eDjgQjhm0Wpf/zQMQxE1jyoqhoxFD16D4jzQUUULEB1QXZhRIdIbHFtSlSvX5anFh11QTHaABkiBXOXoXxGW9galRr4fRiew3yOag/4HjxOydOM9ZyyokPlRKdFBa0CjY1luBiKXXwLw6oeMWEhjoS//NCxD4TUNKKIJpMJNTRh7nf/3kekmjdSWypy9UZXQgZMDh3pnAWB4O2M6nAaelR4r1OmVPFSwoksiWRUE1zc+f1lPc0ZudtdFDr4LLpoSwwGkpVO+oD6Tlb3HsYL7d+R1//td2LQMNF//NAxEwTaP5xYqJMCFlqIwAbEoCJNDEp9/3itYVbV6Yx/v0nuLdzyy50qHQw3cafmKlb6zBo0yXeRMnQG5J4jE7j4PFAkTSpQ9pexojMMsL0PIqP/Z1Xp/TpnVZZ27eWtNWRSSSyWyz/80LEWRSo1nDhWhgAlsstlkskgADyNOHqG5rlhLnSyI0a5oClU7uw0JnJQq2kTMBUYADEskGQ9wdHohh2xMKnCubKTIdyRgT83NEIrcfJpJOL3fV7l9cyXXJwJRDGpJLTZJF1+3OPUX3/80DEYiVyorJfmlgDRVRdYm21rHJXTVH0+ajd35ouiSF1tVcmLGnFummxbrhsXfHNzcf/2qgd/7XhppiSaYkmmQGRpnCsAMAEB4tQrXVA0VOiINSMWfljtMTHsRdZ3iL/V1neW6zvLf/zQsQnDSAiMFXMGADWd4i6zvEX+W/yzud5ZUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ==";let Co=class{constructor(){this.sound=new Qs.Howl({src:[So]})}play(){this.sound.play()}};const oe=n=>{var e,t;if(typeof n.destroy=="function"){n.destroy();return}for(;n.children.length>0;)oe(n.children[0]),(e=n.children[0])==null||e.removeFromParent();if(n instanceof d.Mesh)try{(t=n.geometry)==null||t.dispose()}catch{}};function Mo(n){return new d.Vector3(n[0],n[1],n[2])}function Po(){let n=3,e=Math.max(1/window.devicePixelRatio,.5);return window.innerWidth/window.innerHeight<.65&&(n=4,e=1/window.devicePixelRatio),{tiles:n,renderScale:e}}function Ro(n){let e=!1,t=!1,i=!1,r=1/0,l=1/0,o=1/0,c=-1/0,h=-1/0,m=-1/0,p=0,s=0;return n.traverse(u=>{if(u.isMesh&&u.geometry){const g=u;if(g.userData.ignoreSize||g.material.userData.isLOGO)return;g.geometry.computeBoundingBox();let _=g.geometry.attributes.position;const f=g.geometry.morphAttributes.position;let v=g.morphTargetInfluences;const y=Object.keys(g.morphTargetDictionary||{});y.includes("width")&&(t=!0),y.includes("length")&&(e=!0),y.includes("height")&&(i=!0);for(let x=0;x<_.count;x++){let w=_.getX(x),b=_.getY(x),C=_.getZ(x);s=Math.max(b,s),f&&v&&f.forEach((S,A)=>{const P=v&&v[A]||0;w+=S.getX(x)*P,b+=S.getY(x)*P,C+=S.getZ(x)*P}),w<r&&(r=w),b<l&&(l=b),C<o&&(o=C),w>c&&(c=w),b>h&&(h=b),C>m&&(m=C);const T=Math.sqrt(w*w+b*b);T>p&&(p=T)}}}),{box:new d.Box3(new d.Vector3(r,l,o),new d.Vector3(c,h,m)),maxRadius:p,height:s,hasWidth:t,hasLength:e,hasHeight:i}}function Io(n,e,t=null){let i=0;return function(){let r=t||this,l=arguments;clearTimeout(i),i=window.setTimeout(function(){n.apply(r,l)},e)}}class Eo{constructor(e,t,i){this.length=e,this.width=t,this.height=i}}const us=n=>{var i;let e=0,t=0;if(n.geometry){n.geometry.computeBoundingBox();const r=new d.Vector3;(i=n.geometry.boundingBox)==null||i.getSize(r),r.y?(t=r.y,!r.x&&r.z?e=r.z:r.x&&!r.z?e=r.x:r.x&&r.z&&(e=r.z)):(e=r.z,t=r.x)}return{width:e,height:t}};function Di(){var e;if(typeof navigator>"u")return!1;if(Fo())return!0;const n=(e=navigator.userAgent)==null?void 0:e.toLowerCase();return/iphone|ipad|ipod|android|mobile|blackberry|iemobile|opera mini/.test(n)}function Fo(){try{if(typeof wx<"u"&&wx.getSystemInfo||typeof my<"u"&&my.alert||typeof tt<"u"&&tt.getSystemInfo||typeof swan<"u"&&swan.getSystemInfo)return!0}catch{}return!1}const Zs=new Ar.GLTFExporter,ut=new xr.GLTFLoader,Nt=new wr.DRACOLoader;let We="./draco/";try{We=new URL("./draco/",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ot&&Ot.src||new URL("shop-components.cjs",document.baseURI).href).href}catch{We="./draco/"}typeof window<"u"&&window.dracoPath&&(We=window.dracoPath);Nt.setDecoderConfig({type:"wasm"});Nt.setDecoderPath(We.endsWith("/")?We:`${We}/`);Nt.preload();ut.setDRACOLoader(Nt);const Do=new br.DRACOExporter,fs=[115,103,108,98];function Bo(n,e,t){const i=JSON.stringify(e),r=new TextEncoder().encode(i),l=new Uint8Array([115,103,108,98]),o=new Uint8Array(2);o[0]=t>>8,o[1]=t&255;const c=new Uint8Array(4);c[0]=r.length>>24,c[1]=r.length>>16&255,c[2]=r.length>>8&255,c[3]=r.length&255;const h=new Uint8Array(n),m=l.length+o.length+c.length+r.length+h.length,p=new Uint8Array(m);let s=0;return p.set(l,s),s+=l.length,p.set(o,s),s+=o.length,p.set(c,s),s+=c.length,p.set(r,s),s+=r.length,p.set(h,s),p.buffer}function Lo(n){const e=new Uint8Array(n.slice(0,4));let t=!0;for(let s=0;s<fs.length;s++)if(e[s]!==fs[s]){t=!1;break}if(!t)throw new Error("Invalid file format");const r=new DataView(n,4,2).getUint16(0,!1),o=new DataView(n,6,4).getUint32(0,!1),c=new Uint8Array(n.slice(10,10+o)),h=new TextDecoder().decode(c),m=JSON.parse(h),p=n.slice(10+o);return{version:r,jsonDescription:m,glbContent:p}}class Vt{constructor(e){this.props=e,this.cache=new Map}load(e,t,i,r){if(this.props.useCache&&this.cache.has(e)){t(this.cache.get(e));return}const l=this;fetch(e).then(o=>{if(!o.ok){r==null||r(new ErrorEvent("NetworkError",{message:"NetworkError for "+e+": "+o.statusText}));return}return o.arrayBuffer()}).then(async o=>{o||r==null||r(new ErrorEvent("Error",{message:"Not a valid sglb file."}));try{const c=l.parse(o);if(!c.glbContent){r==null||r(new ErrorEvent("Error",{message:"No glb content."}));return}const h=pi(c.glbContent,"model/gltf-binary"),m=await ut.loadAsync(h);URL.revokeObjectURL(h),c.glbContent=void 0,c.glb=m.scene,o=void 0,this.cache.set(e,c),t(c)}catch(c){r==null||r(new ErrorEvent("Error",{message:c==null?void 0:c.message}))}}).catch(o=>{r==null||r(new ErrorEvent("Error",{message:o.message}))})}async loadAsync(e){if(this.props.useCache&&this.cache.has(e))return this.cache.get(e);try{const t=await fetch(e);if(!t.ok)throw new Error(`NetworkError for ${e}: ${t.statusText}`);const i=await t.arrayBuffer();if(!i)throw new Error("Not a valid sglb file.");const r=this.parse(i);if(!r.glbContent)throw new Error("No GLB content.");const l=pi(r.glbContent,"model/gltf-binary");console.log(l);const o=await ut.loadAsync(l);return URL.revokeObjectURL(l),r.glbContent=void 0,r.glb=o.scene,this.cache.set(e,r),r}catch(t){throw t}}parse(e){return Lo(e)}clear(){[...this.cache.values()]}}const ko=`*{box-sizing:border-box}.slot-item-container.is-mobile .main{pointer-events:none;border-width:1px;opacity:.8}.slot-item-container.is-mobile .main.focus{width:18px!important;height:18px!important;border-width:2px;opacity:1}.slot-item-container.is-mobile .main.filled{opacity:1;border-width:1px;width:14px!important;height:14px!important;background-image:none;border-radius:50%}.slot-item-container.is-mobile .main.to-be-installed{opacity:1;pointer-events:auto;width:38px!important;height:38px!important;border-color:#000;border-width:1px;background-image:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20fill='none'%20version='1.1'%20width='20'%20height='20'%20viewBox='0%200%2020%2020'%3e%3cg%3e%3cg%3e%3cpath%20d='M20,10.75L0,10.75L0,9.25L20,9.25L20,10.75Z'%20fill-rule='evenodd'%20fill='%23000000'%20fill-opacity='1'/%3e%3c/g%3e%3cg%20transform='matrix(0,1,1,0,10,-10)'%3e%3cpath%20d='M30,0.75L10,0.75L10,-0.75L30,-0.75L30,0.75Z'%20fill-rule='evenodd'%20fill='%23000000'%20fill-opacity='1'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e");background-size:20px auto;background-repeat:no-repeat;background-position:center;background-color:#fff9}.slot-item-container.is-mobile .main.to-be-installed+.info{pointer-events:auto;overflow:visible;width:auto}.slot-item-container.is-mobile .main.to-be-installed.filled{opacity:1;border-width:2px;width:18px!important;height:18px!important;background-image:none;border-radius:50%;border-color:#00ff95}.slot-item-container.is-mobile .main.to-be-installed.to-be-replaced{opacity:1;border-width:1px;pointer-events:auto;width:38px!important;height:38px!important;border-radius:50%;background-image:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20fill='none'%20version='1.1'%20width='40'%20height='40'%20viewBox='0%200%2040%2040'%3e%3cdefs%3e%3cclipPath%20id='master_svg0_504_014299'%3e%3crect%20x='0'%20y='0'%20width='40'%20height='40'%20rx='20'/%3e%3c/clipPath%3e%3c/defs%3e%3cg%20clip-path='url(%23master_svg0_504_014299)'%3e%3cg%3e%3cg%3e%3cpath%20d='M31.695414,17L26.009501,10.74549544L24.899591,11.75450456L28.304586,15.5L8.75,15.5L8.75,17L31.695414,17Z'%20fill-rule='evenodd'%20fill='%23000000'%20fill-opacity='1'/%3e%3c/g%3e%3cg%3e%3cpath%20d='M8.3045862,23L13.9904997,29.2545042L15.10041,28.2454953L11.6954139,24.5L31.25,24.5L31.25,23L8.3045862,23Z'%20fill-rule='evenodd'%20fill='%23000000'%20fill-opacity='1'/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e");background-size:38px auto;border-color:#000}.slot-item-container.is-mobile .info{left:100%;margin-top:0;margin-left:4px}.slot-item-container.is-mobile .info .name-wrapper{margin-top:0;border-radius:0;background:#000;color:#fff}.slot-item-container.is-mobile .info>img{display:none}.slot-item-container .main{pointer-events:auto;cursor:pointer;font-size:12px;color:#fff;width:22px;height:22px;background:#fff0;border:2px solid #fff;border-radius:0;transition:background .2s,width .14s,height .14s,border .14s}.slot-item-container .main.disable{cursor:not-allowed}.slot-item-container .main.drag-over{border-color:red}.slot-item-container .main.can-install{position:relative;width:44px;height:44px;background:#0066ff1a;border-color:#06f}.slot-item-container .main.filled{border-color:#00ff95;border-radius:50%}.slot-item-container .main.selected{border-width:4px}.slot-item-container .main.selected+.info{pointer-events:auto;overflow:visible;width:auto}.slot-item-container .main.focus{border-color:#000}.slot-item-container .main.focus+.info{pointer-events:auto;overflow:visible;width:auto}.slot-item-container .main.has-error{border-color:red}.slot-item-container .main.hidden{display:none}.slot-item-container .main.hidden+.info{display:none}.slot-item-container .main:after{pointer-events:none;content:attr(data-name);transition:all .2s .3s;opacity:0;position:absolute;left:50%;bottom:100%;transform:translate3d(-50%,5px,0);white-space:nowrap;font-size:12px;color:#000;padding:2px 8px;border-radius:2px;background:#fff}.slot-item-container .main:hover{background:#ffffff80}.slot-item-container .main:hover+.info{pointer-events:auto;overflow:visible;width:auto}.slot-item-container .name{position:relative}.slot-item-container .name-wrapper{margin-top:-10px;white-space:nowrap;font-size:12px;color:#fff;padding:2px 8px;background:#000}.slot-item-container .functions-wrapper{z-index:20000;position:absolute;left:0;top:100%}.slot-item-container .functions-wrapper>.functions{display:inline-block;min-width:100px;padding:6px 0;border-left:1px solid #00ff95;border-radius:0 2px 2px 0;background:#0003;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.slot-item-container .functions-wrapper>.functions .btn-add{cursor:pointer;padding:2px 0;margin:0 8px;display:flex;justify-content:center;align-content:center;align-items:center;border:1px dashed #eee;font-size:12px;color:#eee;border-radius:2px;-webkit-backdrop-filter:none;backdrop-filter:none;background:#00050a80}.slot-item-container .functions-wrapper>.functions .btn-add.btn-not-allowed{cursor:not-allowed}.slot-item-container .functions-wrapper>.functions .function{display:flex;justify-content:space-between;white-space:nowrap;margin-bottom:6px;padding:0 8px;font-size:12px;color:#fff}.slot-item-container .functions-wrapper>.functions .function span{margin-right:4px}.slot-item-container .functions-wrapper>.functions .function .btn-remove{pointer-events:none;opacity:0;cursor:pointer;align-self:center;margin-right:0;height:14px;width:14px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAACnSURBVEiJxZaxFcMgDETPTuUtWCWTM4pZAq5RojRpnOfEyEKxSnh3HySeBEhNjZJJTRgUG89GyZWilbKOgJCaKmWtFG2UvFnwQr56jYAcengg3dozELPGIjh96x6hu26/DIa9vD0jq/nUA3nikQEkAOW9nACUGbf7skxlX2mIj1Ob0jK76QdxbYpGFNlk3rPnNndDQltFaLMLbdehAyd8ZP5l6Ed+W17xG7oN9QkytAAAAABJRU5ErkJggg==) center no-repeat;background-size:10px 10px}.slot-item-container .functions-wrapper>.functions .function:hover .btn-remove{pointer-events:auto;opacity:1;transform:scale(1.2)}.slot-item-container .device-name{position:relative;margin:2px 0;display:flex;min-width:120px;align-items:center;align-content:center;justify-content:space-between;white-space:nowrap;height:30px;padding:0 8px;font-size:14px;font-weight:700;color:#000;background:#fff}.slot-item-container .device-name .device-logo{margin-left:-8px;margin-right:4px;width:30px;height:30px;object-fit:contain}.slot-item-container .device-name span{display:block;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:250px}.slot-item-container .device-name .btn-close{margin-left:8px;cursor:pointer;height:20px;width:20px;background:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20fill='none'%20version='1.1'%20width='20'%20height='20'%20viewBox='0%200%2020%2020'%3e%3cdefs%3e%3cclipPath%20id='master_svg0_504_017509'%3e%3crect%20x='0'%20y='0'%20width='20'%20height='20'%20rx='0'/%3e%3c/clipPath%3e%3c/defs%3e%3cg%20clip-path='url(%23master_svg0_504_017509)'%3e%3cg%3e%3cpath%20d='M4.375,16.875L4.375,4.375L15.625,4.375L15.625,16.875L4.375,16.875ZM14.375,5.625L5.625,5.625L5.625,15.625L14.375,15.625L14.375,5.625Z'%20fill-rule='evenodd'%20fill='%23999999'%20fill-opacity='1'/%3e%3c/g%3e%3cg%3e%3cpath%20d='M8.125,12.1875L8.125,8.125L9.375,8.125L9.375,12.1875L8.125,12.1875Z'%20fill-rule='evenodd'%20fill='%23999999'%20fill-opacity='1'/%3e%3c/g%3e%3cg%3e%3cpath%20d='M10.625,12.1875L10.625,8.125L11.875,8.125L11.875,12.1875L10.625,12.1875Z'%20fill-rule='evenodd'%20fill='%23999999'%20fill-opacity='1'/%3e%3c/g%3e%3cg%3e%3cpath%20d='M16.875,5.625L3.125,5.625L3.125,4.375L16.875,4.375L16.875,5.625Z'%20fill-rule='evenodd'%20fill='%23999999'%20fill-opacity='1'/%3e%3c/g%3e%3cg%3e%3cpath%20d='M6.4446528999999995,5.625L13.545177899999999,5.625L11.8665838,2.5L8.15767372,2.5L6.4446528999999995,5.625ZM11.4548223,4.3749999L8.5553472,4.3749999L8.8979512,3.75L11.1191032,3.75L11.4548223,4.3749999Z'%20fill-rule='evenodd'%20fill='%23999999'%20fill-opacity='1'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e") center no-repeat;background-size:100% auto}.slot-item-container .device-name.empty{color:#000c;font-weight:400}.slot-item-container .device-name.empty .btn-close{display:none}.slot-item-container .device-name.empty:before{height:0}.slot-item-container .all-functions{opacity:0;pointer-events:none;min-width:80px;position:absolute;left:-10px;margin-left:100%;bottom:0;padding:6px 0;background:#fff;transition:all .3s}.slot-item-container .all-functions.show{opacity:1;pointer-events:auto;left:16px}.slot-item-container .all-functions label{margin-left:8px;margin-bottom:20px;color:#444e69;font-size:14px}.slot-item-container .all-functions .btn-close{cursor:pointer;position:absolute;right:7px;top:7px;height:16px;width:16px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAB4SURBVDiNpZPLEYAgDAUXe6MuoK4UpwdBwQkQJDcyb9+QnxORCOC9jyxE4Y78DiWxAIcmISKnxaSrtZhMNSOB+ZeacAS7ngl3k1JOBSBpk1INPib0YHjH+Du2S1DhlSZOYbPJ1iLtrLKrG2a9yJopYzTD8Jx+ArgAylOzjm1WpDwAAAAASUVORK5CYII=) center no-repeat;background-size:10px 10px}.slot-item-container .all-functions .functions{display:inline-block;max-height:200px;overflow-x:hidden;overflow-y:auto}.slot-item-container .all-functions .functions::-webkit-scrollbar{width:4px}.slot-item-container .all-functions .functions::-webkit-scrollbar-track{background-color:#fff}.slot-item-container .all-functions .functions::-webkit-scrollbar-thumb{background:#787878;border-radius:25px}.slot-item-container .all-functions .function{display:flex;justify-content:space-between;white-space:nowrap;padding:5px 10px;font-size:12px;color:#787878}.slot-item-container .all-functions .function span{display:flex;align-content:center;align-items:center;margin-right:4px}.slot-item-container .all-functions .function:hover{background:#444e6933}.slot-item-container .all-functions .btn-add{cursor:pointer;width:16px;font-size:16px;text-align:center;font-style:normal}.slot-item-container .info{overflow:hidden;margin-left:-2px;margin-top:-19px;position:absolute;left:100%;top:50%;transform:translateY(-50%);width:0;display:flex;align-items:flex-start;transition:all .3s}.slot-item-container .info>img{flex:0 0 auto;width:53px;height:29px}`,Oo="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGsAAAA7CAYAAAB8MXT7AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAGTSURBVHic7dxLbQNBEIThnigADGEhxAwcBoZgCIZgBoZgCIZgCIaQMIgZVC4daw/xXPLoqdX/3fbW0milUtfutMCdpCkiLhEx1U6CLkkvkt4k7atnQYekfR7US/Us6JB0yIOaqmfBA5JWks6SrhzUwCRN+TYdq2dBx+ygDtWzoEPSNg9qVz0LOmZBgsQ3sqUkvufqAf6SpFVEnCPiFhHr1tqteCR8hyBhYrY6OlTPgo5cHX1I2lbPgo6lBInFk3Rc+uroqXqAn8ogcc3H19bae+U8eIDEZ0LSJoMEZeHIWB2ZIPEZoCw0QVlogsRnYlYWsjoaGUHCRK6OOKiRfa2OMvWtqufBAwQJE5SFJmZl4aZ6FnSQ+Azk6mjxZeFv+/fycfbDWrTW1pSFgyLxmcjVEWXh6CgLTZD4DMzKwguro4ERJEywOjIhaUdZaIAgYYKy0ABloQkSnwlxKZUHcSmVBxKfgVwdnSgLB8d35iZIfCYoC01QFpog8Y3rftFWrotO+cilVKMiSJigLDSS30hQFhr4BEcKZN0LNhDxAAAAAElFTkSuQmCC",ds={name:"",isMobile:!1},zo={"&":"&","<":"<",">":">",'"':""","'":"'"};function Xe(n){return n==null?"":String(n).replace(/[&<>"']/g,e=>zo[e])}function ps(...n){return n.filter(Boolean).join(" ")}class Xs extends HTMLElement{constructor(e){super(),this._size=12,this._showDialog=!1,this._selected=!1,this._focused=!1,this._toBeInstalled=!1,this._toBeReplaced=!1,this._hasError=!1,this._canInstall=!1,this._hide=!1,this._disable=!1,this._filled=!1,this._allFunctions=[],this._functions=[],this._deviceName="",this._deviceLogo="",this._renderQueued=!1,this._needsRender=!0,this.attachShadow({mode:"open"}),this._props={...ds,...e??{}},this.handleShadowClick=this.handleShadowClick.bind(this),this.shadowRoot.addEventListener("click",this.handleShadowClick),this.render()}connectedCallback(){this._needsRender&&(this._needsRender=!1,this.render())}get props(){return this._props}set props(e){this._props={...ds,...e},this.scheduleRender()}get slot(){return this._slot}set slot(e){this._slot=e,this.scheduleRender()}get selected(){return this._selected}set selected(e){const t=!!e;this._selected!==t&&(this._selected=t,this.scheduleRender())}get focused(){return this._focused}set focused(e){const t=!!e;this._focused!==t&&(this._focused=t,this.scheduleRender())}get toBeInstalled(){return this._toBeInstalled}set toBeInstalled(e){const t=!!e;this._toBeInstalled!==t&&(this._toBeInstalled=t,this.scheduleRender())}get toBeReplaced(){return this._toBeReplaced}set toBeReplaced(e){const t=!!e;this._toBeReplaced!==t&&(this._toBeReplaced=t,this.scheduleRender())}get hasError(){return this._hasError}set hasError(e){const t=!!e;this._hasError!==t&&(this._hasError=t,this.scheduleRender())}get canInstall(){return this._canInstall}set canInstall(e){const t=!!e;this._canInstall!==t&&(this._canInstall=t,this.scheduleRender())}get hide(){return this._hide}set hide(e){const t=!!e;this._hide!==t&&(this._hide=t,this.scheduleRender())}get disable(){return this._disable}set disable(e){const t=!!e;this._disable!==t&&(this._disable=t,this.scheduleRender())}get filled(){return this._filled}set filled(e){const t=!!e;this._filled!==t&&(this._filled=t,this.scheduleRender())}get allFunctions(){return[...this._allFunctions]}set allFunctions(e){this._allFunctions=Array.isArray(e)?[...e]:[],this.hasMoreFunctions||(this._showDialog=!1),this.scheduleRender()}get functions(){return[...this._functions]}set functions(e){this._functions=Array.isArray(e)?[...e]:[],this.hasMoreFunctions||(this._showDialog=!1),this.scheduleRender()}get deviceName(){return this._deviceName}set deviceName(e){this._deviceName=e??"",this.scheduleRender()}get deviceLogo(){return this._deviceLogo}set deviceLogo(e){this._deviceLogo=e??"",this.scheduleRender()}get hasMoreFunctions(){return this._allFunctions.some(e=>!this._functions.includes(e))}setSize(e=12){const t=Number.isFinite(e)?Number(e):12;this._size!==t&&(this._size=t,this.scheduleRender())}removeDevice(){var e,t;this._showDialog=!1,this.scheduleRender(),(t=(e=this._props).onRemove)==null||t.call(e)}addFunction(e){this.dispatchEvent(new CustomEvent("function-added",{detail:e}))}scheduleRender(){if(!this.isConnected){this._needsRender=!0;return}this._renderQueued||(this._renderQueued=!0,queueMicrotask(()=>{this._renderQueued=!1,this.render()}))}render(){var p;if(!this.shadowRoot)return;const e=ps("slot-item-container",this._props.isMobile&&"is-mobile"),t=ps("main",this._selected&&"selected",this._focused&&"focus",this._toBeInstalled&&"to-be-installed",this._toBeReplaced&&"to-be-replaced",this._hasError&&"has-error",this._canInstall&&"can-install",this._hide&&"hidden",this._disable&&"disable",this._filled&&"filled"),i=this._functions.map(s=>{const a=Xe(s);return`<div class="function" data-function="${a}"><span>${a}</span><i class="btn btn-remove" data-action="remove-function" data-function="${a}"></i></div>`}).join(""),r=this._allFunctions.filter(s=>!this._functions.includes(s)),l=this._allFunctions.length?`<div class="functions">${i}${`<div class="btn btn-add ${this.hasMoreFunctions?"":"btn-not-allowed"}" data-action="toggle-dialog">+添加</div>`}</div>`:"",o=r.length?`<div class="all-functions ${this._showDialog?"show":""}">
|
|
3700
|
+
<label>添加功能<i class="btn btn-close" data-action="toggle-dialog"></i></label>
|
|
3701
|
+
<div class="functions">
|
|
3702
|
+
${r.map(s=>{const a=Xe(s);return`<div class="function"><span>${a}</span><i class="btn btn-add" data-action="add-function" data-function="${a}">+</i></div>`}).join("")}
|
|
3703
|
+
</div>
|
|
3704
|
+
</div>`:"",c=this._deviceLogo?`<img class="device-logo" src="${Xe(this._deviceLogo)}" alt="device logo">`:"",h=Xe(((p=this._slot)==null?void 0:p.name)??this._props.name??""),m=Xe(this._deviceName||"待安装");this.shadowRoot.innerHTML=`
|
|
3705
|
+
<style>${ko}</style>
|
|
3706
|
+
<div class="${e}">
|
|
3707
|
+
<div class="${t}" style="width:${this._size}px;height:${this._size}px"></div>
|
|
3708
|
+
<div class="info">
|
|
3709
|
+
<img alt="" src="${Oo}">
|
|
3710
|
+
<div class="name">
|
|
3711
|
+
<div class="name-wrapper">${h}</div>
|
|
3712
|
+
<div class="functions-wrapper">
|
|
3713
|
+
<div class="device-name ${this._deviceName?"":"empty"}">
|
|
3714
|
+
${c}
|
|
3715
|
+
<span>${m}</span>
|
|
3716
|
+
<i class="btn btn-close" data-action="remove-device"></i>
|
|
3717
|
+
</div>
|
|
3718
|
+
${l}
|
|
3719
|
+
${o}
|
|
3720
|
+
</div>
|
|
3721
|
+
</div>
|
|
3722
|
+
</div>
|
|
3723
|
+
</div>
|
|
3724
|
+
`,this._needsRender=!1}handleShadowClick(e){const t=e.target;if(!t)return;t.closest(".info")&&(e.preventDefault(),e.stopPropagation());const i=t.closest("[data-action]");if(!i)return;const r=i.getAttribute("data-action");if(r)switch(e.preventDefault(),e.stopPropagation(),r){case"remove-device":this.removeDevice();break;case"remove-function":{const l=i.getAttribute("data-function");l&&this.dispatchEvent(new CustomEvent("function-removed",{detail:l}));break}case"toggle-dialog":if(!this.hasMoreFunctions)return;this._showDialog=!this._showDialog,this.scheduleRender();break;case"add-function":{const l=i.getAttribute("data-function");l&&(this.dispatchEvent(new CustomEvent("function-added",{detail:l})),this._showDialog=!1,this.scheduleRender());break}}}}customElements.get("slot-item")||customElements.define("slot-item",Xs);const H={ON_DROP:"slot-on-drop",ON_DEVICE_DELETED:"slot-on-device-deleted",ON_DEVICE_REPLACED:"slot-on-device-replaced",ON_BEFORE_SELECTED:"slot-on-before-selected",ON_SELECTED:"slot-on-selected",ON_ADD_BUTTON_CLICKED:"slot-add-button-clicked",ON_DEVICE_SELECTED:"slot-on-device-selected",ON_DROP_ERROR:"slot-on-drop-error",ON_ERROR_STATE_CHANGE:"slot-on-error-state-change",ON_FUNCTION_REMOVED:"slot-on-function-removed",ON_FUNCTION_ADDED:"slot-on-function-added"};class gi extends se.CSS2DObject{constructor(e){const t=document.createElement("div");super(t),this.props=e,this._emitter=new je,this._slotContainer=new d.Group,this._bracketSlots=[],this._hasError=!1,this.useBracket=!1,this.addEventListener=this._emitter.addListener.bind(this._emitter),this.removeEventListener=this._emitter.removeListener.bind(this._emitter),this._canInstall=!1,this._loading=!1,this._selected=!1,this._deviceSelected=!1,this._focused=!1,this._toBeInstalled=!1,this._toBeReplaced=!1,this._allFunctions=new Set,this._functions=new Set,this._timer=0,this._parentPos=new d.Vector3,this._wrapper=new d.Group,this._showSlot=!0,this._isMirror=!1,this._preventDefaults=i=>{i.preventDefault(),i.stopPropagation()},this.getWP=this._slotContainer.getWorldPosition.bind(this._slotContainer),this._showSlot=typeof e.show=="boolean"?e.show:!0,this.name=e.name,this._isMirror=e.isMirror,this._slotUI=new Xs({name:e.name,isMobile:e.isMobile,onRemove:()=>{this.clearSlot(),this._emitter.emit(H.ON_DEVICE_DELETED)}}),this._slotUI.slot=this,this._slotUI.hide=!this._showSlot||this.isMirror,t.append(this._slotUI),this._parentPos.copy(this.props.slot.position),this._slotUI.addEventListener("function-removed",({detail:i})=>{this.removeFunction(i)}),this._slotUI.addEventListener("function-added",({detail:i})=>{this.addFunction(i)}),this.add(this._slotContainer),this.props.slot.add(this),setTimeout(()=>{var i;(i=this.props.slot.parent)==null||i.add(this._wrapper),this._wrapper.add(this.props.slot)},10),["dragenter","dragover","dragleave","drop"].forEach(i=>{t.addEventListener(i,this._preventDefaults,!1)}),t.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.toBeInstalled?this._emitter.emit(H.ON_ADD_BUTTON_CLICKED):this.selected=!this.selected}),t.addEventListener("dragover",i=>{if(i.preventDefault(),i.dataTransfer.dropEffect="copy",!this._canInstall){i.dataTransfer&&(i.dataTransfer.dropEffect="none");return}}),t.addEventListener("drop",async i=>{var l;if(i.preventDefault(),i.stopPropagation(),!this._canInstall)return;const r=(l=i.dataTransfer)==null?void 0:l.getData("application/json");if(r){const o=JSON.parse(r);try{await this.install(o),this._emitter.emit(H.ON_DROP,this)}catch(c){this._emitter.emit(H.ON_DROP_ERROR,c)}}else this._emitter.emit(H.ON_DROP_ERROR,new Error("No device info"))})}get hasDevice(){return this._slotContainer.children.length>0}get isMirror(){return this._isMirror}shapeKeyChanged(e,t){var i;if(this.props.follows.has(e)){const r=this.props.follows.get(e);if(r){let l="x";["height","mast"].includes(e)?l="y":["width","liftOuterWidth"].includes(e)&&(l="z");const o=((i=this.props.slot)==null?void 0:i.position[l])>0?1:-1;this._wrapper.position[l]=(t-r.origin)*r.scale*o}}}async loadGlb(e){const i=await new Vt({useCache:!0}).loadAsync(e);if(i.glb)return i.glb.clone(!0)}async installBracket(e){const i=await new Vt({useCache:!0}).loadAsync(e);if(!i.glb)return;const r=i.glb.clone(!0);r.traverse(l=>{l.userData.isBracket=!0}),this.useBracket=!0,this._slotContainer.add(r)}async install(e){if(!this._loading){this._loading=!0;try{const t=await this.loadGlb(e.url);if(!t)throw new Error(`Fail to load device from: ${e.url}`);if(t.traverse(i=>{i.userData.isDevice=!0}),this.isMirror&&t.scale.set(1,1,-1),e.bracketUrl){const i=await this.loadGlb(e.bracketUrl);if(i)this.clearSlot(),this._emitter.emit(H.ON_DEVICE_REPLACED),i.traverse(r=>{r.name.startsWith("Slot")&&this._bracketSlots.push(r),r.userData.isBracket=!0}),this._slotContainer.add(i);else throw new Error(`Fail to load bracket from: ${e.bracketUrl}`);this._bracketSlots.forEach(r=>{r.add(t)})}else this.clearSlot(),this._emitter.emit(H.ON_DEVICE_REPLACED),this._slotContainer.add(t);this.mirrorTarget&&this.mirrorTarget.install(e),this.deviceInfo=e,this._slotUI.deviceLogo=e.logo||"",this._slotUI.deviceName=e.name,this._slotUI.filled=!0,this.holeTarget&&(this.holeTarget.visible=!1)}catch(t){throw t}finally{this._loading=!1}}}get device(){return this._slotContainer.children.length?this._slotContainer.children[0]:null}get allFunctions(){return[...this._allFunctions]}set allFunctions(e){this._functions.forEach(t=>{e.includes(t)||this._functions.delete(t)}),this._allFunctions=new Set(e),this._slotUI.allFunctions=e}get functions(){return[...this._functions]}addFunction(e){this._allFunctions.has(e)&&(this._functions.add(e),this._slotUI.functions=[...this.functions],this._emitter.emit(H.ON_FUNCTION_ADDED,e))}removeFunction(e){this._functions.has(e)&&(this._functions.delete(e),this._slotUI.functions=[...this.functions],this._emitter.emit(H.ON_FUNCTION_REMOVED,e))}clearFunctions(){this._functions.forEach(e=>this.removeFunction(e))}addFunctions(e){e.forEach(t=>this.addFunction(t)),this._slotUI.functions=this.functions}changeName(e){var t;this.name=e,this.props.slot.userData.name=e,this.props.name=e,(t=this.element)==null||t.setAttribute("data-name",this.props.name)}clearSlot(){this._bracketSlots=[],this._slotContainer.children.forEach(e=>{e.removeFromParent(),oe(e)}),this._slotUI.filled=!1,this.deviceInfo=void 0,this._slotUI.deviceName="",this._slotUI.deviceLogo="",this.holeTarget&&(this.holeTarget.visible=!0),this.mirrorTarget&&this.mirrorTarget.clearSlot()}enable(){this._slotUI.disable=!1}disable(){this._slotUI.disable=!0}hide(){this._slotUI.hide=!0}show(){this.isMirror||(this._slotUI.hide=!1)}get selected(){return this._selected}get focused(){return this._focused}set focused(e){this._focused=e,this._slotUI.focused=e}get toBeInstalled(){return this._toBeInstalled}set toBeInstalled(e){this._toBeInstalled=e,this._slotUI.toBeInstalled=e}get toBeReplaced(){return this._toBeReplaced}set toBeReplaced(e){this._toBeReplaced=e,this._slotUI.toBeReplaced=e}set selected(e){e&&this._emitter.emit(H.ON_BEFORE_SELECTED,e),this._selected=e,this._slotUI.selected=e,this._emitter.emit(H.ON_SELECTED,e),this.element.style.zIndex="100",this.selected?this.renderOrder=1/0:this.renderOrder=1}get deviceSelected(){return this._deviceSelected}set deviceSelected(e){this._deviceSelected=e,this._emitter.emit(H.ON_DEVICE_SELECTED,e)}get error(){return this._hasError}set error(e){this._loading&&setTimeout(()=>{this.error=e},100),this._hasError=e,this._slotUI.hasError=e,this._emitter.emit(H.ON_ERROR_STATE_CHANGE,e)}getCanInstall(){return this._canInstall}canInstall(e){this._canInstall=e,this._slotUI.canInstall=e}dispose(){cancelAnimationFrame(this._timer),["dragenter","dragover","dragleave","drop"].forEach(e=>{this.element.addEventListener(e,this._preventDefaults,!1)}),this.clearSlot(),this._emitter.removeAllListeners(),oe(this._slotContainer),this.element.remove()}render(e){const t=this.element.style.transform,i=/translate\(-?\d*\.?\d*%?,?\s-?\d*\.?\d*%?\)\s*translate\((-?\d*\.?\d*)px,\s*(-?\d*\.?\d*)px\)/.exec(t);if(!i)return;const r=new d.Vector2(parseFloat(i[1]),parseFloat(i[2])),l=e.mousePos.distanceTo(r);let o=this.props.isMobile?12:18,c=38,h=30;if(this._canInstall&&(o=34,c=60,h=60),l<h){let m=(h-l)*1+o;l<20&&(m=c),m>c&&(m=c),this._slotUI.setSize(m)}else this._slotUI.setSize(o)}clone(e){return new d.Group}}/**
|
|
3725
|
+
* @license
|
|
3726
|
+
* Copyright 2017 Google LLC
|
|
3727
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
3728
|
+
*/const Vo=n=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(n,e)}):customElements.define(n,e)};/**
|
|
3729
|
+
* @license
|
|
3730
|
+
* Copyright 2019 Google LLC
|
|
3731
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
3732
|
+
*/const Dt=globalThis,Bi=Dt.ShadowRoot&&(Dt.ShadyCSS===void 0||Dt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Js=Symbol(),ms=new WeakMap;let Uo=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==Js)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Bi&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=ms.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&ms.set(t,e))}return e}toString(){return this.cssText}};const Ho=n=>new Uo(typeof n=="string"?n:n+"",void 0,Js),No=(n,e)=>{if(Bi)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),r=Dt.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,n.appendChild(i)}},gs=Bi?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return Ho(t)})(n):n;/**
|
|
3733
|
+
* @license
|
|
3734
|
+
* Copyright 2017 Google LLC
|
|
3735
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
3736
|
+
*/const{is:Wo,defineProperty:Go,getOwnPropertyDescriptor:jo,getOwnPropertyNames:qo,getOwnPropertySymbols:Yo,getPrototypeOf:Qo}=Object,de=globalThis,vs=de.trustedTypes,Zo=vs?vs.emptyScript:"",$t=de.reactiveElementPolyfillSupport,lt=(n,e)=>n,Ut={toAttribute(n,e){switch(e){case Boolean:n=n?Zo:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},Li=(n,e)=>!Wo(n,e),_s={attribute:!0,type:String,converter:Ut,reflect:!1,hasChanged:Li};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),de.litPropertyMetadata??(de.litPropertyMetadata=new WeakMap);class Je extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=_s){if(t.state&&(t.attribute=!1),this._$Ei(),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(e,i,t);r!==void 0&&Go(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){const{get:r,set:l}=jo(this.prototype,e)??{get(){return this[t]},set(o){this[t]=o}};return{get(){return r==null?void 0:r.call(this)},set(o){const c=r==null?void 0:r.call(this);l.call(this,o),this.requestUpdate(e,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??_s}static _$Ei(){if(this.hasOwnProperty(lt("elementProperties")))return;const e=Qo(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(lt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(lt("properties"))){const t=this.properties,i=[...qo(t),...Yo(t)];for(const r of i)this.createProperty(r,t[r])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[i,r]of t)this.elementProperties.set(i,r)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const r=this._$Eu(t,i);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const r of i)t.unshift(gs(r))}else e!==void 0&&t.push(gs(e));return t}static _$Eu(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$Eg=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$ES(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$E_??(this._$E_=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$E_)==null||t.delete(e)}_$ES(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return No(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$E_)==null||e.forEach(t=>{var i;return(i=t.hostConnected)==null?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$E_)==null||e.forEach(t=>{var i;return(i=t.hostDisconnected)==null?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$EO(e,t){var l;const i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(r!==void 0&&i.reflect===!0){const o=(((l=i.converter)==null?void 0:l.toAttribute)!==void 0?i.converter:Ut).toAttribute(t,i.type);this._$Em=e,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(e,t){var l;const i=this.constructor,r=i._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const o=i.getPropertyOptions(r),c=typeof o.converter=="function"?{fromAttribute:o.converter}:((l=o.converter)==null?void 0:l.fromAttribute)!==void 0?o.converter:Ut;this._$Em=r,this[r]=c.fromAttribute(t,o.type),this._$Em=null}}requestUpdate(e,t,i){if(e!==void 0){if(i??(i=this.constructor.getPropertyOptions(e)),!(i.hasChanged??Li)(this[e],t))return;this.C(e,t,i)}this.isUpdatePending===!1&&(this._$Eg=this._$EP())}C(e,t,i){this._$AL.has(e)||this._$AL.set(e,t),i.reflect===!0&&this._$Em!==e&&(this._$ET??(this._$ET=new Set)).add(e)}async _$EP(){this.isUpdatePending=!0;try{await this._$Eg}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[l,o]of this._$Ep)this[l]=o;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[l,o]of r)o.wrapped!==!0||this._$AL.has(l)||this[l]===void 0||this.C(l,this[l],o)}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(i=this._$E_)==null||i.forEach(r=>{var l;return(l=r.hostUpdate)==null?void 0:l.call(r)}),this.update(t)):this._$Ej()}catch(r){throw e=!1,this._$Ej(),r}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$E_)==null||t.forEach(i=>{var r;return(r=i.hostUpdated)==null?void 0:r.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$Ej(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$Eg}shouldUpdate(e){return!0}update(e){this._$ET&&(this._$ET=this._$ET.forEach(t=>this._$EO(t,this[t]))),this._$Ej()}updated(e){}firstUpdated(e){}}Je.elementStyles=[],Je.shadowRootOptions={mode:"open"},Je[lt("elementProperties")]=new Map,Je[lt("finalized")]=new Map,$t==null||$t({ReactiveElement:Je}),(de.reactiveElementVersions??(de.reactiveElementVersions=[])).push("2.0.3");/**
|
|
3737
|
+
* @license
|
|
3738
|
+
* Copyright 2017 Google LLC
|
|
3739
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
3740
|
+
*/const Xo={attribute:!0,type:String,converter:Ut,reflect:!1,hasChanged:Li},Jo=(n=Xo,e,t)=>{const{kind:i,metadata:r}=t;let l=globalThis.litPropertyMetadata.get(r);if(l===void 0&&globalThis.litPropertyMetadata.set(r,l=new Map),l.set(t.name,n),i==="accessor"){const{name:o}=t;return{set(c){const h=e.get.call(this);e.set.call(this,c),this.requestUpdate(o,h,n)},init(c){return c!==void 0&&this.C(o,void 0,n),c}}}if(i==="setter"){const{name:o}=t;return function(c){const h=this[o];e.call(this,c),this.requestUpdate(o,h,n)}}throw Error("Unsupported decorator location: "+i)};function Ko(n){return(e,t)=>typeof t=="object"?Jo(n,e,t):((i,r,l)=>{const o=r.hasOwnProperty(l);return r.constructor.createProperty(l,o?{...i,wrapped:!0}:i),o?Object.getOwnPropertyDescriptor(r,l):void 0})(n,e,t)}/**
|
|
3741
|
+
* @license
|
|
3742
|
+
* Copyright 2017 Google LLC
|
|
3743
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
3744
|
+
*/function $o(n){return Ko({...n,state:!0,attribute:!1})}/**
|
|
3745
|
+
* @license
|
|
3746
|
+
* Copyright 2017 Google LLC
|
|
3747
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
3748
|
+
*/const ys=(n,e,t)=>(t.configurable=!0,t.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(n,e,t),t);/**
|
|
3749
|
+
* @license
|
|
3750
|
+
* Copyright 2017 Google LLC
|
|
3751
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
3752
|
+
*/function ea(n,e){return(t,i,r)=>{const l=o=>{var c;return((c=o.renderRoot)==null?void 0:c.querySelector(n))??null};if(e){const{get:o,set:c}=typeof i=="object"?t:r??(()=>{const h=Symbol();return{get(){return this[h]},set(m){this[h]=m}}})();return ys(t,i,{get(){let h=o.call(this);return h===void 0&&(h=l(this),(h!==null||this.hasUpdated)&&c.call(this,h)),h}})}return ys(t,i,{get(){return l(this)}})}}var ta=Object.defineProperty,ia=Object.getOwnPropertyDescriptor,ki=(n,e,t,i)=>{for(var r=i>1?void 0:i?ia(e,t):e,l=n.length-1,o;l>=0;l--)(o=n[l])&&(r=(i?o(e,t,r):o(r))||r);return i&&r&&ta(e,t,r),r};class sa{constructor(e,t,i,r){this.name=e,this.slot=t,this.start=i,this.end=r,this.split="--",this.uuid="",this.valid=!1,this.editable=!1,this.highlight=!1,this.uuid=e+this.split+t}update(e,t){this.start=e.clone(),this.end=t.clone()}}exports.DeviceLines=class extends Ft.LitElement{constructor(e,t=0){super(),this.offset=e,this.heightOffset=t,this.lines=new Map,this.setOffset(this.offset.x,this.offset.y)}setOffset(e,t){this.offset.set(e,t),this.style.setProperty("--left",this.offset.x+"px"),this.style.setProperty("--top",this.offset.y+"px")}setHeightOffset(e){this.heightOffset=e,this.style.setProperty("--heightOffset",this.heightOffset+"px")}hide(){var e;(e=this.container)==null||e.classList.add("hidden")}show(){var e;(e=this.container)==null||e.classList.remove("hidden")}addLine(e){this.lines.has(e.uuid)||this.lines.set(e.uuid,e)}clear(){this.lines.clear()}removeLine(e){this.lines.delete(e.uuid)}getLineByName(e){const t=[];return this.lines.forEach((i,r)=>{i.name===e&&t.push(i)}),t}getLineBySlot(e){const t=[];return this.lines.forEach((i,r)=>{i.slot===e&&t.push(i)}),t}getPath(e){const t=e.end.clone();t.set(t.x-this.offset.x,t.y-this.offset.y);const i=e.start.clone().add(t).multiplyScalar(.5),r=e.start.clone().add(t).multiplyScalar(.7);return`M${e.start.x} ${e.start.y}
|
|
3753
|
+
C${i.x} ${e.start.y}
|
|
3754
|
+
${r.x} ${e.end.y}
|
|
3755
|
+
${t.x} ${t.y}
|
|
3756
|
+
`}updateLine(e){this.lines.set(e.uuid,e)}forceUpdate(){this.requestUpdate()}render(){return Ft.svg`
|
|
3757
|
+
<svg class="container">
|
|
3758
|
+
<g>
|
|
3759
|
+
${[...this.lines.values()].map(e=>Ft.svg`<path
|
|
3760
|
+
class="${e.valid?"valid":""} ${e.editable?"editable":""} ${e.highlight?"highlight":""}"
|
|
3761
|
+
d="${this.getPath(e)}"></path>`)}
|
|
3762
|
+
</g>
|
|
3763
|
+
</svg>`}};exports.DeviceLines.styles=Ft.css`
|
|
3764
|
+
:host {
|
|
3765
|
+
--left: 0px;
|
|
3766
|
+
--top: 0px;
|
|
3767
|
+
position: absolute;
|
|
3768
|
+
left: var(--left);
|
|
3769
|
+
top: var(--top);
|
|
3770
|
+
pointer-events: none;
|
|
3771
|
+
width: calc(100% - var(--left));
|
|
3772
|
+
height: calc(100% - var(--top));
|
|
3773
|
+
}
|
|
3774
|
+
|
|
3775
|
+
svg {
|
|
3776
|
+
width: 100%;
|
|
3777
|
+
height: calc(100% + var(--heightOffset));
|
|
3778
|
+
&.hidden {
|
|
3779
|
+
display: none;
|
|
3780
|
+
}
|
|
3781
|
+
}
|
|
3782
|
+
|
|
3783
|
+
path {
|
|
3784
|
+
stroke: #787878;
|
|
3785
|
+
fill: transparent;
|
|
3786
|
+
stroke-width: 0.5px;
|
|
3787
|
+
stroke-dasharray: 4 4;
|
|
3788
|
+
|
|
3789
|
+
&.valid {
|
|
3790
|
+
stroke-width: 1px;
|
|
3791
|
+
stroke: #00FF95;
|
|
3792
|
+
stroke-dasharray: none;
|
|
3793
|
+
&:hover {
|
|
3794
|
+
cursor: pointer;
|
|
3795
|
+
}
|
|
3796
|
+
}
|
|
3797
|
+
|
|
3798
|
+
&.highlight {
|
|
3799
|
+
stroke: #0066FF;
|
|
3800
|
+
cursor: pointer;
|
|
3801
|
+
stroke-width: 2px;
|
|
3802
|
+
}
|
|
3803
|
+
|
|
3804
|
+
&.editable {
|
|
3805
|
+
pointer-events: auto;
|
|
3806
|
+
&:hover {
|
|
3807
|
+
cursor: pointer;
|
|
3808
|
+
stroke: #0066FF;
|
|
3809
|
+
stroke-width: 2px;
|
|
3810
|
+
stroke-dasharray: none;
|
|
3811
|
+
}
|
|
3812
|
+
}
|
|
3813
|
+
}
|
|
3814
|
+
`;ki([$o()],exports.DeviceLines.prototype,"lines",2);ki([ea(".container")],exports.DeviceLines.prototype,"container",2);exports.DeviceLines=ki([Vo("device-lines")],exports.DeviceLines);class ra extends se.CSS2DObject{constructor(e){const t=document.createElement("div");super(t),this._text=document.createElement("div");const i=Di(),r=i?"#ddd":"#eee";this.element.style.pointerEvents="auto",this.element.style.padding=i?"2px 6px":"3px 12px",this.element.style.borderTop=`1px solid ${r}`,this.element.style.borderBottom=this.element.style.borderTop;const l="6px",o=document.createElement("div");o.style.pointerEvents="none",Object.assign(o.style,{pointerEvents:"none",borderLeft:`1px solid ${r}`,borderRight:`1px solid ${r}`,position:"absolute",left:"0",top:"0",boxSizing:"border-box",height:l,width:"100%"}),this.element.append(o);const c=document.createElement("div");c.style.pointerEvents="none",Object.assign(c.style,{pointerEvents:"none",borderLeft:`1px solid ${r}`,borderRight:`1px solid ${r}`,position:"absolute",left:"0",bottom:"0",boxSizing:"border-box",height:l,width:"100%"}),this.element.append(c),this._text.style.fontSize=i?"10px":"14px",this._text.style.font="SF Pro SC,SF Pro Text,SF Pro Icons,PingFang SC,Helvetica Neue,Helvetica,Arial,sans-serif",this._text.style.color="#fff",this._text.style.fontWeight="500",this._text.style.transition="all .16s",this._text.innerText=e,this.element.append(this._text),this._text.addEventListener("pointermove",()=>{var h;o.style.borderColor=c.style.borderColor=this.element.style.borderColor="#666",this._text.style.color="#000",(h=this.onPointMove)==null||h.call(this)}),this._text.addEventListener("pointerleave",()=>{var h;o.style.borderColor=c.style.borderColor=this.element.style.borderColor=r,this._text.style.transform="scale(1)",this._text.style.color="#fff",(h=this.onPointLeave)==null||h.call(this)})}set text(e){this._text.innerText=e}dispose(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}class Bt extends d.Group{constructor(e,t=!0,i=!0){super(),this._startWith=e,this._showText=t,this.useStartEnd=i,this._line2Length=.01,this._line=new d.LineSegments(new d.BufferGeometry,new d.LineBasicMaterial({color:"#666",linewidth:2})),this._line2=new d.LineSegments(new d.BufferGeometry,new d.LineBasicMaterial({color:"#666",linewidth:2})),this._text=new ra(""),this._line.frustumCulled=!1,this.add(this._line,this._line2),this._showText&&(this.add(this._text),this._text.onPointMove=()=>{this._line.material.color.set("#000"),this._line2.material.color.set("#000")},this._text.onPointLeave=()=>{this._line.material.color.set("#666"),this._line2.material.color.set("#666")})}updateMaterial(e){this._line.material=e}reset(){var e;(e=this._line.geometry)==null||e.dispose(),this._line.computeLineDistances()}update(e,t,i=0){var u,g;(u=this._line.geometry)==null||u.dispose(),this._line.geometry.setFromPoints([e,t]),this._line.computeLineDistances();const r=this._line2Length+i*.02,l=new d.Vector3().subVectors(t,e).normalize();let o;Math.abs(l.z)>Math.abs(l.x)&&Math.abs(l.z)>Math.abs(l.y)?o=new d.Vector3(-l.y,l.x,0):Math.abs(l.y)>Math.abs(l.x)?o=new d.Vector3(1,0,0):o=new d.Vector3(0,1,0),o.length()<.001&&(Math.abs(l.x)<.9?o=new d.Vector3(1,0,0):o=new d.Vector3(0,1,0)),o.normalize();const c=new d.Vector3().addVectors(e,o.clone().multiplyScalar(r)),h=new d.Vector3().addVectors(e,o.clone().multiplyScalar(-r)),m=new d.Vector3().addVectors(t,o.clone().multiplyScalar(r)),p=new d.Vector3().addVectors(t,o.clone().multiplyScalar(-r));(g=this._line2.geometry)==null||g.dispose(),this._line2.geometry=new d.BufferGeometry,this._line2.geometry.setFromPoints([c,h,m,p]),this._line2.computeLineDistances();const s=e.distanceTo(t);this._startWith?this._text.text=`${this._startWith}${(s*1e3).toFixed(0)} mm`:this._text.text=`${(s*1e3).toFixed(0)} mm`;const a=new d.Vector3;a.addVectors(e,t).multiplyScalar(.5),this._text.position.copy(a),this.useStartEnd||(this._line2.visible=!1)}destroy(){this._text.dispose(),this.children.forEach(e=>oe(e)),this.removeFromParent()}}class Ks extends d.Object3D{constructor(e,t){super(),this.radius=e,this._text=new na(""),this._line=new Bt(void 0,!1,!1),this._box=new d.Mesh,this._arc=new Cr.Line2,this._previousPosition=null,this._updateTimer=null,this._updateDelay=300,this._accumulatedAngle=0,this._lastAngle=null,this._line.updateMaterial(new d.LineDashedMaterial({color:"#555",dashSize:.06,gapSize:.06})),this._line.renderOrder=0,this._box.geometry=new d.RingGeometry(e,e+.003,128),this._box.material=new d.MeshBasicMaterial({color:"#666",side:d.DoubleSide}),this._arc.geometry=new Wi.LineGeometry,this._arc.geometry.setPositions([0,0,0,0,0,0]),this._arc.geometry.instanceCount=0,this._arc.material=new Os.LineMaterial({color:"#eee",linewidth:2,resolution:new d.Vector2(window.innerWidth,window.innerHeight)}),this._arc.visible=!1,this._arc.rotateX(-Math.PI/2),this.position.y=t,this._arc.position.y=.001,this.add(this._box),this.add(this._arc),this.add(this._line),this.add(this._text)}hide(){this._text.hide(),this._line.visible=!1,this._arc.visible=!1}show(){this._text.show(),this._line.visible=!0}dispose(){this._updateTimer&&(clearTimeout(this._updateTimer),this._updateTimer=null),this._box.geometry&&this._box.geometry.dispose(),this._arc.geometry&&this._arc.geometry.dispose(),this._arc.visible=!1,this._previousPosition=null}update(e){var t;this.radius=e,(t=this._box.geometry)==null||t.dispose(),this._box.geometry=new d.RingGeometry(e,e+.003,128),this._line.updateMaterial(new d.LineDashedMaterial({color:"#555",dashSize:.06*e,gapSize:.06*e})),this._text.update((e*1e3).toFixed(0))}change(e){const t=e.clone();t.setZ(0),t.normalize().multiplyScalar(this.radius),this._text.position.set(t.x,t.y,t.z),this._text.updateColor("#eee"),this._line.update(t,new d.Vector3),this._previousPosition&&this._updateArc(this._previousPosition,t),this._updateTimer&&clearTimeout(this._updateTimer),this._updateTimer=setTimeout(()=>{this._previousPosition=null,this._accumulatedAngle=0,this._lastAngle=null,this._clearArc(),this._updateTimer=null},this._updateDelay),this._previousPosition||(this._previousPosition=t.clone(),this._lastAngle=Math.atan2(t.y,t.x),this._accumulatedAngle=0)}_updateArc(e,t){const i=Math.atan2(t.y,t.x);if(this._lastAngle!==null){let h=i-this._lastAngle;h>Math.PI?h-=2*Math.PI:h<-Math.PI&&(h+=2*Math.PI),this._accumulatedAngle+=h}if(this._lastAngle=i,Math.abs(this._accumulatedAngle)<.01){this._arc.visible=!1;return}const r=Math.atan2(e.y,e.x),l=r+this._accumulatedAngle;let o=.006*this.radius;o<.003&&(o=.003),o>.006&&(o=.006);const c=this._createArcGeometry(r,l,this.radius+o);this._arc.geometry&&this._arc.geometry.dispose(),this._arc.geometry=c,this._arc.visible=!0}_clearArc(){this._text.updateColor(),this._arc.geometry&&(this._arc.geometry.setPositions([0,0,0,0,0,0]),this._arc.geometry.instanceCount=0,this._arc.computeLineDistances()),this._arc.visible=!1}_createArcGeometry(e,t,i){const r=[],l=t-e,o=Math.max(128,Math.floor(Math.abs(l)/(Math.PI/128))),c=l/o;for(let m=0;m<=o;m++){const p=e+m*c,s=Math.cos(p),a=Math.sin(p);r.push(i*s,0,i*a)}const h=new Wi.LineGeometry;return h.setPositions(r),h.instanceCount=Math.max(0,r.length/3-1),h}}class na extends se.CSS2DObject{constructor(e){const t=document.createElement("div");super(t),this._wrapper=document.createElement("div"),this._circle=document.createElement("div");const i=Di();this._wrapper.style.fontSize=i?"10px":"11px",this._wrapper.style.color="#fff",this._wrapper.style.whiteSpace="nowrap",this._wrapper.style.position="absolute",this._wrapper.style.transform="translateX(-50%)",this._wrapper.style.top="6px",this._wrapper.style.font="SF Pro SC,SF Pro Text,SF Pro Icons,PingFang SC,Helvetica Neue,Helvetica,Arial,sans-serif";const r=this._circle;r.style.position="relative",r.style.zIndex="10",r.style.width=r.style.height="5px",r.style.borderRadius="50%",r.style.background="#666",t.append(this._wrapper,r),this.update(e)}show(){this.element.style.display="block"}hide(){this.element.style.display="none"}update(e){this._wrapper.innerText="旋转半径:"+e+" mm",this.updateColor("#eee")}updateColor(e="#666"){this._circle.style.background=e}}const oa="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADgAAAAUCAYAAADY6P5TAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAEvSURBVFiFzZdbFYMwEEQroRKQgAQkVEIlICEOkFAJlRAJSIgEJNx+sPS0nGxIaOhyv3nM7mTmwOViDHAFesADD+BqrakKQAcMwMQ3AWis9e1C3HLASJoAdNZ6sxG3/MZQMZy1dhWgFbfWRzDGlFjAwFlyyXdh5OD5OIqykBgBy1yiF0aMUQaJugLclOcEoP3nULmFgQgeyCwOoJGBYrijByspDM98ZIszJAt8Ks8dag/VUFYYLtetjHdruRz5JZf8WBg1Ae7KcgOluaSsMAKJwqgJ6Vz2WzcvhZHjVlFh1ESG1DQ67SYtyGs8OwujNpTkUtw4nVtbyLK1XDafF3aKW90Z3EpBbi5lE0u9n3qoNTKk9rHh3heZqqwA8Vw6a11VkVwuPK31HALzb5pfovYC2xSs5LCDIUcAAAAASUVORK5CYII=",aa="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAKCAYAAACngj4SAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAChSURBVDiNrdJbFYMwEIRhJFQCEpCAhEqIhDhBAlKQgAQkIOHrSziHpmkbLvua7P4zO9s0FYUeM0b0NT2nC9FnLQho7wQ9MOwgQ3K4ZPDrrtGmFcKKkL0HTAXXw2HX6HYuFnR/hMWC6ykX+W1AzJqq1abDGguux6LoPK9aUGFOm1Y+F+Bh+7DlsSKehRXgnfdDm5od7GdeN8ADnpuKQ3ldqReHZFd3742nZgAAAABJRU5ErkJggg==",xs="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGwAAABsCAYAAACPZlfNAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAdzSURBVHic7Z3hlZs6EIUvW4E7CB3EHcQdxB08OngugVTg8yrwSQVOKnBSwW4qsFOB3cF9PxhZQsYYjEAS1neOD7ssCwPXMxoNIGWIDJJLAAsASwCfAOTyey6bLOQDABf5qJ9P8vkry48sy05j2+ySzLcBjyC5QiXOV1kuWv+hPxcAvwD8BvCBSsRL6394JDjBSC4ArFEJtG7Y5ILqwp4A/JHlxfyoC04yN/4vh/bEz9Dim9uY+/8O4EfI4nmFZEFyz1veSe5Iri0BXB13Icfekjxaxz6TPMixXXt2fJDM5WLZF+og63MPNi1IbsQGW7zyJYUToXZyEUxP8iLSPUS80hLvdYQTobbWN3fHKvMLGpKrBq/bzla4htC3C8mbutIg3JnkxrddzhCvil4omwbhDqy6IPEisV5xJFn4tsk1rDJI8wtZ+rapN+JV73PzqnuwSk7MtvkQzflabdUxGsMdIGFSnfuZZFPHPxysELjnXDOoFsTbzAJA6dumRiyxSt/2+Ma6Hlvf9lyRb9QumjAwIZKQqOLAznvEEbFUcvFS7VVXWO/WvHsTLYnVnSBEM8JgEqsDlmi7qQ++TWL1xxKtnOqgKvs5J7H6I6KdJxFNsh5FygafxLqOxVgHme6b8QIYkWqcZoW6Mr13vvMXhboi8u56x+a34eXKTWMhXSO3SQirgqZi5WSniSvS1ChyFztUoTCcetjMoNGnHbqjTQqF42P1z4pnd7IwssKUwo8Mq/uIz2eN1NWMg3vzxoUWvu3pihEa+zU/4l3RJhoRC/ZcAkKdxkfnXUC8ggE1L+tWILbartW45o1D5IIpL+tWq43du4C4BQNqXlY82jB67wJmIdhSTG/vl1FXkaP1LiB+wQCA+m5+Ya5/s7b7V5a/J7Eq0cZ/svza+FcrHEZd1ZiJh5kp/q0e1D3tqMMhMA/BgFodt1DrzJD4jyx/TmpVoo3vsqyHxTmFQ2BWHpY3ngP1Pa9h5f1AmItgQC1bXAE6JKpXVn94sSrRxocsl4AW7Iss/0xuTuIRKqfQ7dic2i9gdiHxWlu0V8yi/QLmJRhQc6jlG3T7lYboCRfVji3eoMda+mjeNhEAJ1ku31ANYQekhCNklDafTA87eTEl0YWTLHNTsNSGhYvSZvEGPWDkyY8t1xt2ua/jd0Uyah/jYinBcvt+2OTIBTgAOHi6GJ3wbKeOfkaOn09sRNM4VGcXF8N1P0wiwNmyMx+63x7HV48dnuHqpJ40ZMNbBovmUrAGsRSTjuB2PRefgokhZcPFGCSaK8FaxCqf3ecAW66Cea8juhbNhWCBiaXridRtSD61IZZRzkQbKlhIYok9ut5rCOY9Q3Ml2hDBQhNLbKoJdpBfVr4MMnEh2rOChSiW2KWeCHg3X4wO5h2woaI9I1ioYolt6gHf/RuMOpU/k+pkWVYC+GatXmCkTit1p9hOvL6JLb7JZXky+0LTjn/UgWc9rY+HhexZCuqXIzZmfAzyAdJnROsqWAxiAbUnp9bmmxJn34bdo69oXQSLRSwAt10veqwndqVFtKJh21bBWD2WHotYuo5orDzIymAyxSbuiEZbtDbBqN8hCF4soGbv3lwZbOJh00W0e4LFJhZQG81hY67UHbMIeCRak2AxigXU2q+V/QdF7sWynrSJ1nFdDGJd2y/axXnqikfhx7z+tIjWhdK3/Y+gbqpuu1yM9IU+Nt8EfUQU00ex4YU+84/m6Df55NYNgPdDXhOFb3u7wLZwaGwUXVhUdBSt8G1nV9hlvBTjpKPIFm0eiFb4tq8P7No3ZkA3NJ/hjmiFb7v6QN3Nuh8OjY3VCQffib6HJVrh256+GN5Vdtk4ZwS1xUeIaIVvO/rSy7uMf9rF7mWx0su7jH9SD31E7WWxwfoI5v0eO6QuOiYvmwgOGcGcLkZ6TnSG+kGb7m1Xw05UtnVMoXE8WJ8hYljZjL4mKXsh6HIE85SAjAvHmCqFabKcUeAYk+UYO1ePWqXpqBxBXWx3f0vLyhpL5wd4MYyoNd7bnKzX6IJ+wipkOOXUlJN8M2YMfUxNaSUh+SQHnQFWszLtfGxME2/3whJr+j4t09T2nbHE8jO1vRiSRHtAMGIZBi2M8HhO2aNGskGVYOy8i2VCXQ+bLvsJGNYfci1929OIZeQ+qG/UREjE2QcvlsIKA0cGMjrBFFjt1ZGx3EcUww/Gt2w7Z2+T890Z5/seZQJmhcjjHBMSVuW6o3GepW+bBsHqfo/pbYc5hMkGrzpG6VX3YPWWyTl24e4IVfi2axRYZVBm+h+NcKxGHdhZtm9n5VX3EOHKBo8rGVByIt5UUFdzKDbvXkIomzvCKfE2PsQzRDpYNh1lfT61TcEhwq3lItniHSX0FGMIKAKtxWveecueAbVRmW8DbESUNaopHpe4HbDrhGqU6Q9UMyao309qgyzLTsa+7E8O4LMsm/YPVPOo/QTwI8uyoMbzD04wE7ngS/l8AbBC8wUeghL/J4CPLMt+Od6/U4IWrAlpQ5aoPOSTLHNoIRfGzxfoMd9P0J74F5VIlyzLopok6H/tVqA8kSYfTwAAAABJRU5ErkJggg==",la="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYwAAACsCAYAAABo4pvIAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAzYSURBVHic7d3hcdtIEobhD05gmYGRgbkRLDKwMjiGoBCUgeoi0F0Evo1AdASiIxAcgbkR9P1Aj9mESIm2QMwAeJ8qlihKomeXwHzsHgCsBBTOzGpJK7+pd7/2r3+ceCw69Vh8nkvt/fbW4/H7vaR//H4bfqeNX6uqij8DilPlHgCWxcxW6ibvNFmn+x/DY/Fn0mHyPXVLE7F0ejKOf3/SpRO1B9c55wJNOg6rfrD1/5v7/31pbN97j7WS9lVVnf3vAoZGYGAwPqHW6ia+tbrJce0/Tj+Lk176+k/4/ui2tAnRA/VUaNbqQjXdr8PvtDoOku/xeyoXDIXAwMXMbK1DGHzUcTikiatVN1l9Uy8YmLiG1wuY2r9+0vHrUuvwOux0/PrseF1wKQIDR06EQvw+TTatunexrXgXOwmh+ku31AJc6xAoMUxaESboITAWyoOhVjdhfAr307vQnbpQ2KlrDe2yDBSj8EBJ20S/Qml12B7S/XZp7UIQGLMX3lk2Og6Gnbqd/1u4zySAI+EghRQmH9VtS7W6bWYrKpLFIDBmJFQNf6nbwdOCc6oYvqqrFrY5xof56AXJJ53e3r5J2hIi80FgTFRoIcRwaP32Vb7TUjFgTCdaW426thYhMgMExgT4u7m1Dm2lxn+UqoatCAcUyrffRodqpPEfbcWbm0khMAoUdrBUPTTyUFC3g7UsQmPKvBJpdNzOiq3TLQFSHgKjAKGM/6xDOb+T9Le6d17bXGMDxmJmjY73g1aHRfX/ESD5ERgZhBbTZx2OOCEggOCVAEn7CQEyMgJjJL2Nv9Hxhr/NNS5gKnr7UK0uQNiHMH1mtjKzGzN7MLNnvz34Rg/gHXz/aszs3vetH75/bbyCB8pmZrVvsI/WeTSzWz8/AsCV+L536/vcj7Dv1bnHBvxkZmt/l/MUqogb3uUAefSqjx++X95R3SOLEBK0moDCER4Y3YmQuKfVBEyLh8dd2I8JDwzD+6J3hAQwP2fCo849LkyI9z/TwnVqNxESwIyF8IgL5qxD4jTfYB786KYvZnaTe0wAxudzQTraivVJdE60nDaUpACkn92GuxAed1QdCxSqCY5wAvCm3pFWj8wZM2eHk+p+VhO5xwRgWrzqSCcIPrHWMTMeFGltgmoCwCB6ax33tLMnzM+biG2nOveYAMxPWAulXTU1vUNiuRAZgFGERfJngqNwrE8AKEVoVz0xHxWEoABQqhAczE85ERQApiIEB62qMREUAKaK4BiJH4nwRFAAmDqC40rCeRQEBYBZ8Y5JumZVnXs8k9U7RO0u93gA4Br6cx2nAvyisE5B6gJYBA+OB684uFr2W3rtpzr3eABgbL31jTr3eIoUTq2/yz0WAMjNugsbPpvZbe6xFMOrimfSFACO+fyYzhhvco8nq1BVkKAAcIZXGz/M7D73WEYXqgoWtQHgAr1qo849nlGEvtwm91gAYGoWsbbBEVAAMIxw5YvH2Z23EVpQy+u/AcAV+Hkb9z63rnOPZxBhsWa+5RMAZDKbFlVIvzr3WABgrsbq4ny4xpOm/pqklaQ/q6pqr/HvAAAkn2P/lLSa1FFUIenuco8FAJYmXMiwzj2WVxEWAJBfCI0yF8PN7MYXtze5xwIASxeu+t3kHsuRMLAy0wwAFsjM1kW9kQ9hUeceCwDgWFgq2OQeSPp4wTrrQAAAZ3lo5Ks0QljQhgKAwmVrT1n3iVCEBQBMSAiNcebuUNrwmbMAMDF+ROv11539Ylf5F08AAL8tXH+qvuY/8sgVZwFg+vzkvqdrPfm9mT1e5ckBAKPz604NWwSM1vMCAIxm8HM0wiI3R0QBwMz4kVPDFAS+bjHtD+YAAJzli+DvW3IY5EkAAMV715XGaUUBwHKEOb/+nT/+wudaAMBy+KG2D7/6R42XJ6srjQsAUCCf+y+/kocvdDfXGxIAoETpIysu/eWGhW4AWK6Lz83w6oILCwLAQl1UZaS1i5HGBAAo1JtrGV5dbMYbEgCgRF5lnF6e8EuX/xh5TACAQvUvGfIh/OxW0n/GHhAAoFhbSS/bUp4kzdijAQCU6eS6dvqM7kxjAgAUKhYTqSW1Fu0oAMBLW3UZ0eHMbgDAKUcnc6ejo7huFACgzzPCpK4lVUvaV1W1zzoqAEBxPBt2ZtZ8UNeb2uYdEgCgYK2k9QdJnyR9yzsWAEDBvkr6mFpSbdahAABKtpNXGGtJrF8AAF6zSudhtDlHAQAo2l4hMAAAOGcvaaV0fC0AAOeYmVFhAAAu8kHSPl7vHACAyDOi/aDUmwIA4BUEBgDgLbV0CAwAAM5ZSdp9kJ/Bl3kwAIBy1fI1jO+S/so7FgBAwT5J+pYqjDrvWAAABWvUZUV3QgYfoAQA6IsfspdO3NuKdQwAwEtrSbuqqvYpMP6W9K+MAwIAlOmzuozo+Id8P+cbDwCgRN6OavoPPr94EACwWP1iIl588N+iLQUAOPgs6b8vHjWzmrYUACBJR0el739WGFVVtZJaM9tkGBcAoCCeBbuqqk5fPsrMbqgyAAAXrWv7L21GGREAoDhePDxe8osbqgwAWC4ze7z4qFmqDABYJj+U9u3qIvwBaxkAsDB+3ahfPyfPzB7M7O4qowIAFMfM7szsy+/8Ye3H4NbDDwsAUBIzW79rzve0oTUFADPnC923+Z8EAFAsM7v9pYXuV56o9kUQPi8DAGbm3a2oE0+48dAY5gkBANmFguBm6Ce+N7OnQZ8UAJCNLzncX+vJnzjUFgCmz4uA969bvPIPpPKFRXAAmKiwzLB6+7ff9w9dp+cFALg6v5LHeOfYhVV1jpwCgIkIc3cz9j+8ITQAYBpCWGxyDWAzamkDAPhl4VJPm9wD4RwNAChUWHfe5B6LJNpTAFAib0OVExaJf+hGeQMDgAUKb+TLPKI1pNld7rEAwFKlK40Xv1QQ+mV3uccCAEszmbBIPDSe/FP7rnsmIQAgfbzqg8+9de7x/DK/Vsl0kg4AJih0dq5zIcGx+AdzcP0pALgCn2N/zGaODYvh97SoAGAYs+3ieH/tcbL9NQAoRGhBPcx6PqVFBQC/L1xdYxlzaDiK6nHW6QgAA/F582GWLahLeP9tPos1AHAFYWH7LvdYsvJLilBtAECPVxWPi60qzmFtAwAO/IxtqopzQpo+2tifCAUABVjMEVBDscNnznJpEQCL0FvU3uQez6T4eRvpIlp3BAeAuWKuG0hI3fwfLwgAAwrnVNB+GpIfTcX6BoDJC0HBlS+uieAAMFUhKFinGBPBAWAqCIpChBeC4ABQFIKiUP7CPBEcAHIjKCYitKo4RA3AaPxUgNjx2OQeEy4UguOHB0ede0wA5qd3wt2Dma1zjwm/yV/MdFVc2lUABuFvSh+sw3kUc+Ll4m1Y57ilXQXgV/XXJwiKmeu1q+6pOgC8JlQTqe3U5B4TRmaH61WldhWL5AAk/Wxnx2qCtVB0wjsI1jqABbPuatlfwtpEk3tMKFRY64hHWDW5xwXgesxsHVpOj15Z0G3A5bwkTZcdfiY8gPnwkLin5YTBecuK8AAm7ERI3HPeBK6qFx4caQUUrHeEEyGBfM6FB/1PIA9fh7wJIfFESKA4vuYRF8wf/fs699iAOfNWU9r3LCxc17nHBrzJDhciS4fqplKY6gMYwIlW04NXFuxfV1LlHsBS+BrHWtJnSbWkVtLfknZVVW1zjQuYit4+1Ejain1oVARGBv4OKG74taSd2PiBn3oBsVb3Jmurw36yzzW2pSIwCuABciPpkwgQLNSZgIj7QZtrbOgQGAXyAGkk/aVux1mr23F2kr5J2rLzYMr8iKVah228UVc97CR9VbeNU0EUhsCYgNDCWqvbwRr/0VZdgOzEDoZChe230SEgpMP2uxUtpkkgMCbKDxds1LWxUpjsddgJW1HGY2Qn3tzUOrRYU/XAdjlRBMaMnAkR6bidtZPU8m4O7+VrDisdt06l43Boq6raZRkgBkdgzJyHSOoXx0X1Vl018l2HxUWCBEe8Yqj9tla3DaX7O3XbTmortVQO80ZgLFCYBFKQfAz39+omgr1obS2GL0KndlLaHtJjMRjSGwuqhgUiMHDkREWyCt+3OoRJqkxa8c6yeP66xttH/5pe3/S67tS9tjtJe4IBEYGBi4UwWek4TFLF0uplhbIPj+9peQ0vhMEqfP0Uvq91/Lq0IhTwGwgMDKb3Lnalw7vY9H0tDw4dqhPpUK1IIVy0wIDxduGpWy3pD70MhpWO/1/uJP2jEA5UfxgKgYFRhQmx1vGk99F/JT6WbvverfXf3aubHJM23E+/27//wqUT6htXPk1jTeoz9//Q6UCIf9/q5X/zd/WqNXGQAkZGYKB4YaLuf43300QsvZy8+9+/9fhrzoVP+8pjMdjiY0eBRiWA0v0fPGR4m68wwtkAAAAASUVORK5CYII=";class ws extends se.CSS2DObject{constructor(e,t){const i=document.createElement("div");super(i),this.props=e,this.amr=t,this._direction=1,this._controllingRotate=!1,this._controlling=!1,this._startAt=0,this._looper=0,this._initial=0,this._canRotate=!1,this._emitter=new je,this.addListener=this._emitter.addListener.bind(this._emitter),this.removeListener=this._emitter.removeListener.bind(this._emitter),this._update=()=>{if(this._looper=requestAnimationFrame(this._update),this._controlling){let c=(Date.now()-this._startAt)/200;c>4&&(c=4);let h=this._initial+.005*c*this._direction;if(h>this.props.max||h<this.props.min){this.mechanism&&(h<this.props.min?(this.mechanism.position.setZ(this.props.min),this._emitter.emit("change",this.props.min)):h>this.props.max&&(this.mechanism.position.setZ(this.props.max),this._emitter.emit("change",this.props.max)));return}if(this._initial=h,!this.mechanism)return;this.mechanism.position.setZ(h),this._emitter.emit("change",h)}};const r=Di();e.userData&&e.userData.target&&(this.name=e.userData.target.name,t.traverse(c=>{c.name===e.userData.target.name&&(this.mechanism=c)})),i.style.fontSize="30px",i.style.color="#0066FF",i.style.cursor="pointer",i.style.pointerEvents="auto";const l=document.createElement("div");l.style.position="absolute",l.style.left="0",l.style.transform="translateX(-50%) rotate(-180deg)",l.style.marginBottom="5px",l.style.width=l.style.height=r?"34px":"44px",l.style.background=`url(${xs}) center no-repeat`,l.style.backgroundSize="100% auto",l.setAttribute("data-direction","up"),l.style.transition="all .2s";const o=document.createElement("div");if(o.style.position="absolute",o.style.left="0",o.style.transform="translateX(-50%)",l.style.bottom=o.style.top="8px",o.style.width=o.style.height=l.style.width,o.style.background=`url(${xs}) center no-repeat`,o.style.backgroundSize="100% auto",o.style.transition="all .2s",o.setAttribute("data-direction","down"),Array.from([l,o]).forEach(c=>{r||c.addEventListener("mousemove",()=>{c.style.filter="invert(100%)"}),c.addEventListener("mouseleave",()=>{c.style.filter=""}),c.addEventListener("pointerdown",()=>{this.mechanism&&(c.style.filter="invert(100%)",this._controlling=!0,this._startAt=Date.now(),this._initial=this.mechanism.position.z,this._direction=c.getAttribute("data-direction")==="up"?1:-1,this._update())}),c.addEventListener("pointerup",()=>{this._controlling=!1,cancelAnimationFrame(this._looper),c.style.filter=""}),c.addEventListener("pointerleave",()=>{this._controlling=!1,cancelAnimationFrame(this._looper),c.style.filter=""})}),e.userData&&(this._canRotate=e.userData.canRotate,this._canRotate)){const{rotateTarget:c,rotateDuration:h,rotateStep:m,rotateMax:p,rotateMin:s}=e.userData;let a;if(c&&(t.traverse(u=>{u.name===c.name&&(a=u)}),a)){const u=document.createElement("div");u.style.background=`url(${la}) center no-repeat`,u.style.backgroundSize="100% auto",u.style.position="absolute",u.style.top="-50%",u.style.left="-50%",u.style.width=r?"140px":"160px",u.style.height=r?"70px":"80px",u.style.transform="translateX(-50%) translateY(-50%)",i.append(u);const g=document.createElement("div");g.style.background=`url(${aa}) center no-repeat`,g.style.backgroundSize="100% auto",g.style.width=g.style.height=r?"20px":"26px",g.style.position="absolute",g.style.top="0",g.style.transform="translateY(-50%)",g.style.marginBottom="5px",g.setAttribute("data-direction","left"),i.append(g);const _=document.createElement("div");_.style.background=`url(${oa}) center no-repeat`,_.style.backgroundSize="100% auto",_.style.width=_.style.height=r?"20px":"26px",_.style.position="absolute",g.style.left=_.style.right=r?"62px":"69px",_.style.top="0",_.style.transform="translateY(-50%)",_.style.marginBottom="5px",_.setAttribute("data-direction","right"),i.append(_),Array.from([g,_]).forEach(f=>{r||f.addEventListener("mousemove",()=>{f.style.filter="invert(100%)"}),f.addEventListener("mouseleave",()=>{f.style.filter=""}),f.addEventListener("pointerdown",()=>{if(this._timer&&this._timer.isPlaying())return;f.style.filter="invert(100%)",this._controllingRotate=!0,this._startAt=Date.now(),this._direction=f.getAttribute("data-direction")==="left"?1:-1;let v=m/180*Math.PI*this._direction+a.rotation.z;v>p/180*Math.PI?v=p/180*Math.PI:v<s/180*Math.PI&&(v=s/180*Math.PI),this._timer=new zt(a.rotation).to({z:v}).duration(h).start(),this._update()}),f.addEventListener("pointerup",()=>{this._controllingRotate=!1,cancelAnimationFrame(this._looper),f.style.filter=""}),f.addEventListener("pointerleave",()=>{this._controllingRotate=!1,cancelAnimationFrame(this._looper),f.style.filter=""})})}}i.append(l,o),this.scale.set(.01,.01,.01),this.matrixAutoUpdate=!1,this.updateMatrix()}hide(){this.element.style.display="none",this.traverse(e=>{e.visible=!1,e instanceof se.CSS2DObject&&(e.element.style.visibility="hidden")}),this.visible=!1}show(){this.element.style.display="auto",this.traverse(e=>{e.visible=!0,e instanceof se.CSS2DObject&&(e.element.style.visibility="visible")}),this.visible=!0}dispose(){this._emitter.removeAllListeners(),cancelAnimationFrame(this._looper),this.element.remove()}}class ca extends Mr.CSS3DObject{constructor(e){const t=document.createElement("div");super(t),this.props=e,this._scale=.01,this._emitter=new je,this.addEventListener=this._emitter.on.bind(this._emitter),this.removeEventListener=this._emitter.on.bind(this._emitter),this._mouseStart=new d.Vector2,this._targetSize=new d.Vector2,this._caches=[],this._sizeFlag="width",this._direction=1,this._lines=[],this._pointerdown=h=>{const{pageX:m,pageY:p}=h;this.endNode.setPointerCapture(h.pointerId),this._mouseStart.set(m,p),this._targetSize.setX(parseFloat(this.endNode.parentElement.style.width)),this._targetSize.setY(parseFloat(this.endNode.parentElement.style.height))},this._pointermove=h=>{if(!this._mouseStart.x)return;const{pageX:m,pageY:p}=h;let s=m-this._mouseStart.x,a=s+this._targetSize.x;this._sizeFlag==="height"&&(s=p-this._mouseStart.y,a=s*this._direction+this._targetSize.y);const u=a%10;a=a-u,s=(a-this._targetSize.x)*this._direction,this._sizeFlag==="height"&&(s=(a-this._targetSize.y)*this._direction),this._textNode.innerText=(a/100).toFixed(2)+" m",this.endNode.parentElement.style[this._sizeFlag]=`${a}px`},this._pointercancel=h=>{this.endNode.releasePointerCapture(h.pointerId),this._mouseStart.set(0,0)};const{start:i,end:r}=e,l=r.distanceTo(i);this.props.axios==="z"?this.props.axios="y":this.props.axios==="y"&&(this.props.axios="z"),this.props.axios==="y"&&(this._sizeFlag="height");const o=document.createElement("div");o.style.position="absolute",o.style.left="0",o.style.bottom="0",t.append(o),this._textNode=document.createElement("div"),this._textNode.innerText=l.toFixed(2)+" m",o.append(this._textNode);const c=document.createElement("div");this.endNode=c,c.style.position="absolute",c.style.left="auto",c.style.right="0",c.style.width="4px",c.style.height="4px",c.style.background="#0066FF",c.style.borderRadius="50%",c.style.margin="-2px -2px 0 0",c.style.cursor="pointer",o.append(c),this.scale.set(this._scale,this._scale,this._scale),t.style.fontSize="6px",t.style.color="#fff",o.style[this._sizeFlag]=l*100+"px",o.style.textAlign="center",this._sizeFlag==="height"?(o.style.borderLeft="0.1px dashed #fff",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.whiteSpace="nowrap",c.style.top="0",c.style.left="0",c.style.right="auto",c.style.margin="-2px 0 0 -2px"):o.style.borderBottom="0.1px dashed #fff",c.addEventListener("pointerdown",this._pointerdown),c.addEventListener("pointermove",this._pointermove),c.addEventListener("pointerup",this._pointercancel),r[this.props.axios]<i[this.props.axios]?this.rotateY(Math.PI):this._direction=-1}_getIndexByAxios(){return this.props.axios==="y"?1:this.props.axios==="z"?2:0}dispose(){this._lines.forEach(e=>e.dispose()),this._emitter.removeAllListeners(),this.endNode.removeEventListener("pointerdown",this._pointerdown),this.endNode.removeEventListener("pointermove",this._pointermove),this.endNode.removeEventListener("pointerup",this._pointercancel),this.element.remove(),this._caches.forEach(e=>e.clear()),this._caches=[]}}class ha extends d.Object3D{constructor(){super(),this._box3=new d.Box3,this._line11=new Bt("长:"),this._line12=new Bt("宽:"),this._line13=new Bt("高:"),this._outline=new Ks(0,0),this._radius=0,this._hasWidthConfig=!1,this._hasLengthConfig=!1,this._hasHeightConfig=!1,this.follow="",this.followOrigin=0,this.followScale=1,this.originOffset=0,this.translateCache=0,this.head=0,this.tail=0,this._change=()=>{if(!this._app)return;const e=this._app.camera;e&&this._outline.change(e.position)},this.add(this._outline,this._line11,this._line12,this._line13)}get hasSizeConfig(){return{length:this._hasLengthConfig,width:this._hasWidthConfig,height:this._hasHeightConfig}}get size(){return this._box3.clone()}get radius(){return this._radius}init(e){this._app=e,this._app.controls.addEventListener("change",this._change)}reset(){this.hide(),this._line11.reset()}generate(e,t=0){e&&(this._object=e),this.update(t)}show(e=!0){const t=[this._line11,this._line12,this._line13];e&&(this.visible=!0,this._outline.visible=!0,this._outline.show(),t.push(this._outline)),t.forEach(i=>{i.traverse(r=>{r.visible=!0,r instanceof se.CSS2DObject&&(r.element.style.visibility="visible")})})}hide(e=!0){const t=[this._line11,this._line12,this._line13];e&&(this.visible=!1,this._outline.visible=!1,this._outline.hide(),t.push(this._outline)),t.forEach(i=>{i.traverse(r=>{r.visible=!1,r instanceof se.CSS2DObject&&(r.element.style.visibility="hidden")})})}destroy(){var e;(e=this._app)==null||e.controls.removeEventListener("change",this._change),this._line11.destroy(),this._line12.destroy(),this._line13.destroy()}update(e=0){if(!this._object)return;const t=this._object,{box:i,maxRadius:r,hasLength:l,hasHeight:o,hasWidth:c}=Ro(t);this.tail=Math.abs(i.min.x),this.head=Math.abs(i.max.x),this._hasWidthConfig=c,this._hasLengthConfig=l,this._hasHeightConfig=o,this._box3.copy(i),this._radius=r,this.follow&&e&&(this.originOffset=(this.followOrigin-e)*this.followScale),this._outline.update(this._radius),this._change();const h=this._box3.min.x,m=this._box3.max.x,p=this._box3.min.z,s=this._box3.max.z,a=this._box3.min.y,u=this._box3.max.y;let g=.2;const _=new d.Vector3(h,u,0),f=new d.Vector3(m,u,0);this._line11.update(_.clone().sub(new d.Vector3(0,-g/1.8,0)),f.clone().sub(new d.Vector3(0,-g/1.8,0)),this._radius);const v=new d.Vector3(m,a,0);this._line12.update(f.clone().add(new d.Vector3(g,0,0)),v.clone().add(new d.Vector3(g,0,0)),this._radius);const y=new d.Vector3(h,u,p),x=new d.Vector3(h,u,s),w=y.clone();w.y-=g/6;const b=x.clone();b.y-=g/6,this._line13.update(w,b,this._radius)}}class bs extends d.Object3D{constructor(e=.6,t=.4,i=.2){super(),this.isGoods=!0,this._generate(e,t,i)}updateSize(e=.1,t=.1,i=.1){this._generate(e,t,i)}clearAll(){oe(this)}hide(){this.traverse(e=>e.visible=!1)}show(){this.traverse(e=>e.visible=!0)}_generate(e,t,i){this.clearAll();const r=new d.Mesh(new d.BoxGeometry(e,t,i),new d.MeshBasicMaterial({color:new d.Color("#0f5fd5"),transparent:!0,opacity:.4}));r.geometry.translate(0,0,i/2);const l=new d.EdgesGeometry(r.geometry),o=new d.LineDashedMaterial({color:new d.Color("#000"),dashSize:.015,gapSize:.015}),c=new d.LineSegments(l,o);c.computeLineDistances(),this.add(r,c)}}const ua="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAALSURBVAiZY2AAAgAABQABYlUyiAAAAABJRU5ErkJggg==";class vi{constructor(e){this._props=e,this.name="",this.transparentTexture=Oi.load(ua),this._offscreen=new OffscreenCanvas(0,0),this._defaults={...e},this.target=e.target,this.parent=this.target.parent,this.reset()}get imageSize(){return this._props.imageSize}get size(){return this._props.size}get defaultConfigs(){return{canvasWidth:200,canvasHeight:200,scaleX:1,scaleY:1,x:0,y:0,ox:0,oy:0,url:this._defaults.imageUrl}}clear(){this.change()}change(e,t=new d.Vector2(1,1),i=new d.Vector2){this.imageUrl=e;let r;if(e){const l=new Image;l.crossOrigin="anonymous",l.src=e,l.onload=async()=>{var m;let o=window.devicePixelRatio*2;this._offscreen.width=l.width+o,this._offscreen.height=l.height+o;const c=this._offscreen.getContext("2d");c==null||c.clearRect(0,0,this._offscreen.width,this._offscreen.height),c==null||c.drawImage(l,o/2,o/2,l.width,l.height),r=new d.Texture(this._offscreen),r.minFilter=1003,r.colorSpace=d.SRGBColorSpace,r.wrapS=r.wrapT=d.ClampToEdgeWrapping,r.repeat.set(1/t.x,1/t.y),r.offset.set(i.x,i.y),r.flipY=!1,r.needsUpdate=!0;const h=this._props.target;h.material&&((m=h.material.map)==null||m.dispose(),r?(h.material.map=r,h.material.opacity=1):(h.material.map=this.transparentTexture,h.material.opacity=0))}}else{const l=this._props.target;l.material&&(l.material.map=this.transparentTexture)}}reset(){this._props=this._defaults,this.name=this._props.name,this.imageUrl=this._props.imageUrl,this.target=this._props.target,this.change(this.imageUrl||"")}dispose(){this._offscreen=null}}function $s(n){return n.type?n.type==="Mesh":n.isMesh}const fa=n=>{const e=window.performance.now(),t=[];n.updateWorldMatrix(!0,!0),n.traverse(l=>{if($s(l)||l.geometry){const o=l.geometry.clone();if(o.applyMatrix4(l.matrixWorld),o.morphTargetsRelative=!1,o.morphAttributes)for(const c in o.morphAttributes)delete o.morphAttributes[c];for(const c in o.attributes)c!=="position"&&o.deleteAttribute(c);t.push(o)}});const i=Pr.mergeGeometries(t,!1),r=window.performance.now()-e;return console.log(`Merge object: ${n.name} time: ${r.toFixed(2)} ms`),i},Oi=new d.TextureLoader;Oi.crossOrigin="anonymous";class er extends d.Object3D{constructor(e){super(),this._props=e,this._emitter=new je,this.addEventListener=this._emitter.addListener.bind(this._emitter),this._container=new d.Group,this.lines=new d.Group,this.sizeBox=new ha,this._goodsSize=new Eo(0,0,0),this._slots=[],this._logos=[],this._skins=[],this._levels=new Map,this._bodyOpacity=1,this._masts=new Map,this._liftMaxHeight=0,this._jackMaxHeight=0,this._forkMaxHeight=0,this.controllers=[],this.goods=[],this._breathLights=[],this._shelves=new Map,this._shelfMaxLevel=1,this._url="",this._showController=!0,this._showSlots=!0,this._shapeKeys=new Map,this._shapeKeyTimer=0,this._shapeKeyCache="",this._materialsCache=new Map,this.opacityCache=void 0,this._pointCloudMode=!1,this._pointClouds=[],this._originalMeshes=new Map,this._pointCloudAnimations=[],this.actions=[],this._url=e.url||"",this._url&&this.load(this._url).then(),this.add(this._container,this.lines),this._props.showSizeBox&&this.add(this.sizeBox),this.showController=typeof e.showController=="boolean"?e.showController:!0,this._showSlots=typeof e.showSlots=="boolean"?e.showSlots:!0}get shapeKeys(){return this._shapeKeys}get size(){const e=this.sizeBox.size.getSize(new d.Vector3);return{width:e.z,length:e.x,height:e.y}}get goodsSize(){return this._goodsSize}get showController(){return this._showController}set showController(e){this._showController=e,this.controllers.forEach(t=>e?t.show():t.hide())}get slots(){return this._slots}get logos(){return this._logos}get skins(){return this._skins}get bodyOpacity(){return this._bodyOpacity}get fork(){return this._fork}get forkHeight(){var e;return((e=this._fork)==null?void 0:e.position.z)||0}get liftHeight(){var e;return((e=this._lift)==null?void 0:e.position.z)||0}get jack(){return this._jack}get jackHeight(){var e;return((e=this._jack)==null?void 0:e.position.z)||0}get lift(){return this._lift}set bodyOpacity(e){this._bodyOpacity=e,e<1?this._materialsCache.forEach(t=>{t.mat.transparent=!0,t.mat.opacity=e,t.mat.metalness=0,t.mat.roughness=1,t.mat.color=new d.Color("#3859be"),t.mat.needsUpdate=!0}):this._materialsCache.forEach(t=>{t.mat.transparent=t.transparent,t.mat.opacity=t.opacity,t.mat.metalness=t.metalness,t.mat.roughness=t.roughness,t.mat.color=t.color,t.mat.needsUpdate=!0})}init(e){this._app=e,this.sizeBox.init(e),this.addEventListener("shape-key-changed",(t,i)=>{this._slots.forEach(r=>r.shapeKeyChanged(t,i)),this.sizeBox.follow===t?(this.sizeBox.generate(this._container,i),this.sizeBox.originOffset&&(this._container.traverse(r=>{r instanceof d.Mesh&&!r.userData.isDevice&&!r.userData.isBracket&&r.geometry.translate(this.sizeBox.originOffset-this.sizeBox.translateCache,0,0),r instanceof gi&&!r.props.slot.userData.ignoreOriginChanged&&r.parent&&r.parent.position.add(new d.Vector3(this.sizeBox.originOffset-this.sizeBox.translateCache,0,0))}),this.sizeBox.translateCache=this.sizeBox.originOffset,this.sizeBox.generate(this._container))):this.sizeBox.generate(this._container),["width","length","height"].includes(t)&&this._emitter.emit("size-changed",t,i)})}async load(e,t=""){this._url=e,this.name||(this.name=e.substring(e.lastIndexOf("/")+1,e.lastIndexOf("."))),!e.startsWith("blob")&&e.endsWith(".sglb");let i;if(t==="glb"||e.endsWith(".glb"))i=(await ut.loadAsync(e)).scene;else{const l=await new Vt({useCache:!0}).loadAsync(e);if(!l.glb)return;i=l.glb}this._generateAmr(i.clone(!0)),i=null,this._emitter.emit("amr-loaded")}changeSkin(e,t){e&&(e.change(t),this._app&&this._app.usePathTracing&&(this._app.sampleCount=0,this._app.usePathTracing&&(this._app.pathTracer.pausePathTracing=!1,this._app.pathTracer.updateMaterials())))}changeLogo(e,t){e.change(t.url,new d.Vector2(t.scaleX,t.scaleY),new d.Vector2(t.ox,t.oy))}setShapeKey(e,t,i=!0){i&&this._shapeKeyTimer&&e===this._shapeKeyCache&&clearTimeout(this._shapeKeyTimer),this._shapeKeyCache=e,this._shapeKeyTimer=window.setTimeout(()=>{this._container.traverse(r=>{if(!Object.keys(r.morphTargetDictionary||{}).includes(e))return;let l=t;r.userData[`origin_${e}`]&&(l-=r.userData[`origin_${e}`]);const o=r.morphTargetDictionary[e];r.morphTargetInfluences&&(r.morphTargetInfluences[o]=l),r instanceof d.Mesh&&r.geometry.translate(0,0,1e-5)}),i&&this._emitter.emit("shape-key-changed",e,t)},100)}_generateAmr(e){this._mergedGeometry=fa(e),e.traverse(t=>{t.userData.isShelf&&(this._shelf=t),t.userData.isFork&&(this._fork=t),t.userData.isMast&&t.userData.mastLevel&&this._masts.set(t.userData.mastLevel,t),t.userData.isJack&&(this._jack=t),t.userData.isLift&&(this._lift=t),Object.keys(t.morphTargetDictionary||{}).forEach(i=>{let r=t.morphTargetInfluences[t.morphTargetDictionary[i]];t.userData[`origin_${i}`]&&(r+=t.userData[`origin_${i}`]),this._shapeKeys.has(i)||this._shapeKeys.set(i,r)})}),e.traverse(t=>{if(t instanceof d.Mesh){if(t.castShadow=!0,t.receiveShadow=!0,t.material)if(Array.isArray(t.material))t.material.forEach(r=>{r.userData.changeColor&&(this.skins.find(l=>l.name===r.userData.name)||this.skins.push(new Mi({name:r.userData.name,target:r})))});else{if(t.material.userData.isBreathLight&&t.material.emissiveIntensity){t.material.emissive||(t.material.emissive=new d.Color(16777215)),t.material.emissiveIntensity=2,t.material.toneMapped=!1;const r=1e3,l=new ie.Tween(t.material).to({emissiveIntensity:.2}).easing(ie.Easing.Quintic.InOut).duration(r),o=new ie.Tween(t.material).to({emissiveIntensity:2}).easing(ie.Easing.Quintic.InOut).duration(r);l.onComplete(()=>o.start()),o.onComplete(()=>l.start()),l.start(),this._breathLights.push(l,o)}t.material.userData.changeColor&&(this.skins.find(r=>r.name===t.material.userData.name)||this.skins.push(new Mi({name:t.material.userData.name,target:t.material})))}if(t.material)if(Array.isArray(t.material))t.material.forEach(l=>{if(l.userData.isLOGO){t.material.transparent=!0;let o;const c={width:0,height:0};t.material.map&&t.material.map.image&&(c.width=t.material.map.image.width,c.height=t.material.map.image.height,o=mi(t.material.map.image));const h=new vi({name:l.userData.name,target:t,size:us(t),imageSize:c,imageUrl:o});this._logos.push(h)}l.userData.isTransparent&&(l.transparent=!0),this._materialsCache.set(l.uuid,{opacity:l.opacity,transparent:l.transparent,roughness:l.roughness,metalness:l.metalness,color:l.color,mat:l})});else{const r=t.material;if(r.userData.isLOGO){t.material.transparent=!0;let l;const o={width:0,height:0};t.material.map&&t.material.map.image&&(o.width=t.material.map.image.width,o.height=t.material.map.image.height,l=mi(t.material.map.image));const c=new vi({name:r.userData.name,target:t,size:us(t),imageSize:o,imageUrl:l});this._logos.push(c)}r.userData.isTransparent&&(r.transparent=!0),this._materialsCache.set(r.uuid,{opacity:r.opacity,transparent:r.transparent,roughness:r.roughness,metalness:r.metalness,color:r.color,mat:r})}}this.generateController(t,e),this.generateDimension(t,e);const i=this.generateSlot(t,e);i&&this._slots.push(i),t.userData.isOrigin&&Object.keys(t.userData).forEach(l=>{if(l.startsWith("follow_")){const o=l.replace("follow_","");this.shapeKeys.has(o)&&(this.sizeBox.follow=o,this.sizeBox.followOrigin=this._shapeKeys.get(o)||0,this.sizeBox.followScale=t.userData[l])}})}),this.slots.forEach(t=>{t.props.mirrorTarget&&(t.mirrorTarget=this.slots.find(i=>i.props.slot.name===t.props.mirrorTarget))}),e.updateMatrixWorld(!0),this._container.add(e),this.sizeBox.generate(e),this.sizeBox.show()}setHeight(e){this.setShapeKey("height",e)}setWeight(e){this.setShapeKey("width",e)}setLength(e){this.setShapeKey("length",e)}limitValue(e){this.name==="SFL-CDD14"&&(e>1.6?this.setShapeKey("mast",1):this.setShapeKey("mast",0)),["SFL-CDD20","SFL-CDD20-Y"].includes(this.name)&&(e>1.6?this.setShapeKey("mast",1):this.setShapeKey("mast",0)),this.name==="SFL-CDD15"&&(e>2.43?this.setShapeKey("mast",1):this.setShapeKey("mast",0)),["SFL-CPD20-Y","SFL-CPD30-Y"].includes(this.name)&&(e>3.5?this.setShapeKey("mast",2):e>3?this.setShapeKey("mast",1):this.setShapeKey("mast",0))}setForkHeight(e){if(this._fork){if(e>this._forkMaxHeight&&(e=this._forkMaxHeight),this._fork.position.z=e,this._masts.size===1){const t=this._masts.get(2),i=(t==null?void 0:t.userData.startHeight)||.1;t&&(t.position.z=(e-i)*.5)}this._emitter.emit("fork-height-change",e)}}setForkMaxHeight(e){this._fork&&(this._forkMaxHeight=e,this.limitValue(e),this.controllers.forEach(t=>{t.name.toLowerCase().includes("fork")&&(t.props.max=e)}),this._fork&&this.forkHeight>this._forkMaxHeight&&this.setForkHeight(e))}setLiftHeight(e){this._lift&&(e>this._liftMaxHeight&&(e=this._liftMaxHeight),this._lift.position.z=e)}getLiftMaxHeight(){return this._liftMaxHeight}setLiftMaxHeight(e){if(!this._lift)return;this._liftMaxHeight=e,this.limitValue(e),this.controllers.forEach(l=>{l.name.toLowerCase().includes("lift")&&(l.props.max=e)}),this.liftHeight>this._liftMaxHeight&&this.setLiftHeight(e);let t=.46;this.levelOffset&&(t=this.levelOffset+.1);let i=e+t;const r=this.getShelfMinHeight()+t||0;i<r&&(i=r),this.setHeight(i)}setJackMaxHeight(e){this._jack&&(this._jackMaxHeight=e,this.limitValue(e),this.controllers.forEach(t=>{t.name.toLowerCase().includes("jack")&&(t.props.max=e)}),this.jackHeight>this._jackMaxHeight&&this.setJackHeight(e))}setJackHeight(e){this._jack&&(e>this._jackMaxHeight&&(e=this._jackMaxHeight),requestAnimationFrame(()=>{this.setShapeKey("jackHeight",e,!1)}),this._jack.position.z=e)}setLevel(e){}setGoodsSize(e){this._goodsSize.length=e.length,this._goodsSize.width=e.width,this._goodsSize.height=e.height,this.setShelfLevel(this._shelfMaxLevel)}getShelfMinHeight(){const e=this.levelOffset,t=this._shelfMaxLevel,i=this._shelves.get(0);return i?i.position.z+e*t+.1:0}getShelfMaxShelfHeight(){const e=this.levelOffset,t=this._shelfMaxLevel,i=this._shelves.get(0);if(i)return i.position.z+e*(t-1)}get levelOffset(){return this._goodsSize.height+.2}setShapeKeyToMesh(e,t,i){if(!Object.keys(e.morphTargetDictionary||{}).includes(t))return;const r=e.morphTargetDictionary[t];e.morphTargetInfluences&&(e.morphTargetInfluences[r]=i),e.geometry.translate(0,0,1e-5)}setShelfLevel(e=3){var r;if(!this._shelf)return;this._shelfMaxLevel=e;const t=this.levelOffset;this._shelves.delete(0),this._shelves.forEach(l=>{oe(l),l.parent&&l.removeFromParent()}),this.goods=[],this._shelves.clear(),this._shelves.set(0,this._shelf);for(let l=1;l<e;l++){if(!this._shelf)return;this._shelf.traverse(h=>{$s(h)&&(this.setShapeKeyToMesh(h,"goodsWidth",this._goodsSize.width),this.setShapeKeyToMesh(h,"goodsLength",this._goodsSize.length))});const o=this._shelf.clone(!0);o.position.z+=t*l,this._shelves.set(l,o),(r=this._shelf.parent)==null||r.add(o);let c;if(o.traverse(h=>{h.userData.isShelfContainer&&(c=h)}),(this.shapeKeys.has("goodsLength")||this.shapeKeys.has("goodsWidth"))&&(c==null||c.position.setX((c==null?void 0:c.position.x)-this._goodsSize.length/2)),c){const h=new bs(this._goodsSize.length,this._goodsSize.width,this._goodsSize.height);if(c.add(h),this.goods.push(h),l===1){const m=new bs(this._goodsSize.length,this._goodsSize.width,this._goodsSize.height);m.position.z-=t,c.add(m),this.goods.push(m)}}}const i=this.getShelfMinHeight()||0;this._liftMaxHeight<i&&this.setLiftMaxHeight(i)}generateOuterLine(){this.traverse(e=>{if(e.userData.isOuterObject){const t=this.sizeBox.radius;this._outline?this._outline.update(t):(this._outline=new Ks(t,0),this.add(this._outline))}})}generateController(e,t){if(this.showController){if(e.userData.isForkController&&e.userData.target){const i=e.userData.target.name,{min:r,max:l}=e.userData;let o;if(t.traverse(h=>{h.name===i&&(o=h)}),!o)return;const c=new ws({name:"",target:i,default:0,min:r,max:l},o);e.add(c)}else if(e.userData.isController&&e.userData.target){const i=e.userData.target.name,{min:r,max:l}=e.userData;let o;if(t.traverse(h=>{h.name===i&&(o=h)}),!o)return;const c=new ws({name:"",userData:e.userData,target:e.userData.key,default:0,min:r||0,max:l||1},o);e.add(c),this.controllers.push(c),(o.userData.isFork||o.userData.isLift||o.userData.isJack)&&(this._forkMaxHeight=l||1,this._liftMaxHeight=l||1,this._jackMaxHeight=l||1,c.addListener("change",h=>{this.setForkHeight(h),this.setLiftHeight(h),this.setJackHeight(h)}))}}}generateDimension(e,t){if(e.userData.isDimension){const i=e.userData.divider,r=Mo(e.userData.startOrigin),l=e.userData.axios;let o,c;if(l==="x"?(o=new d.Vector3(e.userData.start-e.position.x,0,0),c=o.clone().setX(e.userData.end-e.position.x)):l==="z"?(o=new d.Vector3(0,e.userData.start-e.position.y,0),c=o.clone().setY(e.userData.end-e.position.y)):(o=new d.Vector3(0,0,e.userData.start-e.position.z),c=o.clone().setZ(e.userData.end-e.position.z)),!Object.keys(e.userData).flatMap(s=>s.startsWith("target")?e.userData[s].name:[]).length)return;const p=new ca({start:o,end:c,startOrigin:r,axios:l,divider:i});e.add(p)}}generateSlot(e,t){var i,r;if(e.userData.isSlot){const l=e.userData.name,o=e.userData.isMirror,c=(i=e.userData.mirrorSlot)==null?void 0:i.name;if(l){const h=e.userData.holeTarget&&e.userData.holeTarget.name;let m;h&&t.traverse(u=>{u.name===h&&(m=u)});const p=new Map;Object.keys(e.userData).forEach(u=>{if(u.startsWith("follow_")){const g=u.split("_")[1];if(g){let _=e.userData[u];p.set(g,{scale:_,origin:this.shapeKeys.get(g)||0})}}});const s=(r=this._app)==null?void 0:r.props.isMobile,a=new gi({name:l,follows:p,slot:e,show:this._showSlots,isMirror:o,mirrorTarget:c,isMobile:s});return a.holeTarget=m,a.addEventListener(H.ON_DROP,u=>{this._app&&this._app.props.useSound&&this._app.sound.play()}),a.addEventListener(H.ON_BEFORE_SELECTED,u=>{this._slots.forEach(g=>{g.selected&&(g.selected=!1)})}),a.addEventListener(H.ON_ERROR_STATE_CHANGE,u=>{if(this._app)if(this._app._outlinePassError.selectedObjects=this._app._outlinePassError.selectedObjects.filter(g=>!!g.parent),u){if(a.device){if(this._app._outlinePassError.selectedObjects.find(_=>{var f;return _.parent==((f=a.device)==null?void 0:f.parent)}))return;this._app._outlinePassError.selectedObjects=[a.device,...this._app._outlinePassError.selectedObjects]}}else a.device&&(this._app._outlinePassError.selectedObjects=this._app._outlinePassError.selectedObjects.filter(g=>{var _;return g.parent!=((_=a.device)==null?void 0:_.parent)}))}),a}}}clean(){this._emitter.removeAllListeners(),this.controllers.forEach(e=>e.dispose()),this.controllers=[],oe(this._container),this._levels.forEach(e=>e.destroy()),this._levels.clear(),this._slots=[],this._logos=[],this._skins=[],this._materialsCache.clear(),this.opacityCache=void 0,this._breathLights.forEach(e=>e.stop()),this._breathLights=[],this.sizeBox.reset()}destroy(){this._pointCloudMode&&this._clearPointClouds(),this.clean(),this.sizeBox.destroy()}setPointCloudMode(e){this._pointCloudMode=e,e?(this.sizeBox.hide(),this.controllers.forEach(t=>t.hide()),this.slots.forEach(t=>t.hide()),this._createPointClouds()):(this.sizeBox.show(),this.slots.forEach(t=>t.hide()),this.controllers.forEach(t=>t.show()),this._clearPointClouds())}_createPointClouds(){this._clearPointClouds();const e=[],t=[],i=.02,r=.05,l=1e7;new d.Vector3;const o=new d.Vector3(1/0,1/0,1/0),c=new d.Vector3(-1/0,-1/0,-1/0);this._container.traverse(p=>{if(p instanceof d.Mesh&&p.geometry&&p.visible){this._originalMeshes.set(p.uuid,{mesh:p,visible:p.visible}),p.visible=!1,p.geometry.computeBoundingBox();const s=p.geometry.boundingBox.clone();s.applyMatrix4(p.matrixWorld),o.min(s.min),c.max(s.max);const a=p.geometry,u=a.attributes.position,g=a.index;if(u){p.updateMatrixWorld();const _=p.matrixWorld;if(g){const f=g.array;for(let v=0;v<f.length;v+=3){const y=f[v],x=f[v+1],w=f[v+2],b=new d.Vector3(u.getX(y),u.getY(y),u.getZ(y)).applyMatrix4(_),C=new d.Vector3(u.getX(x),u.getY(x),u.getZ(x)).applyMatrix4(_),T=new d.Vector3(u.getX(w),u.getY(w),u.getZ(w)).applyMatrix4(_);e.length<l*3&&this._generatePointsOnTriangle(b,C,T,i,r,e,t)}}else for(let f=0;f<u.count;f++){const v=new d.Vector3(u.getX(f),u.getY(f),u.getZ(f)).applyMatrix4(_);e.push(v.x,v.y,v.z);const y=(v.y-o.y)/(c.y-o.y);t.push(0,y*.5,.5+y*.5)}}}});const h=this._removeDuplicatePoints(e,t,i*.5),m=1e5;if(h.positions.length>m*3){const p=m*3/h.positions.length,s=[],a=[];for(let u=0;u<h.positions.length;u+=3)Math.random()<p&&(s.push(h.positions[u],h.positions[u+1],h.positions[u+2]),a.push(h.colors[u],h.colors[u+1],h.colors[u+2]));h.positions=s,h.colors=a}if(h.positions.length>0){const p=o.clone().add(c).multiplyScalar(.5),s=c.clone().sub(o),a=Math.max(s.x,s.y,s.z);if(a===0||!isFinite(a)){console.warn("Point cloud generation failed: invalid model bounds");return}const u=new Float32Array(h.positions.length),g=new Float32Array(h.positions),_=new Float32Array(h.colors.length),f=new Float32Array(h.colors);for(let S=0;S<h.positions.length;S+=3){const A=S/3;g[S],g[S+1],g[S+2];const I=A/(h.positions.length/3)*Math.PI*4,M=Math.random(),R=Math.sqrt(M),E=.05+Math.random()*.1,F=a*2.2*(E+R*(1-E)),D=3,L=A%D*(Math.PI*2/D)+I,V=Math.random()*.4,z=F*(1+V),G=R,Y=.25+R*.2,le=(Math.random()<.5?-1:1)*Math.random()*a*Y*G,we=(Math.random()-.5)*a*.25*G,me=a*.3*(1+R*.5),jt=1.2,qt=.85;u[S]=p.x+Math.cos(L)*z*jt+(Math.random()-.5)*me,u[S+1]=p.y+le+we,u[S+2]=p.z+Math.sin(L)*z*qt+(Math.random()-.5)*me;const Yt=Math.random(),N=Math.random()<.1?1.5:1,Qt=R>.75?.7:R>.5?.4:0,be=Yt*(1-Qt);be<.7?(_[S]=(.1+Math.random()*.2)*N,_[S+1]=(.6+Math.random()*.4)*N,_[S+2]=(.8+Math.random()*.2)*N):be<.8?(_[S]=(.6+Math.random()*.4)*N,_[S+1]=(.1+Math.random()*.3)*N,_[S+2]=(.8+Math.random()*.2)*N):be<.92?(_[S]=(.8+Math.random()*.2)*N,_[S+1]=(.2+Math.random()*.3)*N,_[S+2]=(.6+Math.random()*.3)*N):(_[S]=(.9+Math.random()*.1)*N,_[S+1]=(.4+Math.random()*.3)*N,_[S+2]=(.1+Math.random()*.2)*N)}const v=new d.BufferGeometry;v.setAttribute("position",new d.Float32BufferAttribute(u,3)),v.setAttribute("color",new d.Float32BufferAttribute(_,3));const y=new d.PointsMaterial({size:.002,color:"#367BF5",vertexColors:!1,opacity:.1,transparent:!1,depthWrite:!1,sizeAttenuation:!0}),x=new d.Points(v,y);this.add(x),this._pointClouds.push(x);const w=v.attributes.position,b=v.attributes.color,C={progress:0};y.opacity=.3;const T=new ie.Tween(C).to({progress:1},600).easing(ie.Easing.Linear.None).onUpdate(()=>{const S=C.progress,A=w.array,P=b.array,I=.6,M=S<I,R=S<.9,E=M?S/I:1,F=E*E,D=F*Math.PI*1.25,L=M?0:(S-I)/(1-I),z=(1-Math.pow(1-L,3))*Math.PI*.75,G=M?D:D+z;for(let B=0;B<A.length;B+=3){const le=u[B],we=u[B+1],me=u[B+2],jt=g[B],qt=g[B+1],Yt=g[B+2],N=M?F:1,Qt=le+(jt-le)*N,be=we+(qt-we)*N,hr=me+(Yt-me)*N,Ae=Qt-p.x,Te=hr-p.z;if(M){const Ye=Math.sqrt(Ae*Ae+Te*Te),Qe=Math.atan2(Te,Ae)+G;A[B]=p.x+Math.cos(Qe)*Ye,A[B+1]=be,A[B+2]=p.z+Math.sin(Qe)*Ye}else{const Ye=Math.sqrt(Ae*Ae+Te*Te),Qe=Math.atan2(Te,Ae)+G;A[B]=p.x+Math.cos(Qe)*Ye,A[B+1]=be,A[B+2]=p.z+Math.sin(Qe)*Ye}R&&(P[B]=_[B]+(f[B]-_[B])*S,P[B+1]=_[B+1]+(f[B+1]-_[B+1])*S,P[B+2]=_[B+2]+(f[B+2]-_[B+2])*S)}let Y=.3;M?Y=.3+.4*F:Y=.7-.1*L,y.opacity=Y,w.needsUpdate=!0,R&&(b.needsUpdate=!0)}).onComplete(()=>{const S=this._pointCloudAnimations.indexOf(T);S>-1&&this._pointCloudAnimations.splice(S,1);const A=new Os.LineMaterial({color:"#222",linewidth:.001,opacity:.1,transparent:!0,depthTest:!0,depthWrite:!1}),P=new d.MeshBasicMaterial({colorWrite:!0,color:"#0000ff",depthWrite:!1,depthTest:!0,transparent:!0,opacity:.12}),I=new d.Mesh(this._mergedGeometry,P);I.renderOrder=0,this.lines.add(I);const M=new d.EdgesGeometry(this._mergedGeometry,15),R=new Sr.LineSegmentsGeometry().fromEdgesGeometry(M),E=new Tr.LineSegments2(R,A);E.renderOrder=1,this.slots.forEach(F=>F.show()),x.visible=!1}).start();this._pointCloudAnimations.push(T)}}_generatePointsOnTriangle(e,t,i,r,l,o,c){const h=e.distanceTo(t),m=t.distanceTo(i),p=i.distanceTo(e),s=Math.max(h,m,p),a=Math.max(2,Math.ceil(s/r));if(s>l)for(let u=0;u<=a;u++)for(let g=0;g<=a-u;g++){const _=u/a,f=g/a,v=1-_-f;if(v>=0){const y=new d.Vector3().addScaledVector(e,_).addScaledVector(t,f).addScaledVector(i,v);o.push(y.x,y.y,y.z),c.push(0,y.y/5,1-y.y/1.4)}}else{o.push(e.x,e.y,e.z),o.push(t.x,t.y,t.z),o.push(i.x,i.y,i.z);for(let u=0;u<3;u++)c.push(0,0,0)}}_removeDuplicatePoints(e,t,i){const r=[],l=[],o=new Map;for(let c=0;c<e.length;c+=3){const h=e[c],m=e[c+1],p=e[c+2],s=`${Math.round(h/i)}_${Math.round(m/i)}_${Math.round(p/i)}`;o.has(s)||(o.set(s,!0),r.push(h,m,p),l.push(t[c],t[c+1],t[c+2]))}return{positions:r,colors:l}}_clearPointClouds(){this._pointCloudAnimations.forEach(e=>{e.stop()}),this._pointCloudAnimations=[],this._pointClouds.forEach(e=>{e.geometry.dispose(),e.material instanceof d.PointsMaterial&&e.material.dispose(),e.removeFromParent()}),this._pointClouds=[],this._originalMeshes.forEach(({mesh:e,visible:t})=>{e.visible=t}),this._originalMeshes.clear()}playAction(e,t=!0){}pauseAction(e){console.log(`Pausing action: ${e}`)}}const tr=0,da=1,pa=2,As=2,ei=1.25,Ts=1,ct=6*4+4+4,Wt=65535,ma=Math.pow(2,-24),ti=Symbol("SKIP_GENERATION");function ga(n){return n.index?n.index.count:n.attributes.position.count}function qe(n){return ga(n)/3}function va(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function _a(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,r=va(t,i);n.setIndex(new d.BufferAttribute(r,1));for(let l=0;l<t;l++)r[l]=l}}function ir(n){const e=qe(n),t=n.drawRange,i=t.start/3,r=(t.start+t.count)/3,l=Math.max(0,i),o=Math.min(e,r)-l;return[{offset:Math.floor(l),count:Math.floor(o)}]}function sr(n){if(!n.groups||!n.groups.length)return ir(n);const e=[],t=new Set,i=n.drawRange,r=i.start/3,l=(i.start+i.count)/3;for(const c of n.groups){const h=c.start/3,m=(c.start+c.count)/3;t.add(Math.max(r,h)),t.add(Math.min(l,m))}const o=Array.from(t.values()).sort((c,h)=>c-h);for(let c=0;c<o.length-1;c++){const h=o[c],m=o[c+1];e.push({offset:Math.floor(h),count:Math.floor(m-h)})}return e}function ya(n){if(n.groups.length===0)return!1;const e=qe(n),t=sr(n).sort((l,o)=>l.offset-o.offset),i=t[t.length-1];i.count=Math.min(e-i.offset,i.count);let r=0;return t.forEach(({count:l})=>r+=l),e!==r}function ii(n,e,t,i,r){let l=1/0,o=1/0,c=1/0,h=-1/0,m=-1/0,p=-1/0,s=1/0,a=1/0,u=1/0,g=-1/0,_=-1/0,f=-1/0;for(let v=e*6,y=(e+t)*6;v<y;v+=6){const x=n[v+0],w=n[v+1],b=x-w,C=x+w;b<l&&(l=b),C>h&&(h=C),x<s&&(s=x),x>g&&(g=x);const T=n[v+2],S=n[v+3],A=T-S,P=T+S;A<o&&(o=A),P>m&&(m=P),T<a&&(a=T),T>_&&(_=T);const I=n[v+4],M=n[v+5],R=I-M,E=I+M;R<c&&(c=R),E>p&&(p=E),I<u&&(u=I),I>f&&(f=I)}i[0]=l,i[1]=o,i[2]=c,i[3]=h,i[4]=m,i[5]=p,r[0]=s,r[1]=a,r[2]=u,r[3]=g,r[4]=_,r[5]=f}function xa(n,e=null,t=null,i=null){const r=n.attributes.position,l=n.index?n.index.array:null,o=qe(n),c=r.normalized;let h;e===null?(h=new Float32Array(o*6*4),t=0,i=o):(h=e,t=t||0,i=i||o);const m=r.array,p=r.offset||0;let s=3;r.isInterleavedBufferAttribute&&(s=r.data.stride);const a=["getX","getY","getZ"];for(let u=t;u<t+i;u++){const g=u*3,_=u*6;let f=g+0,v=g+1,y=g+2;l&&(f=l[f],v=l[v],y=l[y]),c||(f=f*s+p,v=v*s+p,y=y*s+p);for(let x=0;x<3;x++){let w,b,C;c?(w=r[a[x]](f),b=r[a[x]](v),C=r[a[x]](y)):(w=m[f+x],b=m[v+x],C=m[y+x]);let T=w;b<T&&(T=b),C<T&&(T=C);let S=w;b>S&&(S=b),C>S&&(S=C);const A=(S-T)/2,P=x*2;h[_+P+0]=T+A,h[_+P+1]=A+(Math.abs(T)+A)*ma}}return h}function O(n,e,t){return t.min.x=e[n],t.min.y=e[n+1],t.min.z=e[n+2],t.max.x=e[n+3],t.max.y=e[n+4],t.max.z=e[n+5],t}function Ss(n){let e=-1,t=-1/0;for(let i=0;i<3;i++){const r=n[i+3]-n[i];r>t&&(t=r,e=i)}return e}function Cs(n,e){e.set(n)}function Ms(n,e,t){let i,r;for(let l=0;l<3;l++){const o=l+3;i=n[l],r=e[l],t[l]=i<r?i:r,i=n[o],r=e[o],t[o]=i>r?i:r}}function _t(n,e,t){for(let i=0;i<3;i++){const r=e[n+2*i],l=e[n+2*i+1],o=r-l,c=r+l;o<t[i]&&(t[i]=o),c>t[i+3]&&(t[i+3]=c)}}function Ke(n){const e=n[3]-n[0],t=n[4]-n[1],i=n[5]-n[2];return 2*(e*t+t*i+i*e)}const ne=32,wa=(n,e)=>n.candidate-e.candidate,ce=new Array(ne).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),yt=new Float32Array(6);function ba(n,e,t,i,r,l){let o=-1,c=0;if(l===tr)o=Ss(e),o!==-1&&(c=(e[o]+e[o+3])/2);else if(l===da)o=Ss(n),o!==-1&&(c=Aa(t,i,r,o));else if(l===pa){const h=Ke(n);let m=ei*r;const p=i*6,s=(i+r)*6;for(let a=0;a<3;a++){const u=e[a],f=(e[a+3]-u)/ne;if(r<ne/4){const v=[...ce];v.length=r;let y=0;for(let w=p;w<s;w+=6,y++){const b=v[y];b.candidate=t[w+2*a],b.count=0;const{bounds:C,leftCacheBounds:T,rightCacheBounds:S}=b;for(let A=0;A<3;A++)S[A]=1/0,S[A+3]=-1/0,T[A]=1/0,T[A+3]=-1/0,C[A]=1/0,C[A+3]=-1/0;_t(w,t,C)}v.sort(wa);let x=r;for(let w=0;w<x;w++){const b=v[w];for(;w+1<x&&v[w+1].candidate===b.candidate;)v.splice(w+1,1),x--}for(let w=p;w<s;w+=6){const b=t[w+2*a];for(let C=0;C<x;C++){const T=v[C];b>=T.candidate?_t(w,t,T.rightCacheBounds):(_t(w,t,T.leftCacheBounds),T.count++)}}for(let w=0;w<x;w++){const b=v[w],C=b.count,T=r-b.count,S=b.leftCacheBounds,A=b.rightCacheBounds;let P=0;C!==0&&(P=Ke(S)/h);let I=0;T!==0&&(I=Ke(A)/h);const M=Ts+ei*(P*C+I*T);M<m&&(o=a,m=M,c=b.candidate)}}else{for(let x=0;x<ne;x++){const w=ce[x];w.count=0,w.candidate=u+f+x*f;const b=w.bounds;for(let C=0;C<3;C++)b[C]=1/0,b[C+3]=-1/0}for(let x=p;x<s;x+=6){let C=~~((t[x+2*a]-u)/f);C>=ne&&(C=ne-1);const T=ce[C];T.count++,_t(x,t,T.bounds)}const v=ce[ne-1];Cs(v.bounds,v.rightCacheBounds);for(let x=ne-2;x>=0;x--){const w=ce[x],b=ce[x+1];Ms(w.bounds,b.rightCacheBounds,w.rightCacheBounds)}let y=0;for(let x=0;x<ne-1;x++){const w=ce[x],b=w.count,C=w.bounds,S=ce[x+1].rightCacheBounds;b!==0&&(y===0?Cs(C,yt):Ms(C,yt,yt)),y+=b;let A=0,P=0;y!==0&&(A=Ke(yt)/h);const I=r-y;I!==0&&(P=Ke(S)/h);const M=Ts+ei*(A*y+P*I);M<m&&(o=a,m=M,c=w.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${l} used.`);return{axis:o,pos:c}}function Aa(n,e,t,i){let r=0;for(let l=e,o=e+t;l<o;l++)r+=n[l*6+i*2];return r/t}class si{constructor(){this.boundingData=new Float32Array(6)}}function Ta(n,e,t,i,r,l){let o=i,c=i+r-1;const h=l.pos,m=l.axis*2;for(;;){for(;o<=c&&t[o*6+m]<h;)o++;for(;o<=c&&t[c*6+m]>=h;)c--;if(o<c){for(let p=0;p<3;p++){let s=e[o*3+p];e[o*3+p]=e[c*3+p],e[c*3+p]=s}for(let p=0;p<6;p++){let s=t[o*6+p];t[o*6+p]=t[c*6+p],t[c*6+p]=s}o++,c--}else return o}}function Sa(n,e,t,i,r,l){let o=i,c=i+r-1;const h=l.pos,m=l.axis*2;for(;;){for(;o<=c&&t[o*6+m]<h;)o++;for(;o<=c&&t[c*6+m]>=h;)c--;if(o<c){let p=n[o];n[o]=n[c],n[c]=p;for(let s=0;s<6;s++){let a=t[o*6+s];t[o*6+s]=t[c*6+s],t[c*6+s]=a}o++,c--}else return o}}function q(n,e){return e[n+15]===65535}function Q(n,e){return e[n+6]}function Z(n,e){return e[n+14]}function X(n){return n+8}function J(n,e){return e[n+6]}function rr(n,e){return e[n+7]}let nr,ot,Lt,or;const Ca=Math.pow(2,32);function _i(n){return"count"in n?1:1+_i(n.left)+_i(n.right)}function Ma(n,e,t){return nr=new Float32Array(t),ot=new Uint32Array(t),Lt=new Uint16Array(t),or=new Uint8Array(t),yi(n,e)}function yi(n,e){const t=n/4,i=n/2,r="count"in e,l=e.boundingData;for(let o=0;o<6;o++)nr[t+o]=l[o];if(r)if(e.buffer){const o=e.buffer;or.set(new Uint8Array(o),n);for(let c=n,h=n+o.byteLength;c<h;c+=ct){const m=c/2;q(m,Lt)||(ot[c/4+6]+=t)}return n+o.byteLength}else{const o=e.offset,c=e.count;return ot[t+6]=o,Lt[i+14]=c,Lt[i+15]=Wt,n+ct}else{const o=e.left,c=e.right,h=e.splitAxis;let m;if(m=yi(n+ct,o),m/4>Ca)throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return ot[t+6]=m/4,m=yi(m,c),ot[t+7]=h,m}}function Pa(n,e){const t=(n.index?n.index.count:n.attributes.position.count)/3,i=t>2**16,r=i?4:2,l=e?new SharedArrayBuffer(t*r):new ArrayBuffer(t*r),o=i?new Uint32Array(l):new Uint16Array(l);for(let c=0,h=o.length;c<h;c++)o[c]=c;return o}function Ra(n,e,t,i,r){const{maxDepth:l,verbose:o,maxLeafTris:c,strategy:h,onProgress:m,indirect:p}=r,s=n._indirectBuffer,a=n.geometry,u=a.index?a.index.array:null,g=p?Sa:Ta,_=qe(a),f=new Float32Array(6);let v=!1;const y=new si;return ii(e,t,i,y.boundingData,f),w(y,t,i,f),y;function x(b){m&&m(b/_)}function w(b,C,T,S=null,A=0){if(!v&&A>=l&&(v=!0,o&&(console.warn(`MeshBVH: Max depth of ${l} reached when generating BVH. Consider increasing maxDepth.`),console.warn(a))),T<=c||A>=l)return x(C+T),b.offset=C,b.count=T,b;const P=ba(b.boundingData,S,e,C,T,h);if(P.axis===-1)return x(C+T),b.offset=C,b.count=T,b;const I=g(s,u,e,C,T,P);if(I===C||I===C+T)x(C+T),b.offset=C,b.count=T;else{b.splitAxis=P.axis;const M=new si,R=C,E=I-C;b.left=M,ii(e,R,E,M.boundingData,f),w(M,R,E,f,A+1);const F=new si,D=I,L=T-E;b.right=F,ii(e,D,L,F.boundingData,f),w(F,D,L,f,A+1)}return b}}function Ia(n,e){const t=n.geometry;e.indirect&&(n._indirectBuffer=Pa(t,e.useSharedArrayBuffer),ya(t)&&!e.verbose&&console.warn('MeshBVH: Provided geometry contains groups that do not fully span the vertex contents while using the "indirect" option. BVH may incorrectly report intersections on unrendered portions of the geometry.')),n._indirectBuffer||_a(t,e);const i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,r=xa(t),l=e.indirect?ir(t):sr(t);n._roots=l.map(o=>{const c=Ra(n,r,o.offset,o.count,e),h=_i(c),m=new i(ct*h);return Ma(0,c,m),m})}class ae{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,r=-1/0;for(let l=0,o=e.length;l<o;l++){const h=e[l][t];i=h<i?h:i,r=h>r?h:r}this.min=i,this.max=r}setFromPoints(e,t){let i=1/0,r=-1/0;for(let l=0,o=t.length;l<o;l++){const c=t[l],h=e.dot(c);i=h<i?h:i,r=h>r?h:r}this.min=i,this.max=r}isSeparated(e){return this.min>e.max||e.min>this.max}}ae.prototype.setFromBox=function(){const n=new d.Vector3;return function(t,i){const r=i.min,l=i.max;let o=1/0,c=-1/0;for(let h=0;h<=1;h++)for(let m=0;m<=1;m++)for(let p=0;p<=1;p++){n.x=r.x*h+l.x*(1-h),n.y=r.y*m+l.y*(1-m),n.z=r.z*p+l.z*(1-p);const s=t.dot(n);o=Math.min(s,o),c=Math.max(s,c)}this.min=o,this.max=c}}();const Ea=function(){const n=new d.Vector3,e=new d.Vector3,t=new d.Vector3;return function(r,l,o){const c=r.start,h=n,m=l.start,p=e;t.subVectors(c,m),n.subVectors(r.end,r.start),e.subVectors(l.end,l.start);const s=t.dot(p),a=p.dot(h),u=p.dot(p),g=t.dot(h),f=h.dot(h)*u-a*a;let v,y;f!==0?v=(s*a-g*u)/f:v=0,y=(s+v*a)/u,o.x=v,o.y=y}}(),zi=function(){const n=new d.Vector2,e=new d.Vector3,t=new d.Vector3;return function(r,l,o,c){Ea(r,l,n);let h=n.x,m=n.y;if(h>=0&&h<=1&&m>=0&&m<=1){r.at(h,o),l.at(m,c);return}else if(h>=0&&h<=1){m<0?l.at(0,c):l.at(1,c),r.closestPointToPoint(c,!0,o);return}else if(m>=0&&m<=1){h<0?r.at(0,o):r.at(1,o),l.closestPointToPoint(o,!0,c);return}else{let p;h<0?p=r.start:p=r.end;let s;m<0?s=l.start:s=l.end;const a=e,u=t;if(r.closestPointToPoint(s,!0,e),l.closestPointToPoint(p,!0,t),a.distanceToSquared(s)<=u.distanceToSquared(p)){o.copy(a),c.copy(s);return}else{o.copy(p),c.copy(u);return}}}}(),Fa=function(){const n=new d.Vector3,e=new d.Vector3,t=new d.Plane,i=new d.Line3;return function(l,o){const{radius:c,center:h}=l,{a:m,b:p,c:s}=o;if(i.start=m,i.end=p,i.closestPointToPoint(h,!0,n).distanceTo(h)<=c||(i.start=m,i.end=s,i.closestPointToPoint(h,!0,n).distanceTo(h)<=c)||(i.start=p,i.end=s,i.closestPointToPoint(h,!0,n).distanceTo(h)<=c))return!0;const _=o.getPlane(t);if(Math.abs(_.distanceToPoint(h))<=c){const v=_.projectPoint(h,e);if(o.containsPoint(v))return!0}return!1}}(),Da=1e-15;function ri(n){return Math.abs(n)<Da}class te extends d.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new d.Vector3),this.satBounds=new Array(4).fill().map(()=>new ae),this.points=[this.a,this.b,this.c],this.sphere=new d.Sphere,this.plane=new d.Plane,this.needsUpdate=!0}intersectsSphere(e){return Fa(e,this)}update(){const e=this.a,t=this.b,i=this.c,r=this.points,l=this.satAxes,o=this.satBounds,c=l[0],h=o[0];this.getNormal(c),h.setFromPoints(c,r);const m=l[1],p=o[1];m.subVectors(e,t),p.setFromPoints(m,r);const s=l[2],a=o[2];s.subVectors(t,i),a.setFromPoints(s,r);const u=l[3],g=o[3];u.subVectors(i,e),g.setFromPoints(u,r),this.sphere.setFromPoints(this.points),this.plane.setFromNormalAndCoplanarPoint(c,e),this.needsUpdate=!1}}te.prototype.closestPointToSegment=function(){const n=new d.Vector3,e=new d.Vector3,t=new d.Line3;return function(r,l=null,o=null){const{start:c,end:h}=r,m=this.points;let p,s=1/0;for(let a=0;a<3;a++){const u=(a+1)%3;t.start.copy(m[a]),t.end.copy(m[u]),zi(t,r,n,e),p=n.distanceToSquared(e),p<s&&(s=p,l&&l.copy(n),o&&o.copy(e))}return this.closestPointToPoint(c,n),p=c.distanceToSquared(n),p<s&&(s=p,l&&l.copy(n),o&&o.copy(c)),this.closestPointToPoint(h,n),p=h.distanceToSquared(n),p<s&&(s=p,l&&l.copy(n),o&&o.copy(h)),Math.sqrt(s)}}();te.prototype.intersectsTriangle=function(){const n=new te,e=new Array(3),t=new Array(3),i=new ae,r=new ae,l=new d.Vector3,o=new d.Vector3,c=new d.Vector3,h=new d.Vector3,m=new d.Vector3,p=new d.Line3,s=new d.Line3,a=new d.Line3,u=new d.Vector3;function g(_,f,v){const y=_.points;let x=0,w=-1;for(let b=0;b<3;b++){const{start:C,end:T}=p;C.copy(y[b]),T.copy(y[(b+1)%3]),p.delta(o);const S=ri(f.distanceToPoint(C));if(ri(f.normal.dot(o))&&S){v.copy(p),x=2;break}const A=f.intersectLine(p,u);if(!A&&S&&u.copy(C),(A||S)&&!ri(u.distanceTo(T))){if(x<=1)(x===1?v.start:v.end).copy(u),S&&(w=x);else if(x>=2){(w===1?v.start:v.end).copy(u),x=2;break}if(x++,x===2&&w===-1)break}}return x}return function(f,v=null,y=!1){this.needsUpdate&&this.update(),f.isExtendedTriangle?f.needsUpdate&&f.update():(n.copy(f),n.update(),f=n);const x=this.plane,w=f.plane;if(Math.abs(x.normal.dot(w.normal))>1-1e-10){const b=this.satBounds,C=this.satAxes;t[0]=f.a,t[1]=f.b,t[2]=f.c;for(let A=0;A<4;A++){const P=b[A],I=C[A];if(i.setFromPoints(I,t),P.isSeparated(i))return!1}const T=f.satBounds,S=f.satAxes;e[0]=this.a,e[1]=this.b,e[2]=this.c;for(let A=0;A<4;A++){const P=T[A],I=S[A];if(i.setFromPoints(I,e),P.isSeparated(i))return!1}for(let A=0;A<4;A++){const P=C[A];for(let I=0;I<4;I++){const M=S[I];if(l.crossVectors(P,M),i.setFromPoints(l,e),r.setFromPoints(l,t),i.isSeparated(r))return!1}}return v&&(y||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),v.start.set(0,0,0),v.end.set(0,0,0)),!0}else{const b=g(this,w,s);if(b===1&&f.containsPoint(s.end))return v&&(v.start.copy(s.end),v.end.copy(s.end)),!0;if(b!==2)return!1;const C=g(f,x,a);if(C===1&&this.containsPoint(a.end))return v&&(v.start.copy(a.end),v.end.copy(a.end)),!0;if(C!==2)return!1;if(s.delta(c),a.delta(h),c.dot(h)<0){let R=a.start;a.start=a.end,a.end=R}const T=s.start.dot(c),S=s.end.dot(c),A=a.start.dot(c),P=a.end.dot(c),I=S<A,M=T<P;return T!==P&&A!==S&&I===M?!1:(v&&(m.subVectors(s.start,a.start),m.dot(c)>0?v.start.copy(s.start):v.start.copy(a.start),m.subVectors(s.end,a.end),m.dot(c)<0?v.end.copy(s.end):v.end.copy(a.end)),!0)}}}();te.prototype.distanceToPoint=function(){const n=new d.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}}();te.prototype.distanceToTriangle=function(){const n=new d.Vector3,e=new d.Vector3,t=["a","b","c"],i=new d.Line3,r=new d.Line3;return function(o,c=null,h=null){const m=c||h?i:null;if(this.intersectsTriangle(o,m))return(c||h)&&(c&&m.getCenter(c),h&&m.getCenter(h)),0;let p=1/0;for(let s=0;s<3;s++){let a;const u=t[s],g=o[u];this.closestPointToPoint(g,n),a=g.distanceToSquared(n),a<p&&(p=a,c&&c.copy(n),h&&h.copy(g));const _=this[u];o.closestPointToPoint(_,n),a=_.distanceToSquared(n),a<p&&(p=a,c&&c.copy(_),h&&h.copy(n))}for(let s=0;s<3;s++){const a=t[s],u=t[(s+1)%3];i.set(this[a],this[u]);for(let g=0;g<3;g++){const _=t[g],f=t[(g+1)%3];r.set(o[_],o[f]),zi(i,r,n,e);const v=n.distanceToSquared(e);v<p&&(p=v,c&&c.copy(n),h&&h.copy(e))}}return Math.sqrt(p)}}();class W{constructor(e,t,i){this.isOrientedBox=!0,this.min=new d.Vector3,this.max=new d.Vector3,this.matrix=new d.Matrix4,this.invMatrix=new d.Matrix4,this.points=new Array(8).fill().map(()=>new d.Vector3),this.satAxes=new Array(3).fill().map(()=>new d.Vector3),this.satBounds=new Array(3).fill().map(()=>new ae),this.alignedSatBounds=new Array(3).fill().map(()=>new ae),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}W.prototype.update=function(){return function(){const e=this.matrix,t=this.min,i=this.max,r=this.points;for(let m=0;m<=1;m++)for(let p=0;p<=1;p++)for(let s=0;s<=1;s++){const a=1*m|2*p|4*s,u=r[a];u.x=m?i.x:t.x,u.y=p?i.y:t.y,u.z=s?i.z:t.z,u.applyMatrix4(e)}const l=this.satBounds,o=this.satAxes,c=r[0];for(let m=0;m<3;m++){const p=o[m],s=l[m],a=1<<m,u=r[a];p.subVectors(c,u),s.setFromPoints(p,r)}const h=this.alignedSatBounds;h[0].setFromPointsField(r,"x"),h[1].setFromPointsField(r,"y"),h[2].setFromPointsField(r,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}();W.prototype.intersectsBox=function(){const n=new ae;return function(t){this.needsUpdate&&this.update();const i=t.min,r=t.max,l=this.satBounds,o=this.satAxes,c=this.alignedSatBounds;if(n.min=i.x,n.max=r.x,c[0].isSeparated(n)||(n.min=i.y,n.max=r.y,c[1].isSeparated(n))||(n.min=i.z,n.max=r.z,c[2].isSeparated(n)))return!1;for(let h=0;h<3;h++){const m=o[h],p=l[h];if(n.setFromBox(m,t),p.isSeparated(n))return!1}return!0}}();W.prototype.intersectsTriangle=function(){const n=new te,e=new Array(3),t=new ae,i=new ae,r=new d.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(n.copy(o),n.update(),o=n);const c=this.satBounds,h=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let a=0;a<3;a++){const u=c[a],g=h[a];if(t.setFromPoints(g,e),u.isSeparated(t))return!1}const m=o.satBounds,p=o.satAxes,s=this.points;for(let a=0;a<3;a++){const u=m[a],g=p[a];if(t.setFromPoints(g,s),u.isSeparated(t))return!1}for(let a=0;a<3;a++){const u=h[a];for(let g=0;g<4;g++){const _=p[g];if(r.crossVectors(u,_),t.setFromPoints(r,e),i.setFromPoints(r,s),t.isSeparated(i))return!1}}return!0}}();W.prototype.closestPointToPoint=function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}}();W.prototype.distanceToPoint=function(){const n=new d.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}}();W.prototype.distanceToBox=function(){const n=["x","y","z"],e=new Array(12).fill().map(()=>new d.Line3),t=new Array(12).fill().map(()=>new d.Line3),i=new d.Vector3,r=new d.Vector3;return function(o,c=0,h=null,m=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(h||m)&&(o.getCenter(r),this.closestPointToPoint(r,i),o.closestPointToPoint(i,r),h&&h.copy(i),m&&m.copy(r)),0;const p=c*c,s=o.min,a=o.max,u=this.points;let g=1/0;for(let f=0;f<8;f++){const v=u[f];r.copy(v).clamp(s,a);const y=v.distanceToSquared(r);if(y<g&&(g=y,h&&h.copy(v),m&&m.copy(r),y<p))return Math.sqrt(y)}let _=0;for(let f=0;f<3;f++)for(let v=0;v<=1;v++)for(let y=0;y<=1;y++){const x=(f+1)%3,w=(f+2)%3,b=v<<x|y<<w,C=1<<f|v<<x|y<<w,T=u[b],S=u[C];e[_].set(T,S);const P=n[f],I=n[x],M=n[w],R=t[_],E=R.start,F=R.end;E[P]=s[P],E[I]=v?s[I]:a[I],E[M]=y?s[M]:a[I],F[P]=a[P],F[I]=v?s[I]:a[I],F[M]=y?s[M]:a[I],_++}for(let f=0;f<=1;f++)for(let v=0;v<=1;v++)for(let y=0;y<=1;y++){r.x=f?a.x:s.x,r.y=v?a.y:s.y,r.z=y?a.z:s.z,this.closestPointToPoint(r,i);const x=r.distanceToSquared(i);if(x<g&&(g=x,h&&h.copy(i),m&&m.copy(r),x<p))return Math.sqrt(x)}for(let f=0;f<12;f++){const v=e[f];for(let y=0;y<12;y++){const x=t[y];zi(v,x,i,r);const w=i.distanceToSquared(r);if(w<g&&(g=w,h&&h.copy(i),m&&m.copy(r),w<p))return Math.sqrt(w)}}return Math.sqrt(g)}}();class Vi{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Ba extends Vi{constructor(){super(()=>new te)}}const K=new Ba;class La{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const k=new La;let fe,He;const Pe=[],xt=new Vi(()=>new d.Box3);function ka(n,e,t,i,r,l){fe=xt.getPrimitive(),He=xt.getPrimitive(),Pe.push(fe,He),k.setBuffer(n._roots[e]);const o=xi(0,n.geometry,t,i,r,l);k.clearBuffer(),xt.releasePrimitive(fe),xt.releasePrimitive(He),Pe.pop(),Pe.pop();const c=Pe.length;return c>0&&(He=Pe[c-1],fe=Pe[c-2]),o}function xi(n,e,t,i,r=null,l=0,o=0){const{float32Array:c,uint16Array:h,uint32Array:m}=k;let p=n*2;if(q(p,h)){const a=Q(n,m),u=Z(p,h);return O(n,c,fe),i(a,u,!1,o,l+n,fe)}else{let P=function(M){const{uint16Array:R,uint32Array:E}=k;let F=M*2;for(;!q(F,R);)M=X(M),F=M*2;return Q(M,E)},I=function(M){const{uint16Array:R,uint32Array:E}=k;let F=M*2;for(;!q(F,R);)M=J(M,E),F=M*2;return Q(M,E)+Z(F,R)};const a=X(n),u=J(n,m);let g=a,_=u,f,v,y,x;if(r&&(y=fe,x=He,O(g,c,y),O(_,c,x),f=r(y),v=r(x),v<f)){g=u,_=a;const M=f;f=v,v=M,y=x}y||(y=fe,O(g,c,y));const w=q(g*2,h),b=t(y,w,f,o+1,l+g);let C;if(b===As){const M=P(g),E=I(g)-M;C=i(M,E,!0,o+1,l+g,y)}else C=b&&xi(g,e,t,i,r,l,o+1);if(C)return!0;x=He,O(_,c,x);const T=q(_*2,h),S=t(x,T,v,o+1,l+_);let A;if(S===As){const M=P(_),E=I(_)-M;A=i(M,E,!0,o+1,l+_,x)}else A=S&&xi(_,e,t,i,r,l,o+1);return!!A}}const $e=new d.Vector3,ni=new d.Vector3;function Oa(n,e,t={},i=0,r=1/0){const l=i*i,o=r*r;let c=1/0,h=null;if(n.shapecast({boundsTraverseOrder:p=>($e.copy(e).clamp(p.min,p.max),$e.distanceToSquared(e)),intersectsBounds:(p,s,a)=>a<c&&a<o,intersectsTriangle:(p,s)=>{p.closestPointToPoint(e,$e);const a=e.distanceToSquared($e);return a<c&&(ni.copy($e),c=a,h=s),a<l}}),c===1/0)return null;const m=Math.sqrt(c);return t.point?t.point.copy(ni):t.point=ni.clone(),t.distance=m,t.faceIndex=h,t}const Re=new d.Vector3,Ie=new d.Vector3,Ee=new d.Vector3,wt=new d.Vector2,bt=new d.Vector2,At=new d.Vector2,Ps=new d.Vector3,Rs=new d.Vector3,Is=new d.Vector3,Tt=new d.Vector3;function za(n,e,t,i,r,l,o,c){let h;if(l===d.BackSide?h=n.intersectTriangle(i,t,e,!0,r):h=n.intersectTriangle(e,t,i,l!==d.DoubleSide,r),h===null)return null;const m=n.origin.distanceTo(r);return m<o||m>c?null:{distance:m,point:r.clone()}}function Va(n,e,t,i,r,l,o,c,h,m,p){Re.fromBufferAttribute(e,l),Ie.fromBufferAttribute(e,o),Ee.fromBufferAttribute(e,c);const s=za(n,Re,Ie,Ee,Tt,h,m,p);if(s){i&&(wt.fromBufferAttribute(i,l),bt.fromBufferAttribute(i,o),At.fromBufferAttribute(i,c),s.uv=d.Triangle.getInterpolation(Tt,Re,Ie,Ee,wt,bt,At,new d.Vector2)),r&&(wt.fromBufferAttribute(r,l),bt.fromBufferAttribute(r,o),At.fromBufferAttribute(r,c),s.uv1=d.Triangle.getInterpolation(Tt,Re,Ie,Ee,wt,bt,At,new d.Vector2)),t&&(Ps.fromBufferAttribute(t,l),Rs.fromBufferAttribute(t,o),Is.fromBufferAttribute(t,c),s.normal=d.Triangle.getInterpolation(Tt,Re,Ie,Ee,Ps,Rs,Is,new d.Vector3),s.normal.dot(n.direction)>0&&s.normal.multiplyScalar(-1));const a={a:l,b:o,c,normal:new d.Vector3,materialIndex:0};d.Triangle.getNormal(Re,Ie,Ee,a.normal),s.face=a,s.faceIndex=l}return s}function Gt(n,e,t,i,r,l,o){const c=i*3;let h=c+0,m=c+1,p=c+2;const s=n.index;n.index&&(h=s.getX(h),m=s.getX(m),p=s.getX(p));const{position:a,normal:u,uv:g,uv1:_}=n.attributes,f=Va(t,a,u,g,_,h,m,p,e,l,o);return f?(f.faceIndex=i,r&&r.push(f),f):null}function U(n,e,t,i){const r=n.a,l=n.b,o=n.c;let c=e,h=e+1,m=e+2;t&&(c=t.getX(c),h=t.getX(h),m=t.getX(m)),r.x=i.getX(c),r.y=i.getY(c),r.z=i.getZ(c),l.x=i.getX(h),l.y=i.getY(h),l.z=i.getZ(h),o.x=i.getX(m),o.y=i.getY(m),o.z=i.getZ(m)}function Ua(n,e,t,i,r,l,o,c){const{geometry:h,_indirectBuffer:m}=n;for(let p=i,s=i+r;p<s;p++)Gt(h,e,t,p,l,o,c)}function Ha(n,e,t,i,r,l,o){const{geometry:c,_indirectBuffer:h}=n;let m=1/0,p=null;for(let s=i,a=i+r;s<a;s++){let u;u=Gt(c,e,t,s,null,l,o),u&&u.distance<m&&(p=u,m=u.distance)}return p}function Na(n,e,t,i,r,l,o){const{geometry:c}=t,{index:h}=c,m=c.attributes.position;for(let p=n,s=e+n;p<s;p++){let a;if(a=p,U(o,a*3,h,m),o.needsUpdate=!0,i(o,a,r,l))return!0}return!1}function Wa(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,r=t.attributes.position;let l,o,c,h,m=0;const p=n._roots;for(let a=0,u=p.length;a<u;a++)l=p[a],o=new Uint32Array(l),c=new Uint16Array(l),h=new Float32Array(l),s(0,m),m+=l.byteLength;function s(a,u,g=!1){const _=a*2;if(c[_+15]===Wt){const v=o[a+6],y=c[_+14];let x=1/0,w=1/0,b=1/0,C=-1/0,T=-1/0,S=-1/0;for(let A=3*v,P=3*(v+y);A<P;A++){let I=i[A];const M=r.getX(I),R=r.getY(I),E=r.getZ(I);M<x&&(x=M),M>C&&(C=M),R<w&&(w=R),R>T&&(T=R),E<b&&(b=E),E>S&&(S=E)}return h[a+0]!==x||h[a+1]!==w||h[a+2]!==b||h[a+3]!==C||h[a+4]!==T||h[a+5]!==S?(h[a+0]=x,h[a+1]=w,h[a+2]=b,h[a+3]=C,h[a+4]=T,h[a+5]=S,!0):!1}else{const v=a+8,y=o[a+6],x=v+u,w=y+u;let b=g,C=!1,T=!1;e?b||(C=e.has(x),T=e.has(w),b=!C&&!T):(C=!0,T=!0);const S=b||C,A=b||T;let P=!1;S&&(P=s(v,u,b));let I=!1;A&&(I=s(y,u,b));const M=P||I;if(M)for(let R=0;R<3;R++){const E=v+R,F=y+R,D=h[E],L=h[E+3],V=h[F],z=h[F+3];h[a+R]=D<V?D:V,h[a+R+3]=L>z?L:z}return M}}}function pe(n,e,t,i,r){let l,o,c,h,m,p;const s=1/t.direction.x,a=1/t.direction.y,u=1/t.direction.z,g=t.origin.x,_=t.origin.y,f=t.origin.z;let v=e[n],y=e[n+3],x=e[n+1],w=e[n+3+1],b=e[n+2],C=e[n+3+2];return s>=0?(l=(v-g)*s,o=(y-g)*s):(l=(y-g)*s,o=(v-g)*s),a>=0?(c=(x-_)*a,h=(w-_)*a):(c=(w-_)*a,h=(x-_)*a),l>h||c>o||((c>l||isNaN(l))&&(l=c),(h<o||isNaN(o))&&(o=h),u>=0?(m=(b-f)*u,p=(C-f)*u):(m=(C-f)*u,p=(b-f)*u),l>p||m>o)?!1:((m>l||l!==l)&&(l=m),(p<o||o!==o)&&(o=p),l<=r&&o>=i)}function Ga(n,e,t,i,r,l,o,c){const{geometry:h,_indirectBuffer:m}=n;for(let p=i,s=i+r;p<s;p++){let a=m?m[p]:p;Gt(h,e,t,a,l,o,c)}}function ja(n,e,t,i,r,l,o){const{geometry:c,_indirectBuffer:h}=n;let m=1/0,p=null;for(let s=i,a=i+r;s<a;s++){let u;u=Gt(c,e,t,h?h[s]:s,null,l,o),u&&u.distance<m&&(p=u,m=u.distance)}return p}function qa(n,e,t,i,r,l,o){const{geometry:c}=t,{index:h}=c,m=c.attributes.position;for(let p=n,s=e+n;p<s;p++){let a;if(a=t.resolveTriangleIndex(p),U(o,a*3,h,m),o.needsUpdate=!0,i(o,a,r,l))return!0}return!1}function Ya(n,e,t,i,r,l,o){k.setBuffer(n._roots[e]),wi(0,n,t,i,r,l,o),k.clearBuffer()}function wi(n,e,t,i,r,l,o){const{float32Array:c,uint16Array:h,uint32Array:m}=k,p=n*2;if(q(p,h)){const a=Q(n,m),u=Z(p,h);Ua(e,t,i,a,u,r,l,o)}else{const a=X(n);pe(a,c,i,l,o)&&wi(a,e,t,i,r,l,o);const u=J(n,m);pe(u,c,i,l,o)&&wi(u,e,t,i,r,l,o)}}const Qa=["x","y","z"];function Za(n,e,t,i,r,l){k.setBuffer(n._roots[e]);const o=bi(0,n,t,i,r,l);return k.clearBuffer(),o}function bi(n,e,t,i,r,l){const{float32Array:o,uint16Array:c,uint32Array:h}=k;let m=n*2;if(q(m,c)){const s=Q(n,h),a=Z(m,c);return Ha(e,t,i,s,a,r,l)}else{const s=rr(n,h),a=Qa[s],g=i.direction[a]>=0;let _,f;g?(_=X(n),f=J(n,h)):(_=J(n,h),f=X(n));const y=pe(_,o,i,r,l)?bi(_,e,t,i,r,l):null;if(y){const b=y.point[a];if(g?b<=o[f+s]:b>=o[f+s+3])return y}const w=pe(f,o,i,r,l)?bi(f,e,t,i,r,l):null;return y&&w?y.distance<=w.distance?y:w:y||w||null}}const St=new d.Box3,Fe=new te,De=new te,et=new d.Matrix4,Es=new W,Ct=new W;function Xa(n,e,t,i){k.setBuffer(n._roots[e]);const r=Ai(0,n,t,i);return k.clearBuffer(),r}function Ai(n,e,t,i,r=null){const{float32Array:l,uint16Array:o,uint32Array:c}=k;let h=n*2;if(r===null&&(t.boundingBox||t.computeBoundingBox(),Es.set(t.boundingBox.min,t.boundingBox.max,i),r=Es),q(h,o)){const p=e.geometry,s=p.index,a=p.attributes.position,u=t.index,g=t.attributes.position,_=Q(n,c),f=Z(h,o);if(et.copy(i).invert(),t.boundsTree)return O(n,l,Ct),Ct.matrix.copy(et),Ct.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:y=>Ct.intersectsBox(y),intersectsTriangle:y=>{y.a.applyMatrix4(i),y.b.applyMatrix4(i),y.c.applyMatrix4(i),y.needsUpdate=!0;for(let x=_*3,w=(f+_)*3;x<w;x+=3)if(U(De,x,s,a),De.needsUpdate=!0,y.intersectsTriangle(De))return!0;return!1}});for(let v=_*3,y=(f+_)*3;v<y;v+=3){U(Fe,v,s,a),Fe.a.applyMatrix4(et),Fe.b.applyMatrix4(et),Fe.c.applyMatrix4(et),Fe.needsUpdate=!0;for(let x=0,w=u.count;x<w;x+=3)if(U(De,x,u,g),De.needsUpdate=!0,Fe.intersectsTriangle(De))return!0}}else{const p=n+8,s=c[n+6];return O(p,l,St),!!(r.intersectsBox(St)&&Ai(p,e,t,i,r)||(O(s,l,St),r.intersectsBox(St)&&Ai(s,e,t,i,r)))}}const Mt=new d.Matrix4,oi=new W,it=new W,Ja=new d.Vector3,Ka=new d.Vector3,$a=new d.Vector3,el=new d.Vector3;function tl(n,e,t,i={},r={},l=0,o=1/0){e.boundingBox||e.computeBoundingBox(),oi.set(e.boundingBox.min,e.boundingBox.max,t),oi.needsUpdate=!0;const c=n.geometry,h=c.attributes.position,m=c.index,p=e.attributes.position,s=e.index,a=K.getPrimitive(),u=K.getPrimitive();let g=Ja,_=Ka,f=null,v=null;r&&(f=$a,v=el);let y=1/0,x=null,w=null;return Mt.copy(t).invert(),it.matrix.copy(Mt),n.shapecast({boundsTraverseOrder:b=>oi.distanceToBox(b),intersectsBounds:(b,C,T)=>T<y&&T<o?(C&&(it.min.copy(b.min),it.max.copy(b.max),it.needsUpdate=!0),!0):!1,intersectsRange:(b,C)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:S=>it.distanceToBox(S),intersectsBounds:(S,A,P)=>P<y&&P<o,intersectsRange:(S,A)=>{for(let P=S,I=S+A;P<I;P++){U(u,3*P,s,p),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let M=b,R=b+C;M<R;M++){U(a,3*M,m,h),a.needsUpdate=!0;const E=a.distanceToTriangle(u,g,f);if(E<y&&(_.copy(g),v&&v.copy(f),y=E,x=M,w=P),E<l)return!0}}}});{const T=qe(e);for(let S=0,A=T;S<A;S++){U(u,3*S,s,p),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let P=b,I=b+C;P<I;P++){U(a,3*P,m,h),a.needsUpdate=!0;const M=a.distanceToTriangle(u,g,f);if(M<y&&(_.copy(g),v&&v.copy(f),y=M,x=P,w=S),M<l)return!0}}}}}),K.releasePrimitive(a),K.releasePrimitive(u),y===1/0?null:(i.point?i.point.copy(_):i.point=_.clone(),i.distance=y,i.faceIndex=x,r&&(r.point?r.point.copy(v):r.point=v.clone(),r.point.applyMatrix4(Mt),_.applyMatrix4(Mt),r.distance=_.sub(r.point).length(),r.faceIndex=w),i)}function il(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,r=t.attributes.position;let l,o,c,h,m=0;const p=n._roots;for(let a=0,u=p.length;a<u;a++)l=p[a],o=new Uint32Array(l),c=new Uint16Array(l),h=new Float32Array(l),s(0,m),m+=l.byteLength;function s(a,u,g=!1){const _=a*2;if(c[_+15]===Wt){const v=o[a+6],y=c[_+14];let x=1/0,w=1/0,b=1/0,C=-1/0,T=-1/0,S=-1/0;for(let A=v,P=v+y;A<P;A++){const I=3*n.resolveTriangleIndex(A);for(let M=0;M<3;M++){let R=I+M;R=i?i[R]:R;const E=r.getX(R),F=r.getY(R),D=r.getZ(R);E<x&&(x=E),E>C&&(C=E),F<w&&(w=F),F>T&&(T=F),D<b&&(b=D),D>S&&(S=D)}}return h[a+0]!==x||h[a+1]!==w||h[a+2]!==b||h[a+3]!==C||h[a+4]!==T||h[a+5]!==S?(h[a+0]=x,h[a+1]=w,h[a+2]=b,h[a+3]=C,h[a+4]=T,h[a+5]=S,!0):!1}else{const v=a+8,y=o[a+6],x=v+u,w=y+u;let b=g,C=!1,T=!1;e?b||(C=e.has(x),T=e.has(w),b=!C&&!T):(C=!0,T=!0);const S=b||C,A=b||T;let P=!1;S&&(P=s(v,u,b));let I=!1;A&&(I=s(y,u,b));const M=P||I;if(M)for(let R=0;R<3;R++){const E=v+R,F=y+R,D=h[E],L=h[E+3],V=h[F],z=h[F+3];h[a+R]=D<V?D:V,h[a+R+3]=L>z?L:z}return M}}}function sl(n,e,t,i,r,l,o){k.setBuffer(n._roots[e]),Ti(0,n,t,i,r,l,o),k.clearBuffer()}function Ti(n,e,t,i,r,l,o){const{float32Array:c,uint16Array:h,uint32Array:m}=k,p=n*2;if(q(p,h)){const a=Q(n,m),u=Z(p,h);Ga(e,t,i,a,u,r,l,o)}else{const a=X(n);pe(a,c,i,l,o)&&Ti(a,e,t,i,r,l,o);const u=J(n,m);pe(u,c,i,l,o)&&Ti(u,e,t,i,r,l,o)}}const rl=["x","y","z"];function nl(n,e,t,i,r,l){k.setBuffer(n._roots[e]);const o=Si(0,n,t,i,r,l);return k.clearBuffer(),o}function Si(n,e,t,i,r,l){const{float32Array:o,uint16Array:c,uint32Array:h}=k;let m=n*2;if(q(m,c)){const s=Q(n,h),a=Z(m,c);return ja(e,t,i,s,a,r,l)}else{const s=rr(n,h),a=rl[s],g=i.direction[a]>=0;let _,f;g?(_=X(n),f=J(n,h)):(_=J(n,h),f=X(n));const y=pe(_,o,i,r,l)?Si(_,e,t,i,r,l):null;if(y){const b=y.point[a];if(g?b<=o[f+s]:b>=o[f+s+3])return y}const w=pe(f,o,i,r,l)?Si(f,e,t,i,r,l):null;return y&&w?y.distance<=w.distance?y:w:y||w||null}}const Pt=new d.Box3,Be=new te,Le=new te,st=new d.Matrix4,Fs=new W,Rt=new W;function ol(n,e,t,i){k.setBuffer(n._roots[e]);const r=Ci(0,n,t,i);return k.clearBuffer(),r}function Ci(n,e,t,i,r=null){const{float32Array:l,uint16Array:o,uint32Array:c}=k;let h=n*2;if(r===null&&(t.boundingBox||t.computeBoundingBox(),Fs.set(t.boundingBox.min,t.boundingBox.max,i),r=Fs),q(h,o)){const p=e.geometry,s=p.index,a=p.attributes.position,u=t.index,g=t.attributes.position,_=Q(n,c),f=Z(h,o);if(st.copy(i).invert(),t.boundsTree)return O(n,l,Rt),Rt.matrix.copy(st),Rt.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:y=>Rt.intersectsBox(y),intersectsTriangle:y=>{y.a.applyMatrix4(i),y.b.applyMatrix4(i),y.c.applyMatrix4(i),y.needsUpdate=!0;for(let x=_,w=f+_;x<w;x++)if(U(Le,3*e.resolveTriangleIndex(x),s,a),Le.needsUpdate=!0,y.intersectsTriangle(Le))return!0;return!1}});for(let v=_,y=f+_;v<y;v++){const x=e.resolveTriangleIndex(v);U(Be,3*x,s,a),Be.a.applyMatrix4(st),Be.b.applyMatrix4(st),Be.c.applyMatrix4(st),Be.needsUpdate=!0;for(let w=0,b=u.count;w<b;w+=3)if(U(Le,w,u,g),Le.needsUpdate=!0,Be.intersectsTriangle(Le))return!0}}else{const p=n+8,s=c[n+6];return O(p,l,Pt),!!(r.intersectsBox(Pt)&&Ci(p,e,t,i,r)||(O(s,l,Pt),r.intersectsBox(Pt)&&Ci(s,e,t,i,r)))}}const It=new d.Matrix4,ai=new W,rt=new W,al=new d.Vector3,ll=new d.Vector3,cl=new d.Vector3,hl=new d.Vector3;function ul(n,e,t,i={},r={},l=0,o=1/0){e.boundingBox||e.computeBoundingBox(),ai.set(e.boundingBox.min,e.boundingBox.max,t),ai.needsUpdate=!0;const c=n.geometry,h=c.attributes.position,m=c.index,p=e.attributes.position,s=e.index,a=K.getPrimitive(),u=K.getPrimitive();let g=al,_=ll,f=null,v=null;r&&(f=cl,v=hl);let y=1/0,x=null,w=null;return It.copy(t).invert(),rt.matrix.copy(It),n.shapecast({boundsTraverseOrder:b=>ai.distanceToBox(b),intersectsBounds:(b,C,T)=>T<y&&T<o?(C&&(rt.min.copy(b.min),rt.max.copy(b.max),rt.needsUpdate=!0),!0):!1,intersectsRange:(b,C)=>{if(e.boundsTree){const T=e.boundsTree;return T.shapecast({boundsTraverseOrder:S=>rt.distanceToBox(S),intersectsBounds:(S,A,P)=>P<y&&P<o,intersectsRange:(S,A)=>{for(let P=S,I=S+A;P<I;P++){const M=T.resolveTriangleIndex(P);U(u,3*M,s,p),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let R=b,E=b+C;R<E;R++){const F=n.resolveTriangleIndex(R);U(a,3*F,m,h),a.needsUpdate=!0;const D=a.distanceToTriangle(u,g,f);if(D<y&&(_.copy(g),v&&v.copy(f),y=D,x=R,w=P),D<l)return!0}}}})}else{const T=qe(e);for(let S=0,A=T;S<A;S++){U(u,3*S,s,p),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let P=b,I=b+C;P<I;P++){const M=n.resolveTriangleIndex(P);U(a,3*M,m,h),a.needsUpdate=!0;const R=a.distanceToTriangle(u,g,f);if(R<y&&(_.copy(g),v&&v.copy(f),y=R,x=P,w=S),R<l)return!0}}}}}),K.releasePrimitive(a),K.releasePrimitive(u),y===1/0?null:(i.point?i.point.copy(_):i.point=_.clone(),i.distance=y,i.faceIndex=x,r&&(r.point?r.point.copy(v):r.point=v.clone(),r.point.applyMatrix4(It),_.applyMatrix4(It),r.distance=_.sub(r.point).length(),r.faceIndex=w),i)}function fl(){return typeof SharedArrayBuffer<"u"}const ht=new k.constructor,Ht=new k.constructor,he=new Vi(()=>new d.Box3),ke=new d.Box3,Oe=new d.Box3,li=new d.Box3,ci=new d.Box3;let hi=!1;function dl(n,e,t,i){if(hi)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");hi=!0;const r=n._roots,l=e._roots;let o,c=0,h=0;const m=new d.Matrix4().copy(t).invert();for(let p=0,s=r.length;p<s;p++){ht.setBuffer(r[p]),h=0;const a=he.getPrimitive();O(0,ht.float32Array,a),a.applyMatrix4(m);for(let u=0,g=l.length;u<g&&(Ht.setBuffer(l[p]),o=ee(0,0,t,m,i,c,h,0,0,a),Ht.clearBuffer(),h+=l[u].length,!o);u++);if(he.releasePrimitive(a),ht.clearBuffer(),c+=r[p].length,o)break}return hi=!1,o}function ee(n,e,t,i,r,l=0,o=0,c=0,h=0,m=null,p=!1){let s,a;p?(s=Ht,a=ht):(s=ht,a=Ht);const u=s.float32Array,g=s.uint32Array,_=s.uint16Array,f=a.float32Array,v=a.uint32Array,y=a.uint16Array,x=n*2,w=e*2,b=q(x,_),C=q(w,y);let T=!1;if(C&&b)p?T=r(Q(e,v),Z(e*2,y),Q(n,g),Z(n*2,_),h,o+e,c,l+n):T=r(Q(n,g),Z(n*2,_),Q(e,v),Z(e*2,y),c,l+n,h,o+e);else if(C){const S=he.getPrimitive();O(e,f,S),S.applyMatrix4(t);const A=X(n),P=J(n,g);O(A,u,ke),O(P,u,Oe);const I=S.intersectsBox(ke),M=S.intersectsBox(Oe);T=I&&ee(e,A,i,t,r,o,l,h,c+1,S,!p)||M&&ee(e,P,i,t,r,o,l,h,c+1,S,!p),he.releasePrimitive(S)}else{const S=X(e),A=J(e,v);O(S,f,li),O(A,f,ci);const P=m.intersectsBox(li),I=m.intersectsBox(ci);if(P&&I)T=ee(n,S,t,i,r,l,o,c,h+1,m,p)||ee(n,A,t,i,r,l,o,c,h+1,m,p);else if(P)if(b)T=ee(n,S,t,i,r,l,o,c,h+1,m,p);else{const M=he.getPrimitive();M.copy(li).applyMatrix4(t);const R=X(n),E=J(n,g);O(R,u,ke),O(E,u,Oe);const F=M.intersectsBox(ke),D=M.intersectsBox(Oe);T=F&&ee(S,R,i,t,r,o,l,h,c+1,M,!p)||D&&ee(S,E,i,t,r,o,l,h,c+1,M,!p),he.releasePrimitive(M)}else if(I)if(b)T=ee(n,A,t,i,r,l,o,c,h+1,m,p);else{const M=he.getPrimitive();M.copy(ci).applyMatrix4(t);const R=X(n),E=J(n,g);O(R,u,ke),O(E,u,Oe);const F=M.intersectsBox(ke),D=M.intersectsBox(Oe);T=F&&ee(A,R,i,t,r,o,l,h,c+1,M,!p)||D&&ee(A,E,i,t,r,o,l,h,c+1,M,!p),he.releasePrimitive(M)}}return T}const Et=new W,Ds=new d.Box3,pl={strategy:tr,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0};class Ui{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,r=e._roots,l=e._indirectBuffer,o=i.getIndex();let c;return t.cloneBuffers?c={roots:r.map(h=>h.slice()),index:o?o.array.slice():null,indirectBuffer:l?l.slice():null}:c={roots:r,index:o?o.array:null,indirectBuffer:l},c}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:r,roots:l,indirectBuffer:o}=e,c=new Ui(t,{...i,[ti]:!0});if(c._roots=l,c._indirectBuffer=o||null,i.setIndex){const h=t.getIndex();if(h===null){const m=new d.BufferAttribute(e.index,1,!1);t.setIndex(m)}else h.array!==r&&(h.array.set(r),h.needsUpdate=!0)}return c}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...pl,[ti]:!1},t),t.useSharedArrayBuffer&&!fl())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[ti]||(Ia(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new d.Box3))),this.resolveTriangleIndex=t.indirect?i=>this._indirectBuffer[i]:i=>i}refit(e=null){return(this.indirect?il:Wa)(this,e)}traverse(e,t=0){const i=this._roots[t],r=new Uint32Array(i),l=new Uint16Array(i);o(0);function o(c,h=0){const m=c*2,p=l[m+15]===Wt;if(p){const s=r[c+6],a=l[m+14];e(h,p,new Float32Array(i,c*4,6),s,a)}else{const s=c+ct/4,a=r[c+6],u=r[c+7];e(h,p,new Float32Array(i,c*4,6),u)||(o(s,h+1),o(a,h+1))}}}raycast(e,t=d.FrontSide,i=0,r=1/0){const l=this._roots,o=this.geometry,c=[],h=t.isMaterial,m=Array.isArray(t),p=o.groups,s=h?t.side:t,a=this.indirect?sl:Ya;for(let u=0,g=l.length;u<g;u++){const _=m?t[p[u].materialIndex].side:s,f=c.length;if(a(this,u,_,e,c,i,r),m){const v=p[u].materialIndex;for(let y=f,x=c.length;y<x;y++)c[y].face.materialIndex=v}}return c}raycastFirst(e,t=d.FrontSide,i=0,r=1/0){const l=this._roots,o=this.geometry,c=t.isMaterial,h=Array.isArray(t);let m=null;const p=o.groups,s=c?t.side:t,a=this.indirect?nl:Za;for(let u=0,g=l.length;u<g;u++){const _=h?t[p[u].materialIndex].side:s,f=a(this,u,_,e,i,r);f!=null&&(m==null||f.distance<m.distance)&&(m=f,h&&(f.face.materialIndex=p[u].materialIndex))}return m}intersectsGeometry(e,t){let i=!1;const r=this._roots,l=this.indirect?ol:Xa;for(let o=0,c=r.length;o<c&&(i=l(this,o,e,t),!i);o++);return i}shapecast(e){const t=K.getPrimitive(),i=this.indirect?qa:Na;let{boundsTraverseOrder:r,intersectsBounds:l,intersectsRange:o,intersectsTriangle:c}=e;if(o&&c){const s=o;o=(a,u,g,_,f)=>s(a,u,g,_,f)?!0:i(a,u,this,c,g,_,t)}else o||(c?o=(s,a,u,g)=>i(s,a,this,c,u,g,t):o=(s,a,u)=>u);let h=!1,m=0;const p=this._roots;for(let s=0,a=p.length;s<a;s++){const u=p[s];if(h=ka(this,s,l,o,r,m),h)break;m+=u.byteLength}return K.releasePrimitive(t),h}bvhcast(e,t,i){let{intersectsRanges:r,intersectsTriangles:l}=i;const o=K.getPrimitive(),c=this.geometry.index,h=this.geometry.attributes.position,m=this.indirect?g=>{const _=this.resolveTriangleIndex(g);U(o,_*3,c,h)}:g=>{U(o,g*3,c,h)},p=K.getPrimitive(),s=e.geometry.index,a=e.geometry.attributes.position,u=e.indirect?g=>{const _=e.resolveTriangleIndex(g);U(p,_*3,s,a)}:g=>{U(p,g*3,s,a)};if(l){const g=(_,f,v,y,x,w,b,C)=>{for(let T=v,S=v+y;T<S;T++){u(T),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let A=_,P=_+f;A<P;A++)if(m(A),o.needsUpdate=!0,l(o,p,A,T,x,w,b,C))return!0}return!1};if(r){const _=r;r=function(f,v,y,x,w,b,C,T){return _(f,v,y,x,w,b,C,T)?!0:g(f,v,y,x,w,b,C,T)}}else r=g}return dl(this,e,t,r)}intersectsBox(e,t){return Et.set(e.min,e.max,t),Et.needsUpdate=!0,this.shapecast({intersectsBounds:i=>Et.intersectsBox(i),intersectsTriangle:i=>Et.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},r={},l=0,o=1/0){return(this.indirect?ul:tl)(this,e,t,i,r,l,o)}closestPointToPoint(e,t={},i=0,r=1/0){return Oa(this,e,t,i,r)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(i=>{O(0,new Float32Array(i),Ds),e.union(Ds)}),e}}class ml{constructor(e){this.name="WorkerBase",this.running=!1,this.worker=e,this.worker.onerror=t=>{throw t.message?new Error(`${this.name}: Could not create Web Worker with error "${t.message}"`):new Error(`${this.name}: Could not create Web Worker.`)}}runTask(){}generate(...e){if(this.running)throw new Error("GenerateMeshBVHWorker: Already running job.");if(this.worker===null)throw new Error("GenerateMeshBVHWorker: Worker has been disposed.");this.running=!0;const t=this.runTask(this.worker,...e);return t.finally(()=>{this.running=!1}),t}dispose(){this.worker.terminate(),this.worker=null}}class gl extends ml{constructor(e){const t=new Worker(e||new URL("data:text/javascript;base64,aW1wb3J0IHsKCUJ1ZmZlckdlb21ldHJ5LAoJQnVmZmVyQXR0cmlidXRlLAp9IGZyb20gJ3RocmVlJzsKaW1wb3J0IHsgTWVzaEJWSCB9IGZyb20gJy4uL2NvcmUvTWVzaEJWSC5qcyc7Cgpvbm1lc3NhZ2UgPSAoIHsgZGF0YSB9ICkgPT4gewoKCWxldCBwcmV2VGltZSA9IHBlcmZvcm1hbmNlLm5vdygpOwoJZnVuY3Rpb24gb25Qcm9ncmVzc0NhbGxiYWNrKCBwcm9ncmVzcyApIHsKCgkJLy8gYWNjb3VudCBmb3IgZXJyb3IKCQlwcm9ncmVzcyA9IE1hdGgubWluKCBwcm9ncmVzcywgMSApOwoKCQljb25zdCBjdXJyVGltZSA9IHBlcmZvcm1hbmNlLm5vdygpOwoJCWlmICggY3VyclRpbWUgLSBwcmV2VGltZSA+PSAxMCAmJiBwcm9ncmVzcyAhPT0gMS4wICkgewoKCQkJcG9zdE1lc3NhZ2UoIHsKCgkJCQllcnJvcjogbnVsbCwKCQkJCXNlcmlhbGl6ZWQ6IG51bGwsCgkJCQlwb3NpdGlvbjogbnVsbCwKCQkJCXByb2dyZXNzLAoKCQkJfSApOwoJCQlwcmV2VGltZSA9IGN1cnJUaW1lOwoKCQl9CgoJfQoKCWNvbnN0IHsgaW5kZXgsIHBvc2l0aW9uLCBvcHRpb25zIH0gPSBkYXRhOwoJdHJ5IHsKCgkJY29uc3QgZ2VvbWV0cnkgPSBuZXcgQnVmZmVyR2VvbWV0cnkoKTsKCQlnZW9tZXRyeS5zZXRBdHRyaWJ1dGUoICdwb3NpdGlvbicsIG5ldyBCdWZmZXJBdHRyaWJ1dGUoIHBvc2l0aW9uLCAzLCBmYWxzZSApICk7CgkJaWYgKCBpbmRleCApIHsKCgkJCWdlb21ldHJ5LnNldEluZGV4KCBuZXcgQnVmZmVyQXR0cmlidXRlKCBpbmRleCwgMSwgZmFsc2UgKSApOwoKCQl9CgoJCWlmICggb3B0aW9ucy5pbmNsdWRlZFByb2dyZXNzQ2FsbGJhY2sgKSB7CgoJCQlvcHRpb25zLm9uUHJvZ3Jlc3MgPSBvblByb2dyZXNzQ2FsbGJhY2s7CgoJCX0KCgkJaWYgKCBvcHRpb25zLmdyb3VwcyApIHsKCgkJCWNvbnN0IGdyb3VwcyA9IG9wdGlvbnMuZ3JvdXBzOwoJCQlmb3IgKCBjb25zdCBpIGluIGdyb3VwcyApIHsKCgkJCQljb25zdCBncm91cCA9IGdyb3Vwc1sgaSBdOwoJCQkJZ2VvbWV0cnkuYWRkR3JvdXAoIGdyb3VwLnN0YXJ0LCBncm91cC5jb3VudCwgZ3JvdXAubWF0ZXJpYWxJbmRleCApOwoKCQkJfQoKCQl9CgoJCWNvbnN0IGJ2aCA9IG5ldyBNZXNoQlZIKCBnZW9tZXRyeSwgb3B0aW9ucyApOwoJCWNvbnN0IHNlcmlhbGl6ZWQgPSBNZXNoQlZILnNlcmlhbGl6ZSggYnZoLCB7IGNvcHlJbmRleEJ1ZmZlcjogZmFsc2UgfSApOwoJCWxldCB0b1RyYW5zZmVyID0gWyBwb3NpdGlvbi5idWZmZXIsIC4uLnNlcmlhbGl6ZWQucm9vdHMgXTsKCQlpZiAoIHNlcmlhbGl6ZWQuaW5kZXggKSB7CgoJCQl0b1RyYW5zZmVyLnB1c2goIHNlcmlhbGl6ZWQuaW5kZXguYnVmZmVyICk7CgoJCX0KCgkJdG9UcmFuc2ZlciA9IHRvVHJhbnNmZXIuZmlsdGVyKCB2ID0+ICggdHlwZW9mIFNoYXJlZEFycmF5QnVmZmVyID09PSAndW5kZWZpbmVkJyApIHx8ICEgKCB2IGluc3RhbmNlb2YgU2hhcmVkQXJyYXlCdWZmZXIgKSApOwoKCQlpZiAoIGJ2aC5faW5kaXJlY3RCdWZmZXIgKSB7CgoJCQl0b1RyYW5zZmVyLnB1c2goIHNlcmlhbGl6ZWQuaW5kaXJlY3RCdWZmZXIuYnVmZmVyICk7CgoJCX0KCgkJcG9zdE1lc3NhZ2UoIHsKCgkJCWVycm9yOiBudWxsLAoJCQlzZXJpYWxpemVkLAoJCQlwb3NpdGlvbiwKCQkJcHJvZ3Jlc3M6IDEsCgoJCX0sIHRvVHJhbnNmZXIgKTsKCgl9IGNhdGNoICggZXJyb3IgKSB7CgoJCXBvc3RNZXNzYWdlKCB7CgoJCQllcnJvciwKCQkJc2VyaWFsaXplZDogbnVsbCwKCQkJcG9zaXRpb246IG51bGwsCgkJCXByb2dyZXNzOiAxLAoKCQl9ICk7CgoJfQoKfTsK",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ot&&Ot.src||new URL("shop-components.cjs",document.baseURI).href),{type:"module"});super(t),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((r,l)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=m=>{l(new Error(`GenerateMeshBVHWorker: ${m.message}`))},e.onmessage=m=>{const{data:p}=m;if(p.error)l(new Error(p.error)),e.onmessage=null;else if(p.serialized){const{serialized:s,position:a}=p,u=Ui.deserialize(s,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=a,s.index)if(t.index)t.index.array=s.index;else{const _=new d.BufferAttribute(s.index,1,!1);t.setIndex(_)}g.setBoundingBox&&(t.boundingBox=u.getBoundingBox(new d.Box3)),i.onProgress&&i.onProgress(p.progress),r(u),e.onmessage=null}else i.onProgress&&i.onProgress(p.progress)};const o=t.index?t.index.array:null,c=t.attributes.position.array,h=[c];o&&h.push(o),e.postMessage({index:o,position:c,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},h.map(m=>m.buffer).filter(m=>typeof SharedArrayBuffer>"u"||!(m instanceof SharedArrayBuffer)))})}}class vl{constructor(e,t){this.lock=!1,this.lockX=!1,this.lockY=!1,this.invRotMat=new d.Matrix4,this.mouse=new d.Vector3,this.rotateStart=new d.Vector2,this.rotateEnd=new d.Vector2,this.rotateDelta=new d.Vector2,this.selectedAxis=null,this.isDragging=!1,this.context=null,this.orbitState=!0,this._animator=0,this._emitter=new je,this.addListener=this._emitter.addListener.bind(this._emitter),this.removeAllListeners=this._emitter.removeAllListeners.bind(this._emitter),this._text=document.createElement("div"),this._textTimer=0,this._update=()=>{this.lock||(this._textTimer&&(window.clearTimeout(this._textTimer),this._textTimer=0),this._textTimer=window.setTimeout(()=>{this._text.style.opacity="0"},800),this.camera.updateMatrix(),this.invRotMat.extractRotation(this.camera.matrix).invert(),this.axes.forEach(r=>{this.setAxisPosition(r)}),this.axes.sort((r,l)=>r.position.z>l.position.z?1:-1),this.drawLayers(!0),this._text.style.opacity="1",this._text.innerText=this.camera.position.distanceTo(this.orbit.target).toFixed(2)+" m")},this.updateMouseFromEvent=r=>{this.rect=this.domElement.getBoundingClientRect();const l=this.domElement.width/this.domElement.clientWidth,o=this.domElement.height/this.domElement.clientHeight,{left:c,top:h}=this.rect;this.mouse.set((r.clientX-c)*l,(r.clientY-h)*o,0)},this.updateSelectedAxisUnderMouse=()=>{this.selectedAxis=null,this.axes.forEach(r=>{this.mouse.distanceTo(r.position)<r.size&&(this.selectedAxis=r)})},this.onPointerDown=r=>{this.rotateStart.set(r.clientX,r.clientY),this.updateMouseFromEvent(r),this.updateSelectedAxisUnderMouse(),this.orbitState=this.orbit.enabled,this.orbit.enabled=!1,window.addEventListener("pointermove",this.onDrag,!1),window.addEventListener("pointerup",this.onPointerUp,!1)},this.onPointerUp=()=>{this.domElement.style.backgroundColor="#FFF0",setTimeout(()=>this.isDragging=!1,0),this.domElement.classList.remove("dragging"),this.orbit.enabled=this.orbitState,window.removeEventListener("pointermove",this.onDrag,!1),window.removeEventListener("pointerup",this.onPointerUp,!1)},this.onPointerEnter=()=>{this.domElement.style.backgroundColor="#FFF3",this.rect=this.domElement.getBoundingClientRect()},this.onPointerMove=r=>{if(this.lock||this.isDragging)return;const l=this.selectedAxis;r&&(this.updateMouseFromEvent(r),this.updateSelectedAxisUnderMouse()),l!==this.selectedAxis&&this.drawLayers()},this.onDrag=r=>{this.lock||(this.isDragging||this.domElement.classList.add("dragging"),this.isDragging=!0,this.selectedAxis=null,this.rotateEnd.set(r.clientX,r.clientY),this.rotateDelta.subVectors(this.rotateEnd,this.rotateStart).multiplyScalar(.5),this.rotateStart.copy(this.rotateEnd),this.orbit.update())},this.onMouseClick=r=>{if(this.lock||(this.updateMouseFromEvent(r),this.updateSelectedAxisUnderMouse(),this.isDragging||!this.selectedAxis))return;this._animator&&cancelAnimationFrame(this._animator);const l=this.selectedAxis.direction.clone();this.camera.lookAt(0,0,0);const o=this.camera.position.distanceTo(this.orbit.target);l.multiplyScalar(o),this.selectedAxis.axis==="z"?l.setZ(this.orbit.target.z+o):this.selectedAxis.axis==="-z"?l.setZ(this.orbit.target.z-o):l.setZ(this.orbit.target.z);const c=500,h=performance.now(),m=1,p=this.selectedAxis.axis,s=()=>{const u=performance.now()-h,g=Math.min(u/c,m);if(this.camera.position.lerp(l,g),this.orbit.update(),g!==m){this._animator=window.requestAnimationFrame(s);return}else this._animator=0,this.onPointerMove(void 0),this._emitter.emit("axis-select-end",p);this.onPointerMove(void 0)};this._emitter.emit("axis-select-start",p),s()},this.drawCircle=(r,l=10,o="#FF0000")=>{this.context&&(this.context.beginPath(),this.context.rect(r.x-l,r.y-l,l*2,l*2),this.context.fillStyle=o,this.context.fill(),this.context.closePath())},this.drawLine=(r,l,o=1,c="#FF0000")=>{this.context&&(this.context.beginPath(),this.context.moveTo(r.x,r.y),this.context.lineTo(l.x,l.y),this.context.lineWidth=o,this.context.strokeStyle=c,this.context.stroke(),this.context.closePath())},this.drawLayers=(r=!1)=>{this.context&&(r&&this.context.clearRect(0,0,this.domElement.width,this.domElement.height),this.axes.forEach(l=>{const o=this.selectedAxis===l,c=l.position.z>=-.01?l.color[0]:l.color[1];if(l.line&&this.drawLine(this.center,l.position,l.line,c),this.drawCircle(l.position,l.size,o?"#0066ff":c),l.label){const h=l.axis==="-x"?this.options.fontSize-3:this.options.fontSize;this.context.font=[this.options.fontWeight,h+"px",this.options.fontFamily].join(" "),this.context.fillStyle=this.options.fontColor,this.context.textBaseline="middle",this.context.textAlign="center",this.context.fillText(l.label,l.position.x,l.position.y)}}))},this.setAxisPosition=r=>{const l=r.direction.clone().applyMatrix4(this.invRotMat),o=r.size;r.position.set(l.x*(this.center.x-o/2-this.options.padding)+this.center.x,this.center.y-l.y*(this.center.y-o/2-this.options.padding),l.z)};const i={offset:new d.Vector2,size:90,padding:8,bubbleSizePrimary:8,bubbleSizeSecondary:6,lineWidth:2,fontSize:11,fontFamily:"arial",fontWeight:"normal",fontColor:"#fff",className:"orbit-controls-gizmo",colors:{x:["#f35f5f","#902525"],y:["#78da2f","#71ae45"],z:["#1d92fa","#d0d1d1"]}};this.options={...i,...t},this.orbit=e,this.camera=e.object,this.center=new d.Vector3(this.options.size/2,this.options.size/2,0),this.axes=this.createAxes(),this.domElement=this.createCanvas(this.options),this.orbit.addEventListener("change",this._update),this._text.style.cssText=`
|
|
3815
|
+
transition: all 0.8s ease-in-out;
|
|
3816
|
+
color: rgb(68, 78, 105);
|
|
3817
|
+
position: absolute;
|
|
3818
|
+
left: auto;
|
|
3819
|
+
right: ${this.options.offset.x+this.options.size/4}px;
|
|
3820
|
+
top: ${this.options.offset.y+this.options.size/2+2}px;
|
|
3821
|
+
width: ${this.options.size/2}px;
|
|
3822
|
+
margin-right: ${-this.options.size/4}px;
|
|
3823
|
+
font-size: 12px;
|
|
3824
|
+
text-align:center;
|
|
3825
|
+
`}appendTo(e){e.append(this.domElement),e.append(this._text)}createAxes(){const{colors:e,lineWidth:t,bubbleSizePrimary:i,bubbleSizeSecondary:r}=this.options;return[{axis:"x",direction:new d.Vector3(1,0,0),size:i,color:e.x,line:t,label:"前",position:new d.Vector3},{axis:"y",direction:new d.Vector3(0,1,0),size:i,color:e.y,line:t,label:"左",position:new d.Vector3},{axis:"z",direction:new d.Vector3(0,0,1),size:i,color:e.z,line:t,label:"上",position:new d.Vector3},{axis:"-x",direction:new d.Vector3(-1,0,0),size:r,color:e.x,label:"后",position:new d.Vector3},{axis:"-y",direction:new d.Vector3(0,-1,0),size:r,color:e.y,position:new d.Vector3,label:"右"},{axis:"-z",direction:new d.Vector3(0,0,-1),size:i,color:e.z,label:"下",position:new d.Vector3}]}createCanvas(e){const t=document.createElement("canvas");return t.width=e.size,t.height=e.size,t.classList.add(e.className),t.style.cssText=`
|
|
3826
|
+
position: absolute;
|
|
3827
|
+
left: auto;
|
|
3828
|
+
top: ${this.options.offset.y}px;
|
|
3829
|
+
right: ${this.options.offset.x}px;
|
|
3830
|
+
width: ${e.size/2}px;
|
|
3831
|
+
height: ${e.size/2}px;
|
|
3832
|
+
z-index: 1000;
|
|
3833
|
+
background-color: transparent;
|
|
3834
|
+
border-radius: 100%;
|
|
3835
|
+
transition: background-color .15s linear;
|
|
3836
|
+
cursor: pointer;
|
|
3837
|
+
`,t.addEventListener("pointerdown",this.onPointerDown,!1),t.addEventListener("pointerenter",this.onPointerEnter,!1),t.addEventListener("pointermove",this.onPointerMove,!1),t.addEventListener("click",this.onMouseClick,!1),this.context=t.getContext("2d"),t}destroy(){cancelAnimationFrame(this._animator),this.orbit.removeEventListener("change",this._update),this.orbit.enabled=this.orbitState,window.removeEventListener("pointermove",this.onDrag,!1),window.removeEventListener("pointerup",this.onPointerUp,!1),this._emitter.removeAllListeners(),this.domElement.removeEventListener("pointerdown",this.onPointerDown,!1),this.domElement.removeEventListener("pointerenter",this.onPointerEnter,!1),this.domElement.removeEventListener("pointermove",this.onPointerMove,!1),this.domElement.removeEventListener("click",this.onMouseClick,!1),this.domElement.remove(),window.clearTimeout(this._textTimer),this._text.remove()}}class _l{get isFinished(){return this.params?this.framesDone>=this.params.frames:!0}set visible(e){this.shadowCatcherMesh.visible=e,this.progShadowGrp.visible=e,e||(this.isRendering=!1)}get paused(){return this.params?this.params.paused:!0}set paused(e){this.params&&(this.params.paused=e,e&&(this.isRendering=!1))}constructor(e,t,{resolution:i=1024,shadowMapRes:r=512,shadowBias:l=.001,lightCount:o=8,size:c=4,frames:h=40,lightRadius:m=2,ambientWeight:p=.5,alphaTest:s=.98,paused:a=!1}={}){this.params={enabled:!0,frames:h,lightRadius:m,ambientWeight:p,alphaTest:s,debugHelpers:!1,size:c,paused:a},this.scene=t,this.renderer=e,this.buffer1Active=!1,this.dirLights=[],this.dirLightsHelpers=[],this.clearColor=new d.Color,this.clearAlpha=0,this.progress=0,this.discardMaterial=new xl,this.lights=[],this.meshes=[],this.objectsToShow=[],this.autoHiddenObjects=[],this.objectsToShowSet=new Set,this.objectsToShowAncestors=new Set,this.framesDone=0,this.fixedCamera=null,this.isRendering=!1,this.isZUp=d.Object3D.DEFAULT_UP.z===1,this.progShadowGrp=new d.Group,this.progShadowGrp.name="progressive_shadow_assets",this.scene.add(this.progShadowGrp),this.lightOrigin=new d.Group,this.lightOrigin.name="light_origin",this.isZUp?this.lightOrigin.position.set(c,c,c*1.5):this.lightOrigin.position.set(c,c,c),this.progShadowGrp.add(this.lightOrigin),this.lightGroup=new d.Group,this.lightGroup.name="all_dir_lights",this.progShadowGrp.add(this.lightGroup);const u=Math.PI;for(let f=0;f<o;f++){const v=new d.DirectionalLight(16777215,u/o);v.name="dir_light_"+f,v.castShadow=!0,v.shadow.bias=l,v.shadow.camera.near=.1,v.shadow.camera.far=50,v.shadow.camera.right=c/2,v.shadow.camera.left=-c/2,v.shadow.camera.top=c/2,v.shadow.camera.bottom=-c/2,v.shadow.mapSize.width=r,v.shadow.mapSize.height=r,this.dirLights.push(v),this.lightGroup.add(v)}const g=/(Android|iPad|iPhone|iPod)/g.test(navigator==null?void 0:navigator.userAgent)?d.HalfFloatType:d.FloatType;this.progressiveLightMap1=new d.WebGLRenderTarget(i,i,{type:g}),this.progressiveLightMap2=new d.WebGLRenderTarget(i,i,{type:g}),this.progressiveLightMap1.texture.colorSpace=d.NoColorSpace,this.progressiveLightMap2.texture.colorSpace=d.NoColorSpace,this.shadowCatcherMaterial=new yl({map:this.progressiveLightMap2.texture,transparent:!0,opacity:1});const _=new d.PlaneGeometry(c,c);this.isZUp||_.rotateX(-Math.PI/2),this.shadowCatcherMesh=new d.Mesh(_,this.shadowCatcherMaterial),this.isZUp?this.shadowCatcherMesh.position.z=.001:this.shadowCatcherMesh.position.y=.001,this.shadowCatcherMesh.name="shadowCatcherMesh",this.shadowCatcherMesh.receiveShadow=!0,this.progShadowGrp.add(this.shadowCatcherMesh),this.addObjectToShow(this.progShadowGrp),this.addObjectToShow(this.lightGroup),this.addObjectToShow(this.lightOrigin),this.addObjectToShow(this.shadowCatcherMesh),this.rebuildObjectsToShowAncestors(),this.debugHelpersGroup=new d.Group,this.targetMat=new d.MeshLambertMaterial({fog:!1}),this.previousShadowMap={value:this.progressiveLightMap1.texture},this.averagingWindow={value:h},this.targetMat.onBeforeCompile=f=>{f.vertexShader=`varying vec2 vUv;
|
|
3838
|
+
`+f.vertexShader.slice(0,-1)+"vUv = uv; gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }";const v=f.fragmentShader.indexOf("void main() {");f.fragmentShader=`varying vec2 vUv;
|
|
3839
|
+
`+f.fragmentShader.slice(0,v)+`uniform sampler2D previousShadowMap;
|
|
3840
|
+
uniform float averagingWindow;
|
|
3841
|
+
`+f.fragmentShader.slice(v-1,-1)+`
|
|
3842
|
+
vec3 texelOld = texture2D(previousShadowMap, vUv).rgb;
|
|
3843
|
+
gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/ averagingWindow);
|
|
3844
|
+
}`,f.uniforms.previousShadowMap=this.previousShadowMap,f.uniforms.averagingWindow=this.averagingWindow}}renderOnRenderTargets(e){this.prepare(),this.averagingWindow.value=this.params.frames;const t=this.buffer1Active?this.progressiveLightMap1:this.progressiveLightMap2,i=this.buffer1Active?this.progressiveLightMap2:this.progressiveLightMap1;this.renderer.setRenderTarget(t),this.previousShadowMap.value=i.texture,this.buffer1Active=!this.buffer1Active,this.renderer.render(this.scene,e),this.finish(),this.renderer.setRenderTarget(null)}showDebugHelpers(e){if(!this.debugHelpersGroup.children.length){const t=new d.Mesh(new d.PlaneGeometry(2,2),new d.MeshBasicMaterial({map:this.progressiveLightMap1.texture,side:d.DoubleSide}));this.isZUp?t.position.z=this.params.size/2:t.position.y=this.params.size/2;for(const l of this.dirLights){const o=new d.DirectionalLightHelper(l);this.dirLightsHelpers.push(o)}const i=this.isZUp?new d.Vector3(0,0,1):new d.Vector3(0,1,0),r=new d.PlaneHelper(new d.Plane(i,.001),this.params.size,16776960);this.debugHelpersGroup.add(t,r,...this.dirLightsHelpers)}e?(this.progShadowGrp.add(this.debugHelpersGroup),this.dirLightsHelpers.forEach(t=>{t.update()})):this.progShadowGrp.remove(this.debugHelpersGroup)}randomiseLights(){const e=this.lightOrigin.position.length();for(let t=0;t<this.dirLights.length;t++){if(Math.random()>this.params.ambientWeight)this.dirLights[t].position.set(this.lightOrigin.position.x+d.MathUtils.randFloatSpread(this.params.lightRadius),this.lightOrigin.position.y+d.MathUtils.randFloatSpread(this.params.lightRadius),this.lightOrigin.position.z+d.MathUtils.randFloatSpread(this.params.lightRadius));else{const i=Math.acos(2*Math.random()-1)-1.570795,r=2*3.14159*Math.random();this.isZUp?this.dirLights[t].position.set(Math.cos(i)*Math.cos(r)*e,Math.cos(i)*Math.sin(r)*e,Math.abs(Math.sin(i)*e)):this.dirLights[t].position.set(Math.cos(i)*Math.cos(r)*e,Math.abs(Math.cos(i)*Math.sin(r)*e),Math.sin(i)*e)}this.params.debugHelpers&&this.dirLightsHelpers[t].update()}}async recalculate(){this.params.enabled&&(this.clear(),this.framesDone=0,this.fixedCamera=null,this.isRendering=!1)}prepare(){this.lights.forEach(t=>{t.object.intensity=0}),this.meshes.forEach(t=>{t.object.material=this.discardMaterial}),this.autoHiddenObjects.length=0;const e=t=>this.objectsToShowAncestors.has(t);this.scene.traverse(t=>{t!==this.scene&&(this.isExcludedObject(t)||e(t)||t.isLight||t.isCamera||t.visible&&(this.autoHiddenObjects.push({object:t,visible:t.visible}),t.visible=!1))}),this.lightGroup.visible=!0,this.shadowCatcherMesh.material=this.targetMat,this.params.debugHelpers&&this.showDebugHelpers(!1)}finish(){this.lights.forEach(e=>{e.object.intensity=e.intensity}),this.meshes.forEach(e=>{e.object.material=e.material}),this.autoHiddenObjects.forEach(e=>{e.object.visible=e.visible}),this.autoHiddenObjects.length=0,this.lightGroup.visible=!1,this.shadowCatcherMesh.material=this.shadowCatcherMaterial,this.params.debugHelpers&&this.showDebugHelpers(!0)}clear(){this.renderer.getClearColor(this.clearColor),this.clearAlpha=this.renderer.getClearAlpha(),this.renderer.setClearColor("black",1),this.renderer.setRenderTarget(this.progressiveLightMap1),this.renderer.clear(),this.renderer.setRenderTarget(this.progressiveLightMap2),this.renderer.clear(),this.renderer.setRenderTarget(null),this.renderer.setClearColor(this.clearColor,this.clearAlpha),this.shadowCatcherMesh.material.alphaTest=0,this.updateShadowObjectsList()}updateShadowObjectsList(){this.lights.length=0,this.meshes.length=0,this.objectsToShow.length=0,this.objectsToShowSet.clear(),this.addObjectToShow(this.progShadowGrp),this.addObjectToShow(this.lightGroup),this.addObjectToShow(this.lightOrigin),this.addObjectToShow(this.shadowCatcherMesh),this.scene.traverse(e=>{if(e!==this.scene){if(this.isExcludedObject(e)){this.addObjectToShow(e);return}if(e===this.progShadowGrp||e===this.lightGroup||e===this.lightOrigin){this.addObjectToShow(e);return}if(e===this.shadowCatcherMesh){this.addObjectToShow(e);return}if(e.isLight&&e.parent!==this.lightGroup){this.lights.push({object:e,intensity:e.intensity});return}e.isGoods||e.isTransformControls||e.geometry&&e!==this.shadowCatcherMesh&&e.castShadow&&(this.meshes.push({object:e,material:e.material}),this.addObjectToShow(e))}}),this.rebuildObjectsToShowAncestors()}addObjectToShow(e){e&&(this.objectsToShowSet.has(e)||(this.objectsToShow.push({object:e,visible:e.visible}),this.objectsToShowSet.add(e)))}rebuildObjectsToShowAncestors(){this.objectsToShowAncestors.clear();const e=t=>{let i=t;for(;i&&!this.objectsToShowAncestors.has(i);)this.objectsToShowAncestors.add(i),i=i.parent};this.objectsToShow.forEach(({object:t})=>{e(t)})}isExcludedObject(e){const t=e;return!!(t.isCSS2DObject||t.isCSS3DObject||t.isHelper||typeof e.type=="string"&&e.type.endsWith("Helper")||typeof e.name=="string"&&e.name.toLowerCase().includes("helper"))}update(e){!this.params||!this.shadowCatcherMesh||!this.progressiveLightMap1||!this.progressiveLightMap2||!this.params.enabled||this.framesDone>=this.params.frames||this.params.paused||!this.shadowCatcherMesh.visible||!this.progShadowGrp.visible||(this.framesDone===0&&(this.fixedCamera=e.clone(),this.isRendering=!0),this.shadowCatcherMesh.material.alphaTest=d.MathUtils.clamp(d.MathUtils.mapLinear(this.framesDone,2,this.params.frames-1,0,this.params.alphaTest),0,1),this.renderOnRenderTargets(this.fixedCamera||e),this.randomiseLights(),this.progress=d.MathUtils.mapLinear(this.framesDone,0,this.params.frames-1,0,100),this.framesDone++,this.framesDone>=this.params.frames&&(this.fixedCamera=null,this.isRendering=!1))}destroy(){this.scene&&this.progShadowGrp&&this.scene.remove(this.progShadowGrp),this.progressiveLightMap1&&(this.progressiveLightMap1.dispose(),this.progressiveLightMap1=null),this.progressiveLightMap2&&(this.progressiveLightMap2.dispose(),this.progressiveLightMap2=null),this.shadowCatcherMaterial&&(this.shadowCatcherMaterial.dispose(),this.shadowCatcherMaterial=null),this.targetMat&&(this.targetMat.dispose(),this.targetMat=null),this.discardMaterial&&(this.discardMaterial.dispose(),this.discardMaterial=null),this.shadowCatcherMesh&&(this.shadowCatcherMesh.geometry&&this.shadowCatcherMesh.geometry.dispose(),this.shadowCatcherMesh=null),this.dirLights.forEach(e=>{e.parent&&e.parent.remove(e);const t=e;t.dispose&&typeof t.dispose=="function"&&t.dispose()}),this.dirLights=[],this.dirLightsHelpers.forEach(e=>{e.parent&&e.parent.remove(e);const t=e;t.dispose&&typeof t.dispose=="function"&&t.dispose()}),this.dirLightsHelpers=[],this.debugHelpersGroup&&(this.debugHelpersGroup.children.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.debugHelpersGroup.clear(),this.debugHelpersGroup=null),this.progShadowGrp&&(this.progShadowGrp.clear(),this.progShadowGrp=null),this.lightGroup&&(this.lightGroup.clear(),this.lightGroup=null),this.lightOrigin&&(this.lightOrigin.clear(),this.lightOrigin=null),this.lights=[],this.meshes=[],this.objectsToShow=[],this.autoHiddenObjects=[],this.objectsToShowSet=new Set,this.objectsToShowAncestors=new Set,this.scene=null,this.renderer=null,this.fixedCamera=null,this.clearColor=null,this.previousShadowMap=null,this.averagingWindow=null,this.params=null}}function ar(n={},e,t,i=r=>{}){const r=class extends d.ShaderMaterial{constructor(l={}){const o=Object.entries(n);super({uniforms:o.reduce((c,[h,m])=>{const p=d.UniformsUtils.clone({[h]:{value:m}});return{...c,...p}},{}),vertexShader:e,fragmentShader:t}),o.forEach(([c])=>Object.defineProperty(this,c,{get:()=>this.uniforms[c].value,set:h=>this.uniforms[c].value=h})),Object.assign(this,l),i&&i(this)}};return r.key=d.MathUtils.generateUUID(),r}const yl=ar({transparent:!0,color:new d.Color(0,0,0),alphaTest:0,opacity:1,map:null,depthWrite:!1,toneMapped:!1,blend:2},`varying vec2 vUv;
|
|
3845
|
+
void main() {
|
|
3846
|
+
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.);
|
|
3847
|
+
vUv = uv;
|
|
3848
|
+
}`,`varying vec2 vUv;
|
|
3849
|
+
uniform sampler2D map;
|
|
3850
|
+
uniform vec3 color;
|
|
3851
|
+
uniform float opacity;
|
|
3852
|
+
uniform float alphaTest;
|
|
3853
|
+
uniform float blend;
|
|
3854
|
+
void main() {
|
|
3855
|
+
vec4 sampledDiffuseColor = texture2D(map, vUv);
|
|
3856
|
+
gl_FragColor = vec4(color * sampledDiffuseColor.r * blend, max(0.0, (1.0 - (sampledDiffuseColor.r + sampledDiffuseColor.g + sampledDiffuseColor.b) / alphaTest)) * opacity);
|
|
3857
|
+
#include <tonemapping_fragment>
|
|
3858
|
+
#include <colorspace_fragment>
|
|
3859
|
+
}`),xl=ar({},"void main() { }","void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); discard; }");class wl extends se.CSS2DObject{constructor(e){const t=document.createElement("div");super(t),this._controls=e}}const bl="https://cdn2.seer-group.com/libs/hdr/aristea_wreck_512.hdr",Al="https://cdn2.seer-group.com/libs/fonts.type.json",Tl=new yr.Font(Al);class Mi{constructor(e){var t;this._props=e,this.name="",this._defaults={color:""},this.color="",this.name=this._props.name,this.color=this._defaults.color="#"+((t=e.target.color)==null?void 0:t.getHexString())}change(e){var t;this.color=e,(t=this._props.target.color)==null||t.set(e)}reset(){this.change(this._defaults.color)}}var lr=(n=>(n[n.DEFAULT=0]="DEFAULT",n[n.CAN_INSTALL=1]="CAN_INSTALL",n))(lr||{});const Bs=.15;d.Object3D.DEFAULT_UP.set(0,0,1);let Ve,kt=0,Pi=0;const Sl=()=>{Ve=void 0,kt=0,Pi=0},Cl=new d.MeshBasicMaterial({colorWrite:!1});class Ml{constructor(e){this.props=e,this.stats=new at,this.scene=new d.Scene,this.overlayScene=new d.Scene,this.renderer=new d.WebGLRenderer({antialias:!0,alpha:!0,logarithmicDepthBuffer:!0,powerPreference:"high-performance",preserveDrawingBuffer:!0}),this.css2dRenderer=new se.CSS2DRenderer,this.mousePos=new d.Vector2,this.mouseCoord=new d.Vector2,this.offset=new d.Vector2,this.size=new d.Vector2,this.amr=new er({showSizeBox:!0,showController:!0}),this._clock=new d.Clock(!0),this._uiHiddenTime=this._clock.getElapsedTime(),this.camera=new d.PerspectiveCamera(39.6,window.innerWidth/window.innerHeight,.1,1e4),this.d=2,this.orthographicCamera=new d.OrthographicCamera(-this.d*(window.innerWidth/window.innerHeight),this.d*(window.innerWidth/window.innerHeight),this.d,-this.d,.1,1e3),this._axisMoving=!1,this._container=new d.Group,this._raycaster=new d.Raycaster,this._selected=[],this._pointerDownTimeout=0,this._dragging=!1,this.maxSample=1024*2,this.sampleCount=0,this._usePathTracing=!1,this._fpsCache=[],this._fpsCacheMax=20,this._emitter=new je,this.sound=new Co,this._rafId=null,this._destroyed=!1,this._ground=new d.Mesh(new d.PlaneGeometry(100,100),new d.MeshPhysicalMaterial({color:new d.Color("#eee"),metalness:.4,roughness:.1,clearcoat:1,clearcoatRoughness:.1})),this.light=new d.PointLight(16777215,10,30),this._amrRender=new d.WebGLRenderTarget(1024,1024,{format:d.RGBAFormat,type:d.UnsignedByteType,colorSpace:d.SRGBColorSpace,samples:8}),this._pointCloudMode=!1,this._shadowMode=!1,this.addEventListener=this._emitter.on.bind(this._emitter),this.removeEventListener=this._emitter.on.bind(this._emitter),this._showSlots=!0,this._showSize=!0,this._showControls=!0,this._drag=p=>{this._dragging=!0,this._pointermove(p)},this._dragend=p=>{this._dragging=!1},this._pointermove=p=>{if(this._pointerDownTimeout)return clearTimeout(this._pointerDownTimeout),this._pointerDownTimeout=0;let{top:s,left:a}=this.renderer.domElement.getBoundingClientRect();this.offset.set(a,s),this.mousePos.set(p.clientX-a,p.clientY-s),this.mouseCoord.set((p.clientX-a)/this.size.x*2-1,-((p.clientY-s)/this.size.y)*2+1),this._raycaster.setFromCamera(this.mouseCoord,this.camera)},this._pointerdown=p=>{const s=()=>{let a=[...this._outlinePass.selectedObjects];this._outlinePass.selectedObjects=[],this.amr.slots.forEach(_=>_.selected=!1);const g=this._raycaster.intersectObjects(this.amr.slots,!1)[0];g&&this.amr.slots.forEach(_=>{_.traverse(f=>{f==g.object?a!=null&&a.includes(_)?(a=void 0,_.deviceSelected=!1):(this._outlinePass.selectedObjects=[_],_.deviceSelected=!0):_.deviceSelected=!1})}),this._pointerDownTimeout=0};this._pointerDownTimeout=window.setTimeout(s,200)},this._detectTrackpad=()=>{Ve||typeof Ve<"u"||(kt===0&&(Pi=performance.now()),kt++,performance.now()-Pi>66&&(kt>5?Ve=!0:Ve=!1,Ve?this.controls.zoomSpeed=.2:this.controls.zoomSpeed=1,setTimeout(Sl,2e3)))},this.debounceForkHeightChange=Io(()=>{var p;(p=this._progressShadow)==null||p.recalculate()},300),this.focusSlots=p=>{if(this.amr.slots.forEach(M=>M.focused=!1),!p.length){this.fit();return}const s=p.flatMap(M=>{if(M.focused=!0,!M.parent)return[];const R=new d.Vector3;return M.parent.getWorldPosition(R),[R]});if(!s.length)return;const a=s.reduce((M,R)=>M.add(R),new d.Vector3).multiplyScalar(1/s.length),u=this.controls.target.clone(),g=this.camera.position.clone().sub(u).normalize();let _=0;for(const M of s){const R=M.clone().sub(a),E=R.dot(g),F=Math.sqrt(Math.max(0,R.lengthSq()-E*E));F>_&&(_=F)}_=_*1.2+.45;const f=this.camera.fov*Math.PI/180,v=2*Math.atan(Math.tan(f/2)*this.camera.aspect),y=_/Math.tan(v/2),x=_/Math.tan(f/2),w=Math.max(y,x),b=new d.Vector3(0,0,a.z),C=a.clone().sub(b).normalize().multiplyScalar(w<1?1:w).add(a),T=this.camera.position.clone(),S=u.clone(),A={t:0};let P=500;const I=T.distanceTo(C)+S.distanceTo(b);I>.001&&(P=Math.min(1e3,Math.max(450,I*45))),this._fitAnimation=new zt(A).to({t:1},P).easing(ie.Easing.Quadratic.InOut).onStart(()=>{this.controls.enabled=!1}).onUpdate(()=>{const M=A.t;this.camera.position.lerpVectors(T,C,M),this.controls.target.lerpVectors(S,b,M)}).onComplete(()=>{this.controls.enabled=!0}).start()},this.fit=()=>{new d.Box3().setFromObject(this._container);const s=this.amr.sizeBox.size.getSize(new d.Vector3),a=s.clone().multiplyScalar(.5),u=new d.Vector3(0,0,a.z);let g=a.clone().sub(u);g.lengthSq()<1e-6&&(g=new d.Vector3(1,0,0));const _=g.clone().normalize(),f=s.clone().multiplyScalar(.5),v=[new d.Vector3(f.x,f.y,f.z),new d.Vector3(f.x,f.y,-f.z),new d.Vector3(f.x,-f.y,f.z),new d.Vector3(f.x,-f.y,-f.z),new d.Vector3(-f.x,f.y,f.z),new d.Vector3(-f.x,f.y,-f.z),new d.Vector3(-f.x,-f.y,f.z),new d.Vector3(-f.x,-f.y,-f.z)];let y=0;for(const L of v){const V=L.dot(_),z=Math.sqrt(Math.max(0,L.lengthSq()-V*V));z>y&&(y=z)}y=y*1.05;const x=this.camera.fov*Math.PI/180,w=2*Math.atan(Math.tan(x/2)*this.camera.aspect),b=y/Math.tan(w/2),C=y/Math.tan(x/2),T=Math.max(b,C),S=a.clone();let A=s.z/3;s.z<s.x&&s.z<s.y&&(A=s.x*.8),s.z>s.x&&s.z>s.y&&(A=0),S.z+=A;const P=g.clone().normalize().multiplyScalar(T<1?1:T).add(S),I=Math.max(s.x*2,5);this.light.position.set(I,0,s.z*2);const M=this.camera.position.clone(),R=this.controls.target.clone(),E={t:0};let F=600;const D=M.distanceTo(P)+R.distanceTo(u);D>.001&&(F=Math.min(800,Math.max(650,D*45))),this._fitAnimation=new zt(E).to({t:1},F).easing(ie.Easing.Quadratic.InOut).onStart(()=>{this.controls.enabled=!1}).onUpdate(()=>{const L=E.t;this.camera.position.lerpVectors(M,P,L),this.controls.target.lerpVectors(R,u,L)}).onComplete(()=>{this.controls.enabled=!0,!this.shadowMode&&(this._progressShadow.visible=!0,this._progressShadow.isFinished||this._progressShadow.recalculate())}).start(),this.controls.minDistance=Math.max(.2,Math.min(T*.25,T-.1)),this.controls.maxDistance=T*4},this.resize=()=>{var _;const p=this.renderer.domElement.parentElement;if(!p)return;p.style.display="flex",this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.renderer.domElement.style.flexGrow="1";const s=p.clientWidth,a=p.clientHeight;this.size.set(s,a),this.camera.aspect=s/a,this.camera.updateProjectionMatrix(),this._amrRender.setSize(s,a),this._updateCamera(),this.css2dRenderer.setSize(s,a);const u=this.renderer.getPixelRatio();(_=this.pathTracer)==null||_.updateCamera(),this.sampleCount=0,this.renderer.setSize(s,a),this._composer.setSize(s,a),this._composer.passes.forEach(f=>f.setSize(s,a));const g=this._fxaaPass.material.uniforms;g.resolution.value.x=1/(s*u),g.resolution.value.y=1/(a*u),this._bloomPass&&this._bloomPass.setSize(s,a)},this.ticker=()=>{if(!this._destroyed){if(this.stats.begin(),this.renderer.domElement.dispatchEvent(new CustomEvent("ticker")),this._rafId=requestAnimationFrame(this.ticker),this.renderer.autoClear=!1,this.renderer.clear(),this.usePathTracing){this.hideAmrUI(),this.sampleCount<this.maxSample?this.sampleCount++:this.pathTracer.pausePathTracing=!0,this.pathTracer.renderSample();const p=this.renderer.autoClear;this.renderer.autoClear=!1,this.scene.overrideMaterial=Cl,this.renderer.clearDepth(),this.renderer.render(this.scene,this.mainCamera),this.scene.overrideMaterial=null,this.renderer.render(this.overlayScene,this.mainCamera),this.renderer.autoClear=p}else{this._clock.getElapsedTime()-this._uiHiddenTime>.15?this.showAmrUI(!0):this.hideAmrUI(!1,!1);const s=this.stats.fps();this.usePathTracing||(this._fpsCache.length>this._fpsCacheMax&&this._fpsCache.shift(),this._fpsCache.push(s)),this.amr.slots.forEach(a=>{this._dragging?a.getCanInstall()&&a.render(this):a.render(this)}),ie.update(),this.controls.update(),this._progressShadow.update(this.mainCamera),this.css2dRenderer.render(this.scene,this.mainCamera),this.updatePosition(),this.scene.overrideMaterial=null,this.renderer.render(this.scene,this.mainCamera)}this.stats.end()}},this.stats.showPanel(0),this.hideState(),e.fov&&(this.camera.fov=e.fov,this.camera.updateProjectionMatrix()),this._ground.visible=!1,this.controls=new gr.OrbitControls(this.camera,this.renderer.domElement),this.controls.enablePan=!0,this.controls.rotateSpeed=this.props.isMobile?.6:.5,this.controls.dampingFactor=Bs,this.controls.enableDamping=!0,this.controls.maxDistance=10,this.controls.minDistance=1,this.controls.zoomSpeed=this.props.isMobile?.3:Ys()?.2:1,this._cameraPositionUI=new wl(this.controls),this.renderer.setPixelRatio(window.devicePixelRatio||1),this.renderer.autoClear=!0,this.renderer.toneMapping=d.ACESFilmicToneMapping,this.renderer.toneMappingExposure=1.4,this.renderer.outputColorSpace=d.SRGBColorSpace,this.renderer.localClippingEnabled=!0,this.renderer.shadowMap.enabled=!0,this.css2dRenderer.domElement.style.pointerEvents="none",this.css2dRenderer.domElement.style.position="absolute",this.css2dRenderer.domElement.style.top="0px",d.ShaderChunk.tonemapping_pars_fragment=d.ShaderChunk.tonemapping_pars_fragment.replace("vec3 CustomToneMapping( vec3 color ) { return color; }",`
|
|
3860
|
+
float startCompression = 0.8;
|
|
3861
|
+
float desaturation = 0.5;
|
|
3862
|
+
vec3 CustomToneMapping( vec3 color ) {
|
|
3863
|
+
color *= toneMappingExposure;
|
|
3864
|
+
|
|
3865
|
+
float d = 1. - startCompression;
|
|
3866
|
+
|
|
3867
|
+
float peak = max(color.r, max(color.g, color.b));
|
|
3868
|
+
if (peak < startCompression) return color;
|
|
3869
|
+
|
|
3870
|
+
float newPeak = 1. - d * d / (peak + d - startCompression);
|
|
3871
|
+
float invPeak = 1. / peak;
|
|
3872
|
+
|
|
3873
|
+
float extraBrightness = dot(color * (1. - startCompression * invPeak), vec3(1, 1, 1));
|
|
3874
|
+
|
|
3875
|
+
color *= newPeak * invPeak;
|
|
3876
|
+
float g = 1. - 3. / (desaturation * extraBrightness + 3.);
|
|
3877
|
+
return mix(color, vec3(1, 1, 1), g);
|
|
3878
|
+
}`),this.camera.position.set(10,-10,5),this.camera.lookAt(new d.Vector3);const{tiles:t}=Po();this.pathTracer=new fo(this.renderer),this.pathTracer.filterGlossyFactor=.6;let i=window.devicePixelRatio;i<2&&(i=2),this.pathTracer.renderScale=this.props.isMobile?1:i,this.pathTracer.bounces=this.props.isMobile?8:10,this.pathTracer.transmissiveBounces=this.props.isMobile?1:3,this.pathTracer.tiles.set(t,t),this.pathTracer.fadeDuration=0;const r=new gl(e.workerUrl),l=typeof navigator<"u"?navigator.hardwareConcurrency:4;r.maxWorkerCount=l,this.pathTracer.setBVHWorker(r),this.orthographicCamera.left=-20,this.orthographicCamera.right=20,this.orthographicCamera.top=-20,this.orthographicCamera.bottom=20;let o=this.controls.target.x,c=this.controls.target.y;const h=()=>{this.controls.target.x=o,this.controls.target.y=c};this.controls.addEventListener("change",()=>{var p;this.sampleCount=0,h(),this._uiHiddenTime=this._clock.getElapsedTime(),this.orthographicCamera.position.copy(this.camera.position),this.orthographicCamera.lookAt(this.controls.target),this.usePathTracing&&(this.pathTracer.pausePathTracing=!1,(p=this.pathTracer)==null||p.updateCamera()),this._updateCamera(),!(Math.abs(this.camera.position.x)<.001||Math.abs(this.camera.position.y)<.001)&&(this._axisMoving||(this.mainCamera=this.camera,this.usePathTracing&&this.generateBVH().then()))}),this._mainCamera=this.camera,this._composer=new _r.EffectComposer(this.renderer),this._composer.setPixelRatio(window.devicePixelRatio);const m=new Hi.RenderPass(this.scene,this.camera);this._composer.addPass(m),this._composer.addPass(new vr.OutputPass),this._outlinePass=new Ni.OutlinePass(new d.Vector2(window.innerWidth,window.innerHeight),this.scene,this.camera),this._outlinePass.visibleEdgeColor.set(26367),this._outlinePass.edgeThickness=.5,this._outlinePass.hiddenEdgeColor.set(26367),this._outlinePass.edgeStrength=3,this._outlinePass.edgeGlow=0,this._composer.addPass(this._outlinePass),this._outlinePassError=new Ni.OutlinePass(new d.Vector2(window.innerWidth,window.innerHeight),this.scene,this.camera),this._outlinePassError.visibleEdgeColor.set(16711680),this._outlinePassError.edgeThickness=.5,this._outlinePassError.hiddenEdgeColor.set(16711680),this._outlinePassError.edgeStrength=3,this._outlinePassError.edgeGlow=0,this._composer.addPass(this._outlinePassError),this._bloomPass=new mr.UnrealBloomPass(new d.Vector2(window.innerWidth,window.innerHeight),.1,.1,.2),this._bloomPass.enabled=!1,this._bloomPass.renderToScreen=!1,this._composer.addPass(this._bloomPass),this._composer.renderTarget1.texture.colorSpace=d.SRGBColorSpace,this._composer.renderTarget2.texture.colorSpace=d.SRGBColorSpace,this._fxaaPass=new dr.ShaderPass(pr.FXAAShader),this._composer.addPass(this._fxaaPass),this._progressShadow=new _l(this.renderer,this.scene,{size:8,lightCount:e.isMobile?6:12,frames:e.isMobile?80:120,lightRadius:8,ambientWeight:.8}),this._progressShadow.lightOrigin.position.set(3,2.5,6),this._progressShadow.visible=!1,this._container.add(this.amr),this.scene.add(this._container),this.ticker(),this._loadEnv(),this._initEvents(),this.scene.add(this._cameraPositionUI),this._ground.rotateX(-Math.PI/2),this.scene.add(this._ground),(typeof e.useAxisBall!="boolean"||e.useAxisBall)&&(this._controlsGizmo=new vl(this.controls,{size:160,padding:12,offset:e.axisBallOffset||new d.Vector2(10,10),fontSize:17,bubbleSizePrimary:18,bubbleSizeSecondary:14}),this._controlsGizmo.addListener("axis-select-start",()=>{this._axisMoving=!0,this.mainCamera=this.orthographicCamera,this.usePathTracing&&this.generateBVH().then()}),this._controlsGizmo.addListener("axis-select-end",()=>{this._axisMoving=!1})),this.test=new d.Mesh(new d.PlaneGeometry(2,2),new d.MeshBasicMaterial({map:this._amrRender.texture,opacity:.5,transparent:!0,side:d.DoubleSide})),this.test.position.set(0,1,0),this.test.visible=!1,this.scene.add(this.test)}get pointCloudMode(){return this._pointCloudMode}set pointCloudMode(e){this._pointCloudMode=e,this.amr.setPointCloudMode(e),e?setTimeout(()=>{console.log(this.amr.lines.children)},3e3):this._outlinePass.selectedObjects=[],this._bloomPass,e?this.scene.fog=null:this.scene.background=null}get usePathTracing(){return this._usePathTracing}_clearAmrContent(){const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(this._amrRender),this.renderer.setClearColor(0,0),this.renderer.clear(!0,!0,!0),this.renderer.setRenderTarget(e)}get shadowMode(){return this._shadowMode}set shadowMode(e){e?(this._progressShadow.visible=!1,this.amr.bodyOpacity=.2):(this._progressShadow.visible=!0,this.amr.bodyOpacity=1,this._progressShadow.isFinished||this._progressShadow.recalculate().then()),this._shadowMode=e}set usePathTracing(e){this._clearAmrContent(),e?(this.scene.add(this.light),this.renderer.toneMappingExposure=1.8,this.overlayScene.add(this._progressShadow.shadowCatcherMesh),this.amr&&(this.amr.bodyOpacity=1),this.hideAmrUI(),this.pathTracer.renderToCanvas=!0,this.scene.background=null):(this.light.removeFromParent(),this.renderer.toneMappingExposure=1.4,this.scene.add(this._progressShadow.shadowCatcherMesh),this.pathTracer.renderToCanvas=!1,this.amr.logos.forEach(t=>{var i;(i=t.parent)==null||i.add(t.target)}),this.showAmrUI(),this.amr&&this.amr.opacityCache!==void 0?(this.amr.bodyOpacity=this.amr.opacityCache,this.amr.opacityCache=void 0):this.amr&&(this.amr.bodyOpacity=1),this.pathTracer.reset(),this._ground.visible=!1,this.scene.background=this.scene.environment),this._usePathTracing=e,this.controls.dampingFactor=e?1:Bs,this.sampleCount=0}get fpsAverage(){return qs(this._fpsCache)}get mainCamera(){return this._mainCamera}set mainCamera(e){this._mainCamera=e,this._composer.passes.forEach(t=>{t instanceof Hi.RenderPass&&(t.camera=e)}),e instanceof d.OrthographicCamera?this.scene.background=null:this.scene.background=this.scene.environment}showState(){this.stats.dom.style.display="block"}hideState(){this.stats.dom.style.display="none"}hideAmrUI(e=!0,t=!0){this.shadowMode||this.amr.slots.forEach(i=>i.hide()),this.amr.sizeBox.hide(e),this.amr.controllers.forEach(i=>i.hide()),t&&this.amr.goods.forEach(i=>i.hide())}showAmrUI(e=!0){this.showSlots&&this.amr.slots.forEach(t=>t.show()),this.showSize&&this.amr.sizeBox.show(e),this.showControls&&this.amr.controllers.forEach(t=>t.show()),this.amr.goods.forEach(t=>t.show())}get showSlots(){return this._showSlots}set showSlots(e){this._showSlots=e,this.amr.slots.forEach(t=>e?t.show():t.hide())}get showSize(){return this._showSize}set showSize(e){this._showSize=e,e?this.amr.sizeBox.show(!0):this.amr.sizeBox.hide(!0)}get showControls(){return this._showControls}set showControls(e){this._showControls=e,this.amr.controllers.forEach(t=>e?t.show():t.hide())}_updateCamera(){const e=this.mainCamera.position.distanceTo(this.controls.target),t=2*Math.tan(this.camera.fov*.5*Math.PI/180)*e,i=this.size.x/this.size.y;this.orthographicCamera.left=-t*i/2,this.orthographicCamera.right=t*i/2,this.orthographicCamera.top=t/2,this.orthographicCamera.bottom=-t/2,this.orthographicCamera.updateProjectionMatrix()}_loadEnv(){new fr.HDRLoader().load(bl,t=>{t.mapping=d.EquirectangularReflectionMapping,this._usePathTracing||(this.scene.background=t,this.scene.backgroundBlurriness=1,this.scene.backgroundIntensity=1,this.scene.backgroundRotation=new d.Euler(Math.PI/2,0,Math.PI*.98*.8),this.scene.environment=t,this.overlayScene.environment=t,this.scene.environmentRotation=this.scene.backgroundRotation,this.overlayScene.environmentRotation=this.scene.environmentRotation,this.scene.environmentIntensity=1.4,this.overlayScene.environmentIntensity=this.scene.environmentIntensity),this.pathTracer.updateEnvironment()},()=>{},()=>{})}_initEvents(){window.addEventListener("drag",this._drag),window.addEventListener("dragend",this._dragend),document.addEventListener("wheel",this._detectTrackpad),window.addEventListener("pointermove",this._pointermove),this.renderer.domElement.addEventListener("pointerdown",this._pointerdown)}switchCamera(){this.mainCamera=this.mainCamera===this.camera?this.orthographicCamera:this.camera}toCameraTop(){const e=this.camera.position.distanceTo(this.controls.target);this.camera.position.copy(new d.Vector3(0,e+this.controls.target.y,0))}toCameraRight(){const e=this.camera.position.distanceTo(this.controls.target);this.camera.position.copy(new d.Vector3(0,this.controls.target.y,e))}toCameraFace(){const e=this.camera.position.distanceTo(this.controls.target);this.camera.position.copy(new d.Vector3(e,this.controls.target.y,0))}async generateBVH(){this.pathTracer.pausePathTracing=!1,this.amr.slots.forEach(e=>e.hide()),this.amr&&(this.amr.opacityCache=this.amr.bodyOpacity,this.amr.bodyOpacity=1,this.overlayScene.clear(),this.amr.logos.forEach(e=>{const t=new d.Group;e.target.updateMatrixWorld(!0),t.applyMatrix4(e.target.matrixWorld),t.add(e.target),this.overlayScene.add(t)})),this.usePathTracing=!0,this.pathTracer.setScene(this.scene,this.mainCamera)}async download(e=!1){if(e&&!this.usePathTracing){const t=this._amrRender.width,i=this._amrRender.height,r=new Uint8Array(t*i*4);this.renderer.setRenderTarget(this._amrRender),this.renderer.readRenderTargetPixels(this._amrRender,0,0,t,i,r),this.renderer.setRenderTarget(null);const l=document.createElement("canvas");l.width=t,l.height=i;const o=l.getContext("2d"),c=new ImageData(t,i);for(let h=0;h<i;h++)for(let m=0;m<t;m++){const p=((i-h-1)*t+m)*4,s=(h*t+m)*4;c.data[s]=r[p],c.data[s+1]=r[p+1],c.data[s+2]=r[p+2],c.data[s+3]=r[p+3]}return o.putImageData(c,0,0),l.toDataURL("image/png")}else return new Promise((t,i)=>{this._uiHiddenTime=this._clock.getElapsedTime(),this.hideAmrUI();const r=this.scene.background;this.scene.background=null,setTimeout(()=>{const l=this.renderer.domElement.toDataURL("image/png");return this.scene.background=r,t(l)},this.fpsAverage)})}async captureTriViews(e){var o;const t=(e==null?void 0:e.subject)??this._container;(o=this._progressShadow)==null||o.visible;const i=this.scene.background,r=this.showSize;return new cr({renderer:this.renderer,scene:this.scene,overlayScene:this.overlayScene,subject:t,onBeforeCapture:()=>{this.scene.background=null,this.hideAmrUI(),this.showSize=!1,this.usePathTracing&&(this.usePathTracing=!1),this._progressShadow.visible=!1},onAfterCapture:()=>{this.scene.background=i,this.showAmrUI(),this.showSize=r,this._progressShadow.visible=!0}}).capture(e)}clearAMR(){oe(this.overlayScene),this.amr.clean(),this.usePathTracing=!1}async exportAMR(){const e=this._container.clone(!0);return e.traverse(t=>{t.dispose&&(t.dispose(),t.removeFromParent())}),await Zs.parseAsync(e,{onlyVisible:!0,binary:!0})}async addAMR(e,t=""){this.amr.init(this),await this.amr.load(e,t),this._progressShadow.clear(),this.amr.addEventListener("fork-height-change",this.debounceForkHeightChange),this.amr.addEventListener("shape-key-changed",(i,r)=>{this.pathTracer.reset(),this.sampleCount=0,this.pathTracer.setScene(this.scene,this.camera),this.overlayScene.traverse(l=>{if(!Object.keys(l.morphTargetDictionary||{}).includes(i))return;let o=r;l.userData[`origin_${i}`]&&(o-=l.userData[`origin_${i}`]);const c=l.morphTargetDictionary[i];l.morphTargetInfluences&&(l.morphTargetInfluences[c]=o),l instanceof d.Mesh&&l.geometry.translate(0,0,1e-5)}),this._progressShadow.clear(),this._progressShadow.recalculate()})}select(e){typeof e=="string"||(Array.isArray(e)?this._outlinePass.selectedObjects=[...e]:this._outlinePass.selectedObjects=[e])}appendTo(e){e.append(this.renderer.domElement),e.append(this.stats.dom),e.append(this.css2dRenderer.domElement),this.props.isMobile&&(e.classList.add("is-mobile"),e.style.cssText=`
|
|
3879
|
+
-webkit-user-select: none;
|
|
3880
|
+
user-select: none;
|
|
3881
|
+
touch-action: none;
|
|
3882
|
+
-webkit-touch-callout: none;
|
|
3883
|
+
`),this._controlsGizmo&&this._controlsGizmo.appendTo(e),this.stats.dom.style.bottom="0",this.stats.dom.style.top="auto",this.resize(),this._resizeObserver=new ResizeObserver(this.resize.bind(this)),this._resizeObserver.observe(e)}add(e){this._container.add(e)}updatePosition(){}removeFromParent(){var t;const e=this.renderer.domElement.parentElement;e&&((t=this._resizeObserver)==null||t.unobserve(e),e.removeChild(this.renderer.domElement))}clean(){this.amr.clean(),this._progressShadow.clear()}destroy(){var t,i,r;this._destroyed=!0,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null),this._clock.stop(),(t=this._controlsGizmo)==null||t.destroy(),this.amr.destroy(),this.amr.removeFromParent(),this._progressShadow.destroy(),ie.removeAll(),this.stats.dom.remove(),this._emitter.removeAllListeners(),(i=this._fitAnimation)==null||i.stop(),window.removeEventListener("drag",this._drag),document.removeEventListener("wheel",this._detectTrackpad),window.removeEventListener("pointermove",this._pointermove),this.renderer.domElement.removeEventListener("pointerdown",this._pointerdown);const e=this.renderer.domElement.parentElement;e&&((r=this._resizeObserver)==null||r.unobserve(e)),this.controls.dispose(),this.renderer.domElement.remove(),this.renderer.dispose(),this._composer.dispose(),oe(this.scene),this.scene.clear()}}class cr{constructor(e){this.deps=e,this.canvas=null,this.pixelBuffer=null,this.orthoCamera=new d.OrthographicCamera(-1,1,1,-1,.1,1e3),this.orthoCamera.position.set(0,0,5),this.perspectiveCamera=new d.PerspectiveCamera(45,1,.1,2e3)}async capture(e){var g,_,f,v,y,x;const t=this.deps.renderer,i=(e==null?void 0:e.subject)??this.deps.subject;if(!i)throw new Error("TriViewCapture: subject is required.");const r=new d.Vector2;t.getSize(r);const l=((g=e==null?void 0:e.size)==null?void 0:g.width)??Math.round(r.x),o=((_=e==null?void 0:e.size)==null?void 0:_.height)??Math.round(r.y),c=(e==null?void 0:e.margin)??.15,h=(e==null?void 0:e.includeOverlay)??!1,m=l/o||1,p=this.resolveViews(e==null?void 0:e.views),s=new d.WebGLRenderTarget(l,o,{format:d.RGBAFormat,type:d.UnsignedByteType});s.texture.colorSpace=d.SRGBColorSpace,s.texture.generateMipmaps=!1,s.depthBuffer=!0;const a=this.storeRendererState(t),u={};try{(v=(f=this.deps).onBeforeCapture)==null||v.call(f);const w=this.computeBounds(i);this.applyRendererState(t,l,o,e==null?void 0:e.backgroundColor);for(const b of p){const C=this.configureCamera(w,b,m,c,l,o);t.setRenderTarget(s),t.clear(!0,!0,!0),t.render(this.deps.scene,C),h&&this.deps.overlayScene&&(t.clearDepth(),t.render(this.deps.overlayScene,C));const T=this.readPixels(t,s,l,o);u[b.key]=T}}finally{s.dispose(),this.restoreRendererState(t,a),(x=(y=this.deps).onAfterCapture)==null||x.call(y)}return u}resolveViews(e){return e&&e.length?e.map(t=>({key:t.key,direction:t.direction.clone(),up:t.up.clone(),plane:t.plane})):[{key:"top",direction:new d.Vector3(0,0,1),up:new d.Vector3(0,1,0),plane:{width:"x",height:"y",depth:"z"}},{key:"front",direction:new d.Vector3(0,-1,0),up:new d.Vector3(0,0,1),plane:{width:"x",height:"z",depth:"y"}},{key:"side",direction:new d.Vector3(1,0,0),up:new d.Vector3(0,0,1),plane:{width:"y",height:"z",depth:"x"}},{key:"perspective",direction:new d.Vector3(1,1,1),up:new d.Vector3(0,0,1),plane:{width:"x",height:"z",depth:"y"},mode:"perspective",fov:39.6}]}computeBounds(e){const t=new d.Box3,i=new d.Box3,r=new d.Vector3,l=new d.Vector3,o=new d.Sphere;return e.updateMatrixWorld(!0),e.traverse(c=>{if(!c.visible)return;const m=c.geometry;if(!m)return;m.boundingBox||m.computeBoundingBox();const p=m.boundingBox;p&&(i.copy(p).applyMatrix4(c.matrixWorld),t.union(i))}),t.isEmpty()?(t.setFromCenterAndSize(r,new d.Vector3(.001,.001,.001)),l.set(.001,.001,.001),o.center.copy(r),o.radius=.001):(t.getCenter(r),t.getSize(l),t.getBoundingSphere(o)),(!Number.isFinite(o.radius)||o.radius<=0)&&(o.radius=Math.max(l.length()*.5,.001)),{box:t,center:r,size:l,sphere:o}}configureCamera(e,t,i,r,l,o){const c=t.direction.clone().normalize();c.lengthSq()===0&&c.set(0,0,1);const h=t.up.clone().normalize();if(Math.abs(h.dot(c))>.999&&(h.set(0,0,1),Math.abs(h.dot(c))>.999&&h.set(0,1,0)),(t.mode??"orthographic")==="perspective"){const w=this.perspectiveCamera,b=t.fov??45,C=d.MathUtils.degToRad(b),T=Math.max(Math.tan(C/2),1e-4),S=Math.max(T*(i||1),1e-4),A=this.getPerspectiveDirection(t,e.size).normalize(),P=new d.Vector3().crossVectors(A,h).normalize();P.lengthSq()<1e-6&&P.set(1,0,0);const I=new d.Vector3().crossVectors(P,A).normalize(),M=Math.max(e.size.x*.5,1e-4),R=Math.max(e.size.y*.5,1e-4),E=Math.max(e.size.z*.5,1e-4),F=[new d.Vector3(-M,-R,-E),new d.Vector3(-M,-R,E),new d.Vector3(-M,R,-E),new d.Vector3(-M,R,E),new d.Vector3(M,-R,-E),new d.Vector3(M,-R,E),new d.Vector3(M,R,-E),new d.Vector3(M,R,E)];let D=0,L=-1/0;for(const G of F){const Y=P.dot(G),B=I.dot(G),le=A.dot(G);L=Math.max(L,le);const we=le+Math.abs(Y)/S,me=le+Math.abs(B)/T;D=Math.max(D,we,me)}D=Math.max(D,L+.1);const V=D*(1+r);let z=1/0;for(const G of F){const Y=A.dot(G),B=V-Y;B>.001&&(z=Math.min(z,B))}return w.fov=b,w.aspect=i||l/Math.max(o,1),w.near=Math.max(.1,Number.isFinite(z)?z*.5:V*.1),w.far=Math.max(w.near+1,V+e.sphere.radius*3),w.position.copy(e.center).add(A.clone().multiplyScalar(V)),w.up.copy(I),w.lookAt(e.center),w.updateProjectionMatrix(),w.updateMatrixWorld(!0),w}const p=this.orthoCamera,s=e.size,a=e.center,u=Math.max(s[t.plane.width]*.5,.01),g=Math.max(s[t.plane.height]*.5,.01),_=Math.max(s[t.plane.depth]*.5,.01);let f=u*(1+r),v=g*(1+r);f/i>v?v=f/i:f=v*i;const y=_*(1+r)+Math.max(f,v),x=a.clone().add(c.multiplyScalar(y));return p.left=-f,p.right=f,p.top=v,p.bottom=-v,p.near=.1,p.far=y*4,p.zoom=1,p.position.copy(x),p.up.copy(h),p.lookAt(a),p.updateProjectionMatrix(),p.updateMatrixWorld(!0),p}getPerspectiveDirection(e,t){const i=e.direction.clone();i.lengthSq()===0&&i.set(1,1,1);const r=new d.Vector3(Math.abs(i.x)||1,Math.abs(i.y)||1,Math.abs(i.z)||1),l=new d.Vector3(Math.sign(i.x||1),Math.sign(i.y||1),Math.sign(i.z||1)),o=.25,c=new d.Vector3(Math.max(o,r.x)*Math.max(t.x,.001),Math.max(o,r.y)*Math.max(t.y,.001),0),h=Math.max((t.x+t.y)*.5,.001),m=Math.max(t.z,.001),p=Math.max(o,r.z),s=m*.5+h*.5;return c.z=p*s,c.multiply(l),c}storeRendererState(e){const t=new d.Vector2;e.getSize(t);const i=new d.Vector4;e.getViewport(i);const r=new d.Vector4;e.getScissor(r);const l=e.getClearColor(new d.Color),o=e.getClearAlpha();return{size:t,pixelRatio:e.getPixelRatio(),viewport:i,scissor:r,scissorTest:e.getScissorTest(),autoClear:e.autoClear,target:e.getRenderTarget(),clearColor:l,clearAlpha:o}}applyRendererState(e,t,i,r){if(e.setPixelRatio(1),e.setSize(t,i,!1),e.setViewport(0,0,t,i),e.setScissor(0,0,t,i),e.setScissorTest(!1),e.autoClear=!0,r!==void 0)if(r===null){const l=e.getClearColor(new d.Color);e.setClearColor(l,0)}else r instanceof d.Color?e.setClearColor(r,1):e.setClearColor(new d.Color(r),1);else{const l=e.getClearColor(new d.Color);e.setClearColor(l,0)}}restoreRendererState(e,t){e.setPixelRatio(t.pixelRatio),e.setSize(t.size.x,t.size.y,!1),e.setViewport(t.viewport.x,t.viewport.y,t.viewport.z,t.viewport.w),e.setScissor(t.scissor.x,t.scissor.y,t.scissor.z,t.scissor.w),e.setScissorTest(t.scissorTest),e.autoClear=t.autoClear,e.setRenderTarget(t.target),e.setClearColor(t.clearColor,t.clearAlpha)}readPixels(e,t,i,r){const l=i*r*4;(!this.pixelBuffer||this.pixelBuffer.length!==l)&&(this.pixelBuffer=new Uint8Array(l)),e.readRenderTargetPixels(t,0,0,i,r,this.pixelBuffer);const o=this.ensureCanvas(i,r),c=o.getContext("2d");if(!c)throw new Error("TriViewCapture: failed to get 2D context.");const h=c.createImageData(i,r),m=h.data,p=this.pixelBuffer;for(let s=0;s<r;s+=1){const u=(r-s-1)*i*4,g=s*i*4;m.set(p.subarray(u,u+i*4),g)}return c.putImageData(h,0,0),o.toDataURL("image/png")}ensureCanvas(e,t){if(typeof document>"u")throw new Error("TriViewCapture: document is not available in this environment.");return this.canvas||(this.canvas=document.createElement("canvas")),(this.canvas.width!==e||this.canvas.height!==t)&&(this.canvas.width=e,this.canvas.height=t),this.canvas}}const Pl="shop-components",Rl="0.2.7",Il="Shop components",El="dist/shop-components.umd.js",Fl="dist/shop-components.mjs",Dl="dist/main.d.ts",Bl={dts:"tsc --emitDeclarationOnly & tsc & storybook build -o dist",test:'echo "Error: no test specified" && exit 1',dev:"vite dev --open",storybook:"storybook dev -p 6006",build:"storybook build -o dist",vite:"vite build",version:"auto-changelog -p && git add CHANGELOG.md"},Ll=["dist","package.json"],kl=[],Ol="machengda<machengda@seer-group.com>",zl="ISC",Vl={"@needle-tools/gltf-progressive":"^3.3.5","auto-changelog":"^2.4.0",vite:"5.1.6","vite-plugin-dts":"^3.7.3"},Ul={"string-width":"4.2.3"},Hl={"@nodetoy/three-nodetoy":"^0.1.36","@tweakpane/core":"^2.0.3","@tweenjs/tween.js":"^23.1.2","@types/bezier-js":"^4.1.1","@types/howler":"^2.2.11","@types/three":"0.180.0","bezier-js":"^6.1.4",eventemitter3:"^5.0.1",howler:"^2.2.4","stats-fps.js":"0.0.6",stylus:"^0.63.0",terser:"^5.44.0",three:"0.180.0","three-gpu-pathtracer":"0.0.23","three-mesh-bvh":"^0.7.5","troika-three-text":"^0.49.1",tweakpane:"^4.0.3"},Nl={name:Pl,version:Rl,description:Il,main:El,module:Fl,types:Dl,scripts:Bl,files:Ll,keywords:kl,author:Ol,license:zl,devDependencies:Vl,resolutions:Ul,dependencies:Hl};function Ls(){const n="Nebular Engin",e=Nl.version,t=`%c ${n} %c v${e} `;console.log(t,"background:#111827;color:#ffffff;padding:4px 10px;border-radius:4px 0 0 4px;font-weight:700;","background:#10B981;color:#ffffff;padding:4px 10px;border-radius:0 4px 4px 0;font-weight:700;")}const ks="__SHOP_COMPONENTS_BANNER_PRINTED__";try{const n=globalThis;n[ks]||(n[ks]=!0,Ls())}catch{Ls()}exports.Amr=er;exports.Line=sa;exports.Logo=vi;exports.SGLBLoader=Vt;exports.SLOT_EVENTS=H;exports.Scene3D=Ml;exports.Skin=Mi;exports.Slot=gi;exports.SlotState=lr;exports.TriViewCapture=cr;exports.arrayBufferToUrl=pi;exports.calculateArrayAverage=qs;exports.calculateFocalLength=To;exports.createSGLBFile=Bo;exports.downloadBlob=Ao;exports.dracoExporter=Do;exports.font=Tl;exports.gltfExporter=Zs;exports.gltfLoader=ut;exports.imageBitmapToUrl=mi;exports.isAppleDevice=Ys;exports.textureLoader=Oi;
|