@thinkersteps_labs/3d-viewer-core 1.0.1 → 1.1.0

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/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var zi=Object.defineProperty;var Ui=(n,t,e)=>t in n?zi(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var ee=(n,t,e)=>Ui(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("three"),ri=require("three/examples/jsm/loaders/GLTFLoader.js"),si=require("three/examples/jsm/loaders/DRACOLoader.js"),ki=require("three/examples/jsm/loaders/STLLoader.js"),Gi=require("three/examples/jsm/loaders/OBJLoader.js"),Oi=require("three/examples/jsm/loaders/MTLLoader.js"),Hi=require("three/examples/jsm/exporters/GLTFExporter.js"),Sn=require("three/examples/jsm/loaders/RGBELoader.js"),Tn=require("three/examples/jsm/loaders/EXRLoader.js"),qi=require("three/examples/jsm/controls/OrbitControls.js");function $i(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const v=$i(B);class Rt extends Error{constructor(e){super(`Unsupported format: "${e}"`);ee(this,"format");this.name="UnsupportedFormatError",this.format=e,Object.setPrototypeOf(this,Rt.prototype)}}class He extends Error{constructor(e,i){super(e);ee(this,"cause");this.name="CorruptFileError",this.cause=i,Object.setPrototypeOf(this,He.prototype)}}class tt extends Error{constructor(e,i,r){super(e);ee(this,"status");ee(this,"url");this.name="NetworkError",this.status=i,this.url=r,Object.setPrototypeOf(this,tt.prototype)}}function Ft(n){n.position.set(0,0,0),n.scale.set(1,1,1),n.updateMatrixWorld(!0);const t=new v.Box3().setFromObject(n),e=t.getCenter(new v.Vector3),i=t.getSize(new v.Vector3),r=Math.max(i.x,i.y,i.z),o=r>0?1/r:1;n.scale.setScalar(o),n.position.sub(e.multiplyScalar(o)),n.updateMatrixWorld(!0)}const dn="https://www.gstatic.com/draco/versioned/decoders/1.5.6/";if(typeof globalThis.FileReader>"u"){class n{constructor(){ee(this,"result",null);ee(this,"onloadend",null);ee(this,"onload",null);ee(this,"onerror",null)}readAsArrayBuffer(e){e.arrayBuffer().then(i=>{var r,o;this.result=i,(r=this.onload)==null||r.call(this),(o=this.onloadend)==null||o.call(this)},i=>{var r,o;(r=this.onerror)==null||r.call(this,i),(o=this.onloadend)==null||o.call(this)})}readAsDataURL(e){e.arrayBuffer().then(i=>{var s,a;const r=globalThis.Buffer,o=r?r.from(i).toString("base64"):"";this.result=`data:${e.type};base64,${o}`,(s=this.onload)==null||s.call(this),(a=this.onloadend)==null||a.call(this)},i=>{var r,o;(r=this.onerror)==null||r.call(this,i),(o=this.onloadend)==null||o.call(this)})}}globalThis.FileReader=n}const Wi=50*1024*1024;async function Yi(n,t){const e=[];switch(n.data.byteLength>Wi&&e.push("File exceeds 50 MB; performance may be affected"),n.format){case"glb":case"gltf":return ji(n,e,t);case"stl":return Xi(n,e);case"obj":return Ki(n,e)}}async function ji(n,t,e){const i=new ri.GLTFLoader,r=new si.DRACOLoader;r.setDecoderPath(e??dn),i.setDRACOLoader(r);try{const o=await new Promise((s,a)=>{i.parse(n.data,"",s,a)});return r.dispose(),Ft(o.scene),{scene:o.scene,warnings:t}}catch(o){throw r.dispose(),new He("Failed to parse GLTF/GLB",o)}}function Xi(n,t){const e=new ki.STLLoader;let i;try{i=e.parse(n.data)}catch(a){throw new He("Failed to parse STL",a)}const r=new v.MeshPhysicalMaterial({name:"metal",color:12632256,metalness:1,roughness:.1,envMapIntensity:1}),o=new v.Mesh(i,r);o.name="metal";const s=new v.Group;return s.add(o),Ft(s),{scene:s,warnings:t}}async function Ki(n,t){n.mtlData||t.push("No material file provided; default material applied");let e;if(n.mtlData){const o=new Oi.MTLLoader,s=new TextDecoder().decode(n.mtlData);try{e=o.parse(s,""),e.preload()}catch{t.push("Failed to parse MTL file; default material applied"),e=void 0}}const i=new Gi.OBJLoader;e&&i.setMaterials(e);let r;try{const o=new TextDecoder().decode(n.data);r=i.parse(o)}catch(o){throw new He("Failed to parse OBJ",o)}return Ft(r),{scene:r,warnings:t}}async function Ji(n){const t=new Hi.GLTFExporter;return new Promise((e,i)=>{t.parse(n,r=>{if(r instanceof ArrayBuffer)e(r);else{const o=JSON.stringify(r),s=new TextEncoder().encode(o);e(s.buffer)}},i,{binary:!0})})}class Zi{constructor(){ee(this,"_listeners",new Map)}on(t,e){return this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var i;(i=this._listeners.get(t))==null||i.delete(e)}emit(t,e){var i;(i=this._listeners.get(t))==null||i.forEach(r=>{try{r(e)}catch(o){console.error(`[3d-viewer] uncaught listener error on "${String(t)}":`,o)}})}clear(){this._listeners.clear()}}const Qi={".stl":"stl",".obj":"obj",".glb":"glb",".gltf":"gltf"},eo={"model/gltf-binary":"glb","model/gltf+json":"gltf"};function to(n){try{const t=new URL(n,"http://dummy").pathname,e=t.lastIndexOf(".");if(e===-1)return null;const i=t.slice(e).toLowerCase();return Qi[i]??null}catch{return null}}function no(n){const t=n.split(";")[0].trim().toLowerCase();return eo[t]??null}function Bn(n){if(n.byteLength<4)return null;const t=new Uint8Array(n,0,Math.min(n.byteLength,80));return t[0]===103&&t[1]===108&&t[2]===84&&t[3]===70?"glb":t[0]===123?"gltf":String.fromCharCode(...t.slice(0,5)).toLowerCase()==="solid"?"stl":null}async function Cn(n){const t=new Uint8Array(n);if(t.length>=2&&t[0]===31&&t[1]===139&&typeof DecompressionStream<"u")try{const e=new DecompressionStream("gzip"),i=new Blob([n]).stream().pipeThrough(e),r=await new Response(i).arrayBuffer();if(r.byteLength>0)return r}catch(e){console.warn("[fetchSource] Decompression failed, proceeding with original buffer:",e)}return n}async function io(n,t){if("data"in n){let s=n.data instanceof Blob?await n.data.arrayBuffer():n.data;s=await Cn(s);const a=n.mtlData instanceof Blob?await n.mtlData.arrayBuffer():n.mtlData,c=n.format||Bn(s)||"glb";return{data:s,mtlData:a,format:c}}let e=n.format??to(n.url);const i=await fetch(n.url,{headers:n.headers,signal:t}).catch(s=>{throw s.name==="AbortError"?s:new tt(`Fetch failed: ${s.message}`,void 0,n.url)});if(!i.ok)throw new tt(`HTTP ${i.status}`,i.status,n.url);if(!e){const s=i.headers.get("content-type")??"";e=no(s)}let r=await i.arrayBuffer();if(r=await Cn(r),e||(e=Bn(r)),!e)throw new Rt("unknown");let o;if(n.mtlUrl){const s=await fetch(n.mtlUrl,{headers:n.headers,signal:t});s.ok&&(o=await s.arrayBuffer())}return{data:r,mtlData:o,format:e}}const oo=["glb","gltf","obj","stl"];function ai(n){var i;const e=(i=n.split("?")[0].split("#")[0].split(".").pop())==null?void 0:i.toLowerCase();return e&&oo.includes(e)?e:"glb"}function ro(n){if(!n)return null;if(typeof n=="string"){const t=n.trim();return t?{url:t,format:ai(t)}:null}return n}async function ci(n,t,e,i){e==null||e(0);const r=await io(n,t);e==null||e(.3);const{scene:o,warnings:s}=await Yi(r,i==null?void 0:i.dracoDecoderPath);e==null||e(.7);const a=r.format==="glb"?r.data:await Ji(o);e==null||e(1);let c=0;return o.traverse(u=>{u.isMesh&&c++}),{glb:a,sourceFormat:r.format,meshCount:c,warnings:s}}const so=["stone","diamond","gem","jewel","crystal"],ao=["metal","gold","silver","platinum","band","ring","prong","shank"];function In(n,t){const e=n.toLowerCase();return t.some(i=>e.includes(i))}function Pn(n){return n.trim().replace(/[^a-zA-Z0-9_-]/g,"_")}function co(n,t,e){var a,c;if(typeof((a=n.userData)==null?void 0:a.partId)=="string"&&n.userData.partId.trim()){const u=n.userData.partId.trim();return e.add(u),u}if(typeof((c=n.userData)==null?void 0:c.id)=="string"&&n.userData.id.trim()){const u=n.userData.id.trim();return e.add(u),u}if(n.name&&n.name.trim()){const u=n.name.trim();if(!e.has(u))return e.add(u),u}let i=n.name?n.name.trim():"mesh",r=n.parent;for(;r&&r!==t;)r.name&&r.name.trim()&&(i=`${r.name.trim()}/${i}`),r=r.parent;let o=i,s=1;for(;e.has(o);)o=`${i}_${s++}`;return e.add(o),o}function lo(n){var r,o,s;if(Array.isArray((r=n.userData)==null?void 0:r.originalSlots)&&n.userData.originalSlots.length>0)return n.userData.originalSlots;if(Array.isArray(n.material))return n.material.map((a,c)=>{var f,l;const u=((f=a==null?void 0:a.name)==null?void 0:f.trim())||`Material_${c}`;return{slotId:typeof((l=a==null?void 0:a.userData)==null?void 0:l.slotId)=="string"&&a.userData.slotId||`slot_${c}_${Pn(u)}`,materialName:u,index:c}});const t=n.material,e=((o=t==null?void 0:t.name)==null?void 0:o.trim())||(n.name?`${n.name}_mat`:"default");return[{slotId:typeof((s=t==null?void 0:t.userData)==null?void 0:s.slotId)=="string"&&t.userData.slotId||`slot_0_${Pn(e)}`,materialName:e,index:0}]}function uo(n,t){const e=`${n} ${t}`,i=In(e,so),r=In(e,ao);return i?"stone":"metal"}function En(n,t){const e=[],i=new Set;return n.traverse(r=>{var l;if(!(r instanceof v.Mesh))return;const o=r,s=co(o,n,i);o.userData.partId=s;const a=lo(o);o.userData.originalSlots=a;const c=((l=a[0])==null?void 0:l.materialName)??"";o.userData.originalMaterialName=c;const u=a.map(d=>d.materialName).join(" "),m=o.uuid in t||s in t,f=t[s]??t[o.uuid];m&&f?e.push({meshId:o.uuid,partId:s,meshName:o.name,materialName:c,slots:a,type:f,overridden:!0}):e.push({meshId:o.uuid,partId:s,meshName:o.name,materialName:c,slots:a,type:uo(o.name,u),overridden:!1})}),e}function Rn(n){const t=new Map;for(const e of n)for(const i of e.slots){const r=t.get(i.slotId);r?(r.partIds.includes(e.partId)||r.partIds.push(e.partId),r.meshIds.includes(e.meshId)||r.meshIds.push(e.meshId),r.type!=="stone"&&e.type==="stone"&&(r.type="stone")):t.set(i.slotId,{slotId:i.slotId,name:i.materialName,type:e.type,partIds:[e.partId],meshIds:[e.meshId]})}return Array.from(t.values())}const ge=[{id:"yellow-gold-18k",label:"18K Yellow Gold",hex:"#ffd566",metalness:1,roughness:.04,category:"gold",specularColor:"#fffdbf",density:15500,thumbnail:"/thumbnails/yellow-gold-18k.svg"},{id:"yellow-gold-14k",label:"14K Yellow Gold",hex:"#fed882",metalness:1,roughness:.05,category:"gold",specularColor:"#fffec9",density:13500,thumbnail:"/thumbnails/yellow-gold-14k.svg"},{id:"pure-gold-24k",label:"24K Pure Gold",hex:"#ffe496",metalness:1,roughness:.03,category:"gold",specularColor:"#fffdbf",density:19320,source:"physicallybased.info/gold",thumbnail:"/thumbnails/pure-gold-24k.svg"},{id:"rose-gold-18k",label:"18K Rose Gold",hex:"#e8927c",metalness:1,roughness:.04,category:"gold",specularColor:"#ffd7cb",density:15400,thumbnail:"/thumbnails/rose-gold-18k.svg"},{id:"rose-gold-14k",label:"14K Rose Gold",hex:"#f1a998",metalness:1,roughness:.05,category:"gold",specularColor:"#ffe4db",density:13300,thumbnail:"/thumbnails/rose-gold-14k.svg"},{id:"white-gold-18k",label:"18K White Gold",hex:"#f5f6f8",metalness:1,roughness:.03,category:"gold",specularColor:"#ffffff",density:15600,thumbnail:"/thumbnails/white-gold-18k.svg"},{id:"platinum-950",label:"Platinum 950",hex:"#e3ded7",metalness:1,roughness:.04,category:"platinum-silver",specularColor:"#edebe6",density:21450,source:"physicallybased.info/platinum",thumbnail:"/thumbnails/platinum-950.svg"},{id:"silver-925",label:"Sterling Silver 925",hex:"#fefdfc",metalness:1,roughness:.05,category:"platinum-silver",specularColor:"#ffffff",density:10360,source:"physicallybased.info/silver",thumbnail:"/thumbnails/silver-925.svg"},{id:"titanium",label:"Titanium",hex:"#b1aaa2",metalness:1,roughness:.1,category:"alternative",specularColor:"#c8c3bd",density:4506,source:"physicallybased.info/titanium",thumbnail:"/thumbnails/titanium.svg"},{id:"black-ruthenium",label:"Black Ruthenium",hex:"#28282c",metalness:.95,roughness:.06,category:"alternative",specularColor:"#444448",density:12450,thumbnail:"/thumbnails/black-ruthenium.svg"},{id:"rmj-custom-yellow-gold",label:"RMJ Custom Yellow Gold",hex:"#ffc766",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-custom-yellow-gold.svg"},{id:"rmj-custom-rose-gold",label:"RMJ Custom Rose Gold",hex:"#ffb6a3",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-custom-rose-gold.svg"},{id:"rmj-white-gold-polished",label:"RMJ White Gold Polished",hex:"#c2c2c3",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-white-gold-polished.svg"},{id:"rmj-gold-polished",label:"RMJ Gold Polished (18K)",hex:"#e5b377",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-gold-polished.svg"},{id:"rmj-rose-gold-polished",label:"RMJ Rose Gold Polished",hex:"#f2af83",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-rose-gold-polished.svg"},{id:"rmj-gold-22k",label:"RMJ Gold 22K",hex:"#eaa958",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-gold-22k.svg"},{id:"rmj-gold-14k",label:"RMJ Gold 14K",hex:"#d6af80",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-gold-14k.svg"},{id:"rmj-gold-09k",label:"RMJ Gold 9K",hex:"#d4b38c",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-gold-09k.svg"},{id:"rmj-silver-polished",label:"RMJ Silver Polished",hex:"#dedede",metalness:1,roughness:.1,category:"platinum-silver",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-silver-polished.svg"},{id:"rmj-platinum-polished",label:"RMJ Platinum Polished",hex:"#b9bbbc",metalness:1,roughness:0,category:"platinum-silver",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-platinum-polished.svg"},{id:"yellow-gold",label:"Yellow Gold",hex:"#ffc766",metalness:1,roughness:.06,thumbnail:"/thumbnails/yellow-gold.svg"},{id:"rose-gold",label:"Rose Gold",hex:"#ffb6a3",metalness:1,roughness:.06,thumbnail:"/thumbnails/rose-gold.svg"},{id:"white-gold",label:"White Gold",hex:"#f0f0f0",metalness:1,roughness:.05,thumbnail:"/thumbnails/white-gold.svg"},{id:"platinum",label:"Platinum",hex:"#e5e5e5",metalness:1,roughness:.05,thumbnail:"/thumbnails/platinum.svg"},{id:"silver",label:"Silver",hex:"#dcdcdc",metalness:1,roughness:.08,thumbnail:"/thumbnails/silver.svg"}],le=[{id:"diamond-d",label:"White Diamond",hex:"#ffffff",ior:2.417,transmission:.98,roughness:0,category:"diamond",grade:"D-F Colorless",dispersion:.024,absorptionFactor:0,ambientFloor:.05,source:"physicallybased.info/diamond",thumbnail:"/thumbnails/diamond-d.svg"},{id:"diamond-gh",label:"Near Colorless Diamond",hex:"#fbf9f5",ior:2.417,transmission:.97,roughness:0,category:"diamond",grade:"G-H Near Colorless",dispersion:.012,absorptionFactor:0,ambientFloor:.05,thumbnail:"/thumbnails/diamond-gh.svg"},{id:"diamond-fancy-yellow",label:"Yellow Diamond",hex:"#fdd835",ior:2.417,transmission:.95,roughness:0,category:"diamond",grade:"Fancy Yellow",dispersion:.01,absorptionFactor:.11,thumbnail:"/thumbnails/diamond-fancy-yellow.svg"},{id:"diamond-fancy-pink",label:"Pink Diamond",hex:"#f472b6",ior:2.417,transmission:.94,roughness:0,category:"diamond",grade:"Fancy Pink",dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-pink.svg"},{id:"diamond-fancy-blue",label:"Blue Diamond",hex:"#38bdf8",ior:2.417,transmission:.94,roughness:0,category:"diamond",grade:"Fancy Blue",dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-blue.svg"},{id:"diamond-fancy-green",label:"Green Diamond",hex:"#34d399",ior:2.417,transmission:.94,roughness:0,category:"diamond",grade:"Fancy Green",dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-green.svg"},{id:"diamond-fancy-champagne",label:"Champagne Diamond",hex:"#c28b51",ior:2.417,transmission:.93,roughness:0,category:"diamond",grade:"Fancy Champagne",dispersion:.01,absorptionFactor:.18,thumbnail:"/thumbnails/diamond-fancy-champagne.svg"},{id:"diamond-fancy-black",label:"Black Diamond",hex:"#151515",ior:2.417,transmission:0,roughness:.05,category:"diamond",grade:"Fancy Black",dispersion:0,absorptionFactor:0,thumbnail:"/thumbnails/diamond-fancy-black.svg"},{id:"ruby",label:"Ruby",hex:"#e14276",ior:1.77,transmission:.88,roughness:.03,category:"gemstone",dispersion:0,absorptionFactor:.5,thumbnail:"/thumbnails/ruby.svg"},{id:"sapphire",label:"Sapphire",hex:"#1a4fb4",ior:1.77,transmission:.88,roughness:.03,category:"gemstone",dispersion:0,absorptionFactor:.45,source:"physicallybased.info/sapphire",thumbnail:"/thumbnails/sapphire.svg"},{id:"emerald",label:"Emerald",hex:"#20cc95",ior:1.58,transmission:.9,roughness:.04,category:"gemstone",dispersion:0,absorptionFactor:.4,thumbnail:"/thumbnails/emerald.svg"},{id:"aquamarine",label:"Aquamarine",hex:"#5eead4",ior:1.577,transmission:.94,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:.1,thumbnail:"/thumbnails/aquamarine.svg"},{id:"amethyst",label:"Amethyst",hex:"#9333ea",ior:1.544,transmission:.91,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:.35,source:"physicallybased.info/quartz",thumbnail:"/thumbnails/amethyst.svg"},{id:"tanzanite",label:"Tanzanite",hex:"#6366f1",ior:1.691,transmission:.9,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:.42,thumbnail:"/thumbnails/tanzanite.svg"},{id:"rmj-diamond-d-colorless",label:"RMJ Diamond D Colorless",hex:"#ececec",ior:2.4,transmission:.98,roughness:0,category:"diamond",dispersion:.004,absorptionFactor:1,boostFactors:[2,2,2],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-diamond-d-colorless.svg"},{id:"rmj-ruby-1",label:"RMJ Ruby 1",hex:"#e14276",ior:1.77,transmission:.88,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:1.6,boostFactors:[1.3,.16,.9],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-ruby-1.svg"},{id:"rmj-emerald-1",label:"RMJ Emerald 1",hex:"#20cc95",ior:1.577,transmission:.9,roughness:0,category:"gemstone",dispersion:.012,absorptionFactor:1,boostFactors:[.892,.892,.986],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-emerald-1.svg"},{id:"rmj-sapphire-cabachon-2",label:"RMJ Sapphire Cabochon 2",hex:"#45b1e1",ior:1.66,transmission:.88,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:2.51,boostFactors:[1,1,1],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-sapphire-cabachon-2.svg"},{id:"rmj-diamond-pink-2",label:"RMJ Diamond Pink 2",hex:"#f1bcd5",ior:2.6,transmission:.94,roughness:0,category:"diamond",dispersion:.012,absorptionFactor:1,boostFactors:[1.3,1,1],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-diamond-pink-2.svg"},{id:"rmj-diamond-yellow-2",label:"RMJ Diamond Yellow 2",hex:"#fce88c",ior:2.6,transmission:.94,roughness:0,category:"diamond",dispersion:.012,absorptionFactor:1.3,boostFactors:[1,1,1],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-diamond-yellow-2.svg"},{id:"rmj-diamond-blue-2",label:"RMJ Diamond Blue 2",hex:"#80c9fc",ior:2.6,transmission:.94,roughness:0,category:"diamond",dispersion:.013,absorptionFactor:1,boostFactors:[.9,1,1],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-diamond-blue-2.svg"},{id:"diamond",label:"White Diamond",hex:"#ffffff",ior:2.417,transmission:.95,roughness:.02,dispersion:.012,absorptionFactor:0,ambientFloor:.05,thumbnail:"/thumbnails/diamond-d.svg"},{id:"yellow-diamond",label:"Yellow Diamond",hex:"#fcd34d",ior:2.42,transmission:.94,roughness:.02,dispersion:.01,absorptionFactor:.11,thumbnail:"/thumbnails/diamond-fancy-yellow.svg"},{id:"pink-diamond",label:"Pink Diamond",hex:"#f472b6",ior:2.42,transmission:.94,roughness:.02,dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-pink.svg"},{id:"blue-diamond",label:"Blue Diamond",hex:"#60a5fa",ior:2.42,transmission:.94,roughness:.02,dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-blue.svg"},{id:"black-diamond",label:"Black Diamond",hex:"#1a1a1a",ior:2.42,transmission:0,roughness:.05,dispersion:0,absorptionFactor:0,thumbnail:"/thumbnails/diamond-fancy-black.svg"}],mn=ge,pn=le,fo=ge.filter(n=>n.category!==void 0&&!n.id.startsWith("rmj-"));ge.filter(n=>n.id.startsWith("rmj-"));const mo=le.filter(n=>n.category==="diamond"&&!n.id.startsWith("rmj-")&&n.id.startsWith("diamond-")),po=le.filter(n=>n.category==="gemstone"&&!n.id.startsWith("rmj-"));le.filter(n=>n.id.startsWith("rmj-"));const ho=new Set(["yellow-gold","rose-gold","white-gold","platinum","silver"]),yo=new Set(["diamond","yellow-diamond","pink-diamond","blue-diamond","black-diamond"]),go=ge.filter(n=>!ho.has(n.id)),vo=le.filter(n=>!yo.has(n.id));function bo(n){if(!n)return;const t=n.toLowerCase().trim();return ge.find(e=>e.id.toLowerCase()===t||e.hex.toLowerCase()===t)}function xo(n){if(!n)return;const t=n.toLowerCase().trim();return le.find(e=>e.id.toLowerCase()===t||e.hex.toLowerCase()===t)}const Fn=new WeakMap;function wo(n){var p,x;n.boundingSphere||n.computeBoundingSphere();const t=(p=n.boundingSphere)!=null&&p.center?n.boundingSphere.center.clone():new v.Vector3,e=((x=n.boundingSphere)==null?void 0:x.radius)??1,i=Math.max(e,.01),r=n.getAttribute("position");if(!r||r.count===0)return{centroid:t,radius:i,triangleCount:0,starConvexFailureArea:1,isBakeable:!1,flippedWinding:!1};const o=n.getIndex(),s=o?o.count/3:r.count/3;let a=0,c=0,u=0;const m=new v.Vector3,f=new v.Vector3,l=new v.Vector3,d=new v.Vector3,y=new v.Vector3,w=new v.Vector3,b=new v.Vector3;for(let g=0;g<s;g++){const A=o?o.getX(g*3):g*3,T=o?o.getX(g*3+1):g*3+1,I=o?o.getX(g*3+2):g*3+2;m.fromBufferAttribute(r,A).sub(t).divideScalar(i),f.fromBufferAttribute(r,T).sub(t).divideScalar(i),l.fromBufferAttribute(r,I).sub(t).divideScalar(i),d.subVectors(f,m),y.subVectors(l,m),w.crossVectors(d,y);const E=w.length();if(E<1e-12)continue;const S=E*.5;a+=S,w.divideScalar(E);const P=m.dot(w);b.crossVectors(f,l),u+=m.dot(b)/6,P<=1e-4&&(c+=S)}const M=a>0?c/a:1,h=u<0;return{centroid:t,radius:i,triangleCount:s,starConvexFailureArea:M,isBakeable:M<=.005&&!isNaN(a)&&a>0,flippedWinding:h}}function Mo(n,t){const i=(n.getIndex()?n.toNonIndexed():n.clone()).getAttribute("position"),r=i.count,o=new Float32Array(r*4),s=new v.Vector3,a=new v.Vector3,c=new v.Vector3,u=new v.Vector3,m=new v.Vector3,f=new v.Vector3,l=t.flippedWinding?-1:1;for(let d=0;d<r;d+=3){s.fromBufferAttribute(i,d).sub(t.centroid).divideScalar(t.radius),a.fromBufferAttribute(i,d+1).sub(t.centroid).divideScalar(t.radius),c.fromBufferAttribute(i,d+2).sub(t.centroid).divideScalar(t.radius),u.subVectors(a,s),m.subVectors(c,s),f.crossVectors(u,m).multiplyScalar(l);const y=f.length();y>1e-12?f.divideScalar(y):f.set(0,1,0);const w=s.dot(f);for(let b=0;b<3;b++){const M=(d+b)*4;o[M]=f.x,o[M+1]=f.y,o[M+2]=f.z,o[M+3]=w}}return o}function Ao(n,t){const e=Fn.get(n);if(e)return e;const i=n.getAttribute("position"),r=n.getIndex();let o=2166136261;const s=u=>{o^=u&255,o=Math.imul(o,16777619),o^=u>>8&255,o=Math.imul(o,16777619),o^=u>>16&255,o=Math.imul(o,16777619),o^=u>>24&255,o=Math.imul(o,16777619)};if(s(t.triangleCount),r)for(let u=0;u<r.count;u++)s(r.getX(u));const a=new v.Vector3;for(let u=0;u<i.count;u++)a.fromBufferAttribute(i,u).sub(t.centroid).divideScalar(t.radius),s(Math.round(a.x*1e4)),s(Math.round(a.y*1e4)),s(Math.round(a.z*1e4));const c=(o>>>0).toString(16);return Fn.set(n,c),c}const li=0,So=1,ui=2,_n=2,Ut=1.25,Dn=1,Z=6*4+4+4,j=Z/4,hn=65535,To=hn<<16,Tt=Math.pow(2,-24),yn=Symbol("SKIP_GENERATION"),fi={strategy:li,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[yn]:!1};function q(n,t,e){return e.min.x=t[n],e.min.y=t[n+1],e.min.z=t[n+2],e.max.x=t[n+3],e.max.y=t[n+4],e.max.z=t[n+5],e}function Jt(n){let t=-1,e=-1/0;for(let i=0;i<3;i++){const r=n[i+3]-n[i];r>e&&(e=r,t=i)}return t}function Nn(n,t){t.set(n)}function Ln(n,t,e){let i,r;for(let o=0;o<3;o++){const s=o+3;i=n[o],r=t[o],e[o]=i<r?i:r,i=n[s],r=t[s],e[s]=i>r?i:r}}function ut(n,t,e){for(let i=0;i<3;i++){const r=t[n+2*i],o=t[n+2*i+1],s=r-o,a=r+o;s<e[i]&&(e[i]=s),a>e[i+3]&&(e[i+3]=a)}}function We(n){const t=n[3]-n[0],e=n[4]-n[1],i=n[5]-n[2];return 2*(t*e+e*i+i*t)}function $(n,t){return t[n+15]===hn}function X(n,t){return t[n+6]}function Q(n,t){return t[n+14]}function K(n){return n+j}function J(n,t){const e=t[n+6];return n+e*j}function _t(n,t){return t[n+7]}function kt(n,t,e,i,r){let o=1/0,s=1/0,a=1/0,c=-1/0,u=-1/0,m=-1/0,f=1/0,l=1/0,d=1/0,y=-1/0,w=-1/0,b=-1/0;const M=n.offset||0;for(let h=(t-M)*6,p=(t+e-M)*6;h<p;h+=6){const x=n[h+0],g=n[h+1],A=x-g,T=x+g;A<o&&(o=A),T>c&&(c=T),x<f&&(f=x),x>y&&(y=x);const I=n[h+2],E=n[h+3],S=I-E,P=I+E;S<s&&(s=S),P>u&&(u=P),I<l&&(l=I),I>w&&(w=I);const C=n[h+4],F=n[h+5],_=C-F,V=C+F;_<a&&(a=_),V>m&&(m=V),C<d&&(d=C),C>b&&(b=C)}i[0]=o,i[1]=s,i[2]=a,i[3]=c,i[4]=u,i[5]=m,r[0]=f,r[1]=l,r[2]=d,r[3]=y,r[4]=w,r[5]=b}const pe=32,Bo=(n,t)=>n.candidate-t.candidate,Me=new Array(pe).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),ft=new Float32Array(6);function Co(n,t,e,i,r,o){let s=-1,a=0;if(o===li)s=Jt(t),s!==-1&&(a=(t[s]+t[s+3])/2);else if(o===So)s=Jt(n),s!==-1&&(a=Io(e,i,r,s));else if(o===ui){const c=We(n);let u=Ut*r;const m=e.offset||0,f=(i-m)*6,l=(i+r-m)*6;for(let d=0;d<3;d++){const y=t[d],M=(t[d+3]-y)/pe;if(r<pe/4){const h=[...Me];h.length=r;let p=0;for(let g=f;g<l;g+=6,p++){const A=h[p];A.candidate=e[g+2*d],A.count=0;const{bounds:T,leftCacheBounds:I,rightCacheBounds:E}=A;for(let S=0;S<3;S++)E[S]=1/0,E[S+3]=-1/0,I[S]=1/0,I[S+3]=-1/0,T[S]=1/0,T[S+3]=-1/0;ut(g,e,T)}h.sort(Bo);let x=r;for(let g=0;g<x;g++){const A=h[g];for(;g+1<x&&h[g+1].candidate===A.candidate;)h.splice(g+1,1),x--}for(let g=f;g<l;g+=6){const A=e[g+2*d];for(let T=0;T<x;T++){const I=h[T];A>=I.candidate?ut(g,e,I.rightCacheBounds):(ut(g,e,I.leftCacheBounds),I.count++)}}for(let g=0;g<x;g++){const A=h[g],T=A.count,I=r-A.count,E=A.leftCacheBounds,S=A.rightCacheBounds;let P=0;T!==0&&(P=We(E)/c);let C=0;I!==0&&(C=We(S)/c);const F=Dn+Ut*(P*T+C*I);F<u&&(s=d,u=F,a=A.candidate)}}else{for(let x=0;x<pe;x++){const g=Me[x];g.count=0,g.candidate=y+M+x*M;const A=g.bounds;for(let T=0;T<3;T++)A[T]=1/0,A[T+3]=-1/0}for(let x=f;x<l;x+=6){let T=~~((e[x+2*d]-y)/M);T>=pe&&(T=pe-1);const I=Me[T];I.count++,ut(x,e,I.bounds)}const h=Me[pe-1];Nn(h.bounds,h.rightCacheBounds);for(let x=pe-2;x>=0;x--){const g=Me[x],A=Me[x+1];Ln(g.bounds,A.rightCacheBounds,g.rightCacheBounds)}let p=0;for(let x=0;x<pe-1;x++){const g=Me[x],A=g.count,T=g.bounds,E=Me[x+1].rightCacheBounds;A!==0&&(p===0?Nn(T,ft):Ln(T,ft,ft)),p+=A;let S=0,P=0;p!==0&&(S=We(ft)/c);const C=r-p;C!==0&&(P=We(E)/c);const F=Dn+Ut*(S*p+P*C);F<u&&(s=d,u=F,a=g.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${o} used.`);return{axis:s,pos:a}}function Io(n,t,e,i){let r=0;const o=n.offset;for(let s=t,a=t+e;s<a;s++)r+=n[(s-o)*6+i*2];return r/e}class Gt{constructor(){this.boundingData=new Float32Array(6)}}function Po(n,t,e,i,r,o){let s=i,a=i+r-1;const c=o.pos,u=o.axis*2,m=e.offset||0;for(;;){for(;s<=a&&e[(s-m)*6+u]<c;)s++;for(;s<=a&&e[(a-m)*6+u]>=c;)a--;if(s<a){for(let f=0;f<t;f++){let l=n[s*t+f];n[s*t+f]=n[a*t+f],n[a*t+f]=l}for(let f=0;f<6;f++){const l=s-m,d=a-m,y=e[l*6+f];e[l*6+f]=e[d*6+f],e[d*6+f]=y}s++,a--}else return s}}let di,Bt,Zt,mi;const Eo=Math.pow(2,32);function Qt(n){return"count"in n?1:1+Qt(n.left)+Qt(n.right)}function Ro(n,t,e){return di=new Float32Array(e),Bt=new Uint32Array(e),Zt=new Uint16Array(e),mi=new Uint8Array(e),en(n,t)}function en(n,t){const e=n/4,i=n/2,r="count"in t,o=t.boundingData;for(let s=0;s<6;s++)di[e+s]=o[s];if(r)return t.buffer?(mi.set(new Uint8Array(t.buffer),n),n+t.buffer.byteLength):(Bt[e+6]=t.offset,Zt[i+14]=t.count,Zt[i+15]=hn,n+Z);{const{left:s,right:a,splitAxis:c}=t,u=n+Z;let m=en(u,s);const f=n/Z,d=m/Z-f;if(d>Eo)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Bt[e+6]=d,Bt[e+7]=c,en(m,a)}}function Fo(n,t,e,i,r,o){const{maxDepth:s,verbose:a,targetLeafSize:c,_strictLeafSize:u=1/0,strategy:m,onProgress:f}=r,l=n.primitiveBuffer,d=n.primitiveBufferStride,y=new Float32Array(6);let w=!1;const b=new Gt;return kt(t,e,i,b.boundingData,y),h(b,e,i,y),b;function M(p){f&&f((p-o.offset)/o.count)}function h(p,x,g,A=null,T=0){!w&&T>=s&&(w=!0,a&&console.warn(`BVH: Max depth of ${s} reached when generating BVH. Consider increasing maxDepth.`));const I=g>u;if(g<=c&&!I||T>=s)return M(x+g),p.offset=x,p.count=g,p;const E=Co(p.boundingData,A,t,x,g,m);let S=E.axis===-1?-1:Po(l,d,t,x,g,E);if(E.axis===-1||S===x||S===x+g){if(!I)return M(x+g),p.offset=x,p.count=g,p;E.axis=Math.max(0,Jt(p.boundingData)),S=x+Math.max(1,Math.floor(g/2))}p.splitAxis=E.axis;const P=new Gt,C=x,F=S-x;p.left=P,kt(t,C,F,P.boundingData,y),h(P,C,F,y,T+1);const _=new Gt,V=S,k=g-F;return p.right=_,kt(t,V,k,_.boundingData,y),h(_,V,k,y,T+1),p}}function _o(n,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=n.getRootRanges(t.range),r=i[0],o=i[i.length-1],s={offset:r.offset,count:o.offset+o.count-r.offset},a=new Float32Array(6*s.count);a.offset=s.offset,n.computePrimitiveBounds(s.offset,s.count,a),n._roots=i.map(c=>{const u=Fo(n,a,c.offset,c.count,t,s),m=Qt(u),f=new e(Z*m);return Ro(0,u,f),f})}class gn{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class Do{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const O=new Do;let Se,Ge;const Re=[],dt=new gn(()=>new B.Box3);function No(n,t,e,i,r,o){Se=dt.getPrimitive(),Ge=dt.getPrimitive(),Re.push(Se,Ge),O.setBuffer(n._roots[t]);const s=tn(0,n.geometry,e,i,r,o);O.clearBuffer(),dt.releasePrimitive(Se),dt.releasePrimitive(Ge),Re.pop(),Re.pop();const a=Re.length;return a>0&&(Ge=Re[a-1],Se=Re[a-2]),s}function tn(n,t,e,i,r=null,o=0,s=0){const{float32Array:a,uint16Array:c,uint32Array:u}=O;let m=n*2;if($(m,c)){const l=X(n,u),d=Q(m,c);return q(n,a,Se),i(l,d,!1,s,o+n/j,Se)}else{let S=function(C){const{uint16Array:F,uint32Array:_}=O;let V=C*2;for(;!$(V,F);)C=K(C),V=C*2;return X(C,_)},P=function(C){const{uint16Array:F,uint32Array:_}=O;let V=C*2;for(;!$(V,F);)C=J(C,_),V=C*2;return X(C,_)+Q(V,F)};const l=K(n),d=J(n,u);let y=l,w=d,b,M,h,p;if(r&&(h=Se,p=Ge,q(y,a,h),q(w,a,p),b=r(h),M=r(p),M<b)){y=d,w=l;const C=b;b=M,M=C,h=p}h||(h=Se,q(y,a,h));const x=$(y*2,c),g=e(h,x,b,s+1,o+y/j);let A;if(g===_n){const C=S(y),_=P(y)-C;A=i(C,_,!0,s+1,o+y/j,h)}else A=g&&tn(y,t,e,i,r,o,s+1);if(A)return!0;p=Ge,q(w,a,p);const T=$(w*2,c),I=e(p,T,M,s+1,o+w/j);let E;if(I===_n){const C=S(w),_=P(w)-C;E=i(C,_,!0,s+1,o+w/j,p)}else E=I&&tn(w,t,e,i,r,o,s+1);return!!E}}const et=new O.constructor,Ct=new O.constructor,Ae=new gn(()=>new B.Box3),Fe=new B.Box3,_e=new B.Box3,Ot=new B.Box3,Ht=new B.Box3;let qt=!1;function Lo(n,t,e,i){if(qt)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");qt=!0;const r=n._roots,o=t._roots;let s,a=0,c=0;const u=new B.Matrix4().copy(e).invert();for(let m=0,f=r.length;m<f;m++){et.setBuffer(r[m]),c=0;const l=Ae.getPrimitive();q(0,et.float32Array,l),l.applyMatrix4(u);for(let d=0,y=o.length;d<y&&(Ct.setBuffer(o[d]),s=ue(0,0,e,u,i,a,c,0,0,l),Ct.clearBuffer(),c+=o[d].byteLength/Z,!s);d++);if(Ae.releasePrimitive(l),et.clearBuffer(),a+=r[m].byteLength/Z,s)break}return qt=!1,s}function ue(n,t,e,i,r,o=0,s=0,a=0,c=0,u=null,m=!1){let f,l;m?(f=Ct,l=et):(f=et,l=Ct);const d=f.float32Array,y=f.uint32Array,w=f.uint16Array,b=l.float32Array,M=l.uint32Array,h=l.uint16Array,p=n*2,x=t*2,g=$(p,w),A=$(x,h);let T=!1;if(A&&g)m?T=r(X(t,M),Q(t*2,h),X(n,y),Q(n*2,w),c,s+t/j,a,o+n/j):T=r(X(n,y),Q(n*2,w),X(t,M),Q(t*2,h),a,o+n/j,c,s+t/j);else if(A){const I=Ae.getPrimitive();q(t,b,I),I.applyMatrix4(e);const E=K(n),S=J(n,y);q(E,d,Fe),q(S,d,_e);const P=I.intersectsBox(Fe),C=I.intersectsBox(_e);T=P&&ue(t,E,i,e,r,s,o,c,a+1,I,!m)||C&&ue(t,S,i,e,r,s,o,c,a+1,I,!m),Ae.releasePrimitive(I)}else{const I=K(t),E=J(t,M);q(I,b,Ot),q(E,b,Ht);const S=u.intersectsBox(Ot),P=u.intersectsBox(Ht);if(S&&P)T=ue(n,I,e,i,r,o,s,a,c+1,u,m)||ue(n,E,e,i,r,o,s,a,c+1,u,m);else if(S)if(g)T=ue(n,I,e,i,r,o,s,a,c+1,u,m);else{const C=Ae.getPrimitive();C.copy(Ot).applyMatrix4(e);const F=K(n),_=J(n,y);q(F,d,Fe),q(_,d,_e);const V=C.intersectsBox(Fe),k=C.intersectsBox(_e);T=V&&ue(I,F,i,e,r,s,o,c,a+1,C,!m)||k&&ue(I,_,i,e,r,s,o,c,a+1,C,!m),Ae.releasePrimitive(C)}else if(P)if(g)T=ue(n,E,e,i,r,o,s,a,c+1,u,m);else{const C=Ae.getPrimitive();C.copy(Ht).applyMatrix4(e);const F=K(n),_=J(n,y);q(F,d,Fe),q(_,d,_e);const V=C.intersectsBox(Fe),k=C.intersectsBox(_e);T=V&&ue(E,F,i,e,r,s,o,c,a+1,C,!m)||k&&ue(E,_,i,e,r,s,o,c,a+1,C,!m),Ae.releasePrimitive(C)}}return T}const $t=new class{constructor(){let n=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(o,s)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=s,this.buffer=n=o._roots[s],this.uint16Array=e=new Uint16Array(n),this.uint32Array=t=new Uint32Array(n)},this.reset=()=>{this.root=null,this.buffer=n=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=o=>{let s=o*2;for(;!$(s,e);)o=K(o),s=o*2;return X(o,t)},this.getRangeEnd=o=>{let s=o*2;for(;!$(s,e);)o=J(o,t),s=o*2;return X(o,t)+Q(s,e)};const r=(o,s,a)=>{const c=s*2,u=$(c,e);if(!o(a,u,s)&&!u){const f=K(s),l=J(s,t);r(o,f,a+1),r(o,l,a+1)}};this.traverseBuffer=o=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{r(o,0,0)}finally{i=!1}},this.traverse=o=>{this.traverseBuffer((s,a,c)=>{if(a){const u=c*2,m=t[c+6],f=e[u+14];return o(s,a,new Float32Array(n,c*4,6),m,f)}else{const u=_t(c,t);return o(s,a,new Float32Array(n,c*4,6),u)}})}}},Vn=new B.Box3,De=new Float32Array(6);class Vo{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...fi,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),_o(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,r){let o=1/0,s=1/0,a=1/0,c=-1/0,u=-1/0,m=-1/0;for(let f=t,l=t+e;f<l;f++){this.writePrimitiveBounds(f,De,0);const[d,y,w,b,M,h]=De;d<o&&(o=d),b>c&&(c=b),y<s&&(s=y),M>u&&(u=M),w<a&&(a=w),h>m&&(m=h)}return i[r+0]=o,i[r+1]=s,i[r+2]=a,i[r+3]=c,i[r+4]=u,i[r+5]=m,i}computePrimitiveBounds(t,e,i){const r=i.offset||0;for(let o=t,s=t+e;o<s;o++){this.writePrimitiveBounds(o,De,0);const[a,c,u,m,f,l]=De,d=(a+m)/2,y=(c+f)/2,w=(u+l)/2,b=(m-a)/2,M=(f-c)/2,h=(l-u)/2,p=(o-r)*6;i[p+0]=d,i[p+1]=b+(Math.abs(d)+b)*Tt,i[p+2]=y,i[p+3]=M+(Math.abs(y)+M)*Tt,i[p+4]=w,i[p+5]=h+(Math.abs(w)+h)*Tt}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,r=e.length;i<r;i++)e[i]+=t;else{const i=this._roots;for(let r=0;r<i.length;r++){const o=i[r],s=new Uint32Array(o),a=new Uint16Array(o),c=o.byteLength/Z;for(let u=0;u<c;u++){const m=j*u,f=2*m;$(f,a)&&(s[m+6]+=t)}}}}traverse(t,e=0){$t.setBVH(this,e),$t.traverse(t),$t.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const r=t[e],o=new Uint32Array(r),s=new Uint16Array(r),a=new Float32Array(r),c=r.byteLength/Z;for(let u=c-1;u>=0;u--){const m=u*j,f=m*2;if($(f,s)){const d=X(m,o),y=Q(f,s);this.writePrimitiveRangeBounds(d,y,De,0),a.set(De,m)}else{const d=K(m),y=J(m,o);for(let w=0;w<3;w++){const b=a[d+w],M=a[d+w+3],h=a[y+w],p=a[y+w+3];a[m+w]=b<h?b:h,a[m+w+3]=M>p?M:p}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{q(0,new Float32Array(i),Vn),t.union(Vn)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:r,intersectsPrimitive:o,scratchPrimitive:s,iterate:a}=t;if(r&&o){const f=r;r=(l,d,y,w,b)=>f(l,d,y,w,b)?!0:a(l,d,this,o,y,w,s)}else r||(o?r=(f,l,d,y)=>a(f,l,this,o,d,y,s):r=(f,l,d)=>d);let c=!1,u=0;const m=this._roots;for(let f=0,l=m.length;f<l;f++){const d=m[f];if(c=No(this,f,i,r,e,u),c)break;u+=d.byteLength/Z}return c}bvhcast(t,e,i){let{intersectsRanges:r}=i;return Lo(this,t,e,r)}}function zo(){return typeof SharedArrayBuffer<"u"}function Dt(n){return n.index?n.index.count:n.attributes.position.count}function Nt(n){return Dt(n)/3}function pi(n,t=ArrayBuffer){return n>65535?new Uint32Array(new t(4*n)):new Uint16Array(new t(2*n))}function Uo(n,t){if(!n.index){const e=n.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,r=pi(e,i);n.setIndex(new B.BufferAttribute(r,1));for(let o=0;o<e;o++)r[o]=o}}function ko(n,t,e){const i=Dt(n)/e,r=t||n.drawRange,o=r.start/e,s=(r.start+r.count)/e,a=Math.max(0,o),c=Math.min(i,s)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function Go(n,t){return n.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function zn(n,t,e){const i=ko(n,t,e),r=Go(n,e);if(!r.length)return[i];const o=[],s=i.offset,a=i.offset+i.count,c=Dt(n)/e,u=[];for(const l of r){const{offset:d,count:y}=l,w=d,b=isFinite(y)?y:c-d,M=d+b;w<a&&M>s&&(u.push({pos:Math.max(s,w),isStart:!0}),u.push({pos:Math.min(a,M),isStart:!1}))}u.sort((l,d)=>l.pos!==d.pos?l.pos-d.pos:l.type==="end"?-1:1);let m=0,f=null;for(const l of u){const d=l.pos;m!==0&&d!==f&&o.push({offset:f,count:d-f}),m+=l.isStart?1:-1,f=d}return o}function Oo(n,t){const e=n[n.length-1],i=e.offset+e.count>2**16,r=n.reduce((u,m)=>u+m.count,0),o=i?4:2,s=t?new SharedArrayBuffer(r*o):new ArrayBuffer(r*o),a=i?new Uint32Array(s):new Uint16Array(s);let c=0;for(let u=0;u<n.length;u++){const{offset:m,count:f}=n[u];for(let l=0;l<f;l++)a[c+l]=m+l;c+=f}return a}class Ho extends Vo{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!zo())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...fi,...e},e[yn]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const r=zn(e,t.range,i),o=Oo(r,t.useSharedArrayBuffer);this._indirectBuffer=o}else Uo(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new B.Box3))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:zn(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class ve{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,r=-1/0;for(let o=0,s=t.length;o<s;o++){const c=t[o][e];i=c<i?c:i,r=c>r?c:r}this.min=i,this.max=r}setFromPoints(t,e){let i=1/0,r=-1/0;for(let o=0,s=e.length;o<s;o++){const a=e[o],c=t.dot(a);i=c<i?c:i,r=c>r?c:r}this.min=i,this.max=r}isSeparated(t){return this.min>t.max||t.min>this.max}}ve.prototype.setFromBox=function(){const n=new B.Vector3;return function(e,i){const r=i.min,o=i.max;let s=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let u=0;u<=1;u++)for(let m=0;m<=1;m++){n.x=r.x*c+o.x*(1-c),n.y=r.y*u+o.y*(1-u),n.z=r.z*m+o.z*(1-m);const f=e.dot(n);s=Math.min(f,s),a=Math.max(f,a)}this.min=s,this.max=a}}();const qo=function(){const n=new B.Vector3,t=new B.Vector3,e=new B.Vector3;return function(r,o,s){const a=r.start,c=n,u=o.start,m=t;e.subVectors(a,u),n.subVectors(r.end,r.start),t.subVectors(o.end,o.start);const f=e.dot(m),l=m.dot(c),d=m.dot(m),y=e.dot(c),b=c.dot(c)*d-l*l;let M,h;b!==0?M=(f*l-y*d)/b:M=0,h=(f+M*l)/d,s.x=M,s.y=h}}(),vn=function(){const n=new B.Vector2,t=new B.Vector3,e=new B.Vector3;return function(r,o,s,a){qo(r,o,n);let c=n.x,u=n.y;if(c>=0&&c<=1&&u>=0&&u<=1){r.at(c,s),o.at(u,a);return}else if(c>=0&&c<=1){u<0?o.at(0,a):o.at(1,a),r.closestPointToPoint(a,!0,s);return}else if(u>=0&&u<=1){c<0?r.at(0,s):r.at(1,s),o.closestPointToPoint(s,!0,a);return}else{let m;c<0?m=r.start:m=r.end;let f;u<0?f=o.start:f=o.end;const l=t,d=e;if(r.closestPointToPoint(f,!0,t),o.closestPointToPoint(m,!0,e),l.distanceToSquared(f)<=d.distanceToSquared(m)){s.copy(l),a.copy(f);return}else{s.copy(m),a.copy(d);return}}}}(),$o=function(){const n=new B.Vector3,t=new B.Vector3,e=new B.Plane,i=new B.Line3;return function(o,s){const{radius:a,center:c}=o,{a:u,b:m,c:f}=s;if(i.start=u,i.end=m,i.closestPointToPoint(c,!0,n).distanceTo(c)<=a||(i.start=u,i.end=f,i.closestPointToPoint(c,!0,n).distanceTo(c)<=a)||(i.start=m,i.end=f,i.closestPointToPoint(c,!0,n).distanceTo(c)<=a))return!0;const w=s.getPlane(e);if(Math.abs(w.distanceToPoint(c))<=a){const M=w.projectPoint(c,t);if(s.containsPoint(M))return!0}return!1}}(),Wo=["x","y","z"],he=1e-15,Un=he*he;function ae(n){return Math.abs(n)<he}class fe extends B.Triangle{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new B.Vector3),this.satBounds=new Array(4).fill().map(()=>new ve),this.points=[this.a,this.b,this.c],this.plane=new B.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new B.Line3,this.needsUpdate=!0}intersectsSphere(t){return $o(t,this)}update(){const t=this.a,e=this.b,i=this.c,r=this.points,o=this.satAxes,s=this.satBounds,a=o[0],c=s[0];this.getNormal(a),c.setFromPoints(a,r);const u=o[1],m=s[1];u.subVectors(t,e),m.setFromPoints(u,r);const f=o[2],l=s[2];f.subVectors(e,i),l.setFromPoints(f,r);const d=o[3],y=s[3];d.subVectors(i,t),y.setFromPoints(d,r);const w=u.length(),b=f.length(),M=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,w<he?b<he||M<he?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):b<he?M<he?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):M<he&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}fe.prototype.closestPointToSegment=function(){const n=new B.Vector3,t=new B.Vector3,e=new B.Line3;return function(r,o=null,s=null){const{start:a,end:c}=r,u=this.points;let m,f=1/0;for(let l=0;l<3;l++){const d=(l+1)%3;e.start.copy(u[l]),e.end.copy(u[d]),vn(e,r,n,t),m=n.distanceToSquared(t),m<f&&(f=m,o&&o.copy(n),s&&s.copy(t))}return this.closestPointToPoint(a,n),m=a.distanceToSquared(n),m<f&&(f=m,o&&o.copy(n),s&&s.copy(a)),this.closestPointToPoint(c,n),m=c.distanceToSquared(n),m<f&&(f=m,o&&o.copy(n),s&&s.copy(c)),Math.sqrt(f)}}();fe.prototype.intersectsTriangle=function(){const n=new fe,t=new ve,e=new ve,i=new B.Vector3,r=new B.Vector3,o=new B.Vector3,s=new B.Vector3,a=new B.Line3,c=new B.Line3,u=new B.Vector3,m=new B.Vector2,f=new B.Vector2;function l(p,x,g,A){const T=i;!p.isDegenerateIntoPoint&&!p.isDegenerateIntoSegment?T.copy(p.plane.normal):T.copy(x.plane.normal);const I=p.satBounds,E=p.satAxes;for(let C=1;C<4;C++){const F=I[C],_=E[C];if(t.setFromPoints(_,x.points),F.isSeparated(t)||(s.copy(T).cross(_),t.setFromPoints(s,p.points),e.setFromPoints(s,x.points),t.isSeparated(e)))return!1}const S=x.satBounds,P=x.satAxes;for(let C=1;C<4;C++){const F=S[C],_=P[C];if(t.setFromPoints(_,p.points),F.isSeparated(t)||(s.crossVectors(T,_),t.setFromPoints(s,p.points),e.setFromPoints(s,x.points),t.isSeparated(e)))return!1}return g&&(A||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),g.start.set(0,0,0),g.end.set(0,0,0)),!0}function d(p,x,g,A,T,I,E,S,P,C,F){let _=E/(E-S);C.x=A+(T-A)*_,F.start.subVectors(x,p).multiplyScalar(_).add(p),_=E/(E-P),C.y=A+(I-A)*_,F.end.subVectors(g,p).multiplyScalar(_).add(p)}function y(p,x,g,A,T,I,E,S,P,C,F){if(T>0)d(p.c,p.a,p.b,A,x,g,P,E,S,C,F);else if(I>0)d(p.b,p.a,p.c,g,x,A,S,E,P,C,F);else if(S*P>0||E!=0)d(p.a,p.b,p.c,x,g,A,E,S,P,C,F);else if(S!=0)d(p.b,p.a,p.c,g,x,A,S,E,P,C,F);else if(P!=0)d(p.c,p.a,p.b,A,x,g,P,E,S,C,F);else return!0;return!1}function w(p,x,g,A){const T=x.degenerateSegment,I=p.plane.distanceToPoint(T.start),E=p.plane.distanceToPoint(T.end);return ae(I)?ae(E)?l(p,x,g,A):(g&&(g.start.copy(T.start),g.end.copy(T.start)),p.containsPoint(T.start)):ae(E)?(g&&(g.start.copy(T.end),g.end.copy(T.end)),p.containsPoint(T.end)):p.plane.intersectLine(T,i)!=null?(g&&(g.start.copy(i),g.end.copy(i)),p.containsPoint(i)):!1}function b(p,x,g){const A=x.a;return ae(p.plane.distanceToPoint(A))&&p.containsPoint(A)?(g&&(g.start.copy(A),g.end.copy(A)),!0):!1}function M(p,x,g){const A=p.degenerateSegment,T=x.a;return A.closestPointToPoint(T,!0,i),T.distanceToSquared(i)<Un?(g&&(g.start.copy(T),g.end.copy(T)),!0):!1}function h(p,x,g,A){if(p.isDegenerateIntoSegment)if(x.isDegenerateIntoSegment){const T=p.degenerateSegment,I=x.degenerateSegment,E=r,S=o;T.delta(E),I.delta(S);const P=i.subVectors(I.start,T.start),C=E.x*S.y-E.y*S.x;if(ae(C))return!1;const F=(P.x*S.y-P.y*S.x)/C,_=-(E.x*P.y-E.y*P.x)/C;if(F<0||F>1||_<0||_>1)return!1;const V=T.start.z+E.z*F,k=I.start.z+S.z*_;return ae(V-k)?(g&&(g.start.copy(T.start).addScaledVector(E,F),g.end.copy(T.start).addScaledVector(E,F)),!0):!1}else return x.isDegenerateIntoPoint?M(p,x,g):w(x,p,g,A);else{if(p.isDegenerateIntoPoint)return x.isDegenerateIntoPoint?x.a.distanceToSquared(p.a)<Un?(g&&(g.start.copy(p.a),g.end.copy(p.a)),!0):!1:x.isDegenerateIntoSegment?M(x,p,g):b(x,p,g);if(x.isDegenerateIntoPoint)return b(p,x,g);if(x.isDegenerateIntoSegment)return w(p,x,g,A)}}return function(x,g=null,A=!1){this.needsUpdate&&this.update(),x.isExtendedTriangle?x.needsUpdate&&x.update():(n.copy(x),n.update(),x=n);const T=h(this,x,g,A);if(T!==void 0)return T;const I=this.plane,E=x.plane;let S=E.distanceToPoint(this.a),P=E.distanceToPoint(this.b),C=E.distanceToPoint(this.c);ae(S)&&(S=0),ae(P)&&(P=0),ae(C)&&(C=0);const F=S*P,_=S*C;if(F>0&&_>0)return!1;let V=I.distanceToPoint(x.a),k=I.distanceToPoint(x.b),H=I.distanceToPoint(x.c);ae(V)&&(V=0),ae(k)&&(k=0),ae(H)&&(H=0);const te=V*k,oe=V*H;if(te>0&&oe>0)return!1;r.copy(I.normal),o.copy(E.normal);const qe=r.cross(o);let ie=0,re=Math.abs(qe.x);const nt=Math.abs(qe.y);nt>re&&(re=nt,ie=1),Math.abs(qe.z)>re&&(ie=2);const xe=Wo[ie],it=this.a[xe],ot=this.b[xe],rt=this.c[xe],st=x.a[xe],at=x.b[xe],Vt=x.c[xe];if(y(this,it,ot,rt,F,_,S,P,C,m,a))return l(this,x,g,A);if(y(x,st,at,Vt,te,oe,V,k,H,f,c))return l(this,x,g,A);if(m.y<m.x){const $e=m.y;m.y=m.x,m.x=$e,u.copy(a.start),a.start.copy(a.end),a.end.copy(u)}if(f.y<f.x){const $e=f.y;f.y=f.x,f.x=$e,u.copy(c.start),c.start.copy(c.end),c.end.copy(u)}return m.y<f.x||f.y<m.x?!1:(g&&(f.x>m.x?g.start.copy(c.start):g.start.copy(a.start),f.y<m.y?g.end.copy(c.end):g.end.copy(a.end)),!0)}}();fe.prototype.distanceToPoint=function(){const n=new B.Vector3;return function(e){return this.closestPointToPoint(e,n),e.distanceTo(n)}}();fe.prototype.distanceToTriangle=function(){const n=new B.Vector3,t=new B.Vector3,e=["a","b","c"],i=new B.Line3,r=new B.Line3;return function(s,a=null,c=null){const u=a||c?i:null;if(this.intersectsTriangle(s,u,!0))return(a||c)&&(a&&u.getCenter(a),c&&u.getCenter(c)),0;let m=1/0;for(let f=0;f<3;f++){let l;const d=e[f],y=s[d];this.closestPointToPoint(y,n),l=y.distanceToSquared(n),l<m&&(m=l,a&&a.copy(n),c&&c.copy(y));const w=this[d];s.closestPointToPoint(w,n),l=w.distanceToSquared(n),l<m&&(m=l,a&&a.copy(w),c&&c.copy(n))}for(let f=0;f<3;f++){const l=e[f],d=e[(f+1)%3];i.set(this[l],this[d]);for(let y=0;y<3;y++){const w=e[y],b=e[(y+1)%3];r.set(s[w],s[b]),vn(i,r,n,t);const M=n.distanceToSquared(t);M<m&&(m=M,a&&a.copy(n),c&&c.copy(t))}}return Math.sqrt(m)}}();class ne{constructor(t,e,i){this.isOrientedBox=!0,this.min=new B.Vector3,this.max=new B.Vector3,this.matrix=new B.Matrix4,this.invMatrix=new B.Matrix4,this.points=new Array(8).fill().map(()=>new B.Vector3),this.satAxes=new Array(3).fill().map(()=>new B.Vector3),this.satBounds=new Array(3).fill().map(()=>new ve),this.alignedSatBounds=new Array(3).fill().map(()=>new ve),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}ne.prototype.update=function(){return function(){const t=this.matrix,e=this.min,i=this.max,r=this.points;for(let u=0;u<=1;u++)for(let m=0;m<=1;m++)for(let f=0;f<=1;f++){const l=1*u|2*m|4*f,d=r[l];d.x=u?i.x:e.x,d.y=m?i.y:e.y,d.z=f?i.z:e.z,d.applyMatrix4(t)}const o=this.satBounds,s=this.satAxes,a=r[0];for(let u=0;u<3;u++){const m=s[u],f=o[u],l=1<<u,d=r[l];m.subVectors(a,d),f.setFromPoints(m,r)}const c=this.alignedSatBounds;c[0].setFromPointsField(r,"x"),c[1].setFromPointsField(r,"y"),c[2].setFromPointsField(r,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}();ne.prototype.intersectsBox=function(){const n=new ve;return function(e){this.needsUpdate&&this.update();const i=e.min,r=e.max,o=this.satBounds,s=this.satAxes,a=this.alignedSatBounds;if(n.min=i.x,n.max=r.x,a[0].isSeparated(n)||(n.min=i.y,n.max=r.y,a[1].isSeparated(n))||(n.min=i.z,n.max=r.z,a[2].isSeparated(n)))return!1;for(let c=0;c<3;c++){const u=s[c],m=o[c];if(n.setFromBox(u,e),m.isSeparated(n))return!1}return!0}}();ne.prototype.intersectsTriangle=function(){const n=new fe,t=new Array(3),e=new ve,i=new ve,r=new B.Vector3;return function(s){this.needsUpdate&&this.update(),s.isExtendedTriangle?s.needsUpdate&&s.update():(n.copy(s),n.update(),s=n);const a=this.satBounds,c=this.satAxes;t[0]=s.a,t[1]=s.b,t[2]=s.c;for(let l=0;l<3;l++){const d=a[l],y=c[l];if(e.setFromPoints(y,t),d.isSeparated(e))return!1}const u=s.satBounds,m=s.satAxes,f=this.points;for(let l=0;l<3;l++){const d=u[l],y=m[l];if(e.setFromPoints(y,f),d.isSeparated(e))return!1}for(let l=0;l<3;l++){const d=c[l];for(let y=0;y<4;y++){const w=m[y];if(r.crossVectors(d,w),e.setFromPoints(r,t),i.setFromPoints(r,f),e.isSeparated(i))return!1}}return!0}}();ne.prototype.closestPointToPoint=function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}}();ne.prototype.distanceToPoint=function(){const n=new B.Vector3;return function(e){return this.closestPointToPoint(e,n),e.distanceTo(n)}}();ne.prototype.distanceToBox=function(){const n=["x","y","z"],t=new Array(12).fill().map(()=>new B.Line3),e=new Array(12).fill().map(()=>new B.Line3),i=new B.Vector3,r=new B.Vector3;return function(s,a=0,c=null,u=null){if(this.needsUpdate&&this.update(),this.intersectsBox(s))return(c||u)&&(s.getCenter(r),this.closestPointToPoint(r,i),s.closestPointToPoint(i,r),c&&c.copy(i),u&&u.copy(r)),0;const m=a*a,f=s.min,l=s.max,d=this.points;let y=1/0;for(let b=0;b<8;b++){const M=d[b];r.copy(M).clamp(f,l);const h=M.distanceToSquared(r);if(h<y&&(y=h,c&&c.copy(M),u&&u.copy(r),h<m))return Math.sqrt(h)}let w=0;for(let b=0;b<3;b++)for(let M=0;M<=1;M++)for(let h=0;h<=1;h++){const p=(b+1)%3,x=(b+2)%3,g=M<<p|h<<x,A=1<<b|M<<p|h<<x,T=d[g],I=d[A];t[w].set(T,I);const S=n[b],P=n[p],C=n[x],F=e[w],_=F.start,V=F.end;_[S]=f[S],_[P]=M?f[P]:l[P],_[C]=h?f[C]:l[P],V[S]=l[S],V[P]=M?f[P]:l[P],V[C]=h?f[C]:l[P],w++}for(let b=0;b<=1;b++)for(let M=0;M<=1;M++)for(let h=0;h<=1;h++){r.x=b?l.x:f.x,r.y=M?l.y:f.y,r.z=h?l.z:f.z,this.closestPointToPoint(r,i);const p=r.distanceToSquared(i);if(p<y&&(y=p,c&&c.copy(i),u&&u.copy(r),p<m))return Math.sqrt(p)}for(let b=0;b<12;b++){const M=t[b];for(let h=0;h<12;h++){const p=e[h];vn(M,p,i,r);const x=i.distanceToSquared(r);if(x<y&&(y=x,c&&c.copy(i),u&&u.copy(r),x<m))return Math.sqrt(x)}}return Math.sqrt(y)}}();class Yo extends gn{constructor(){super(()=>new fe)}}const ce=new Yo,Ye=new B.Vector3,Wt=new B.Vector3;function jo(n,t,e={},i=0,r=1/0){const o=i*i,s=r*r;let a=1/0,c=null;if(n.shapecast({boundsTraverseOrder:m=>(Ye.copy(t).clamp(m.min,m.max),Ye.distanceToSquared(t)),intersectsBounds:(m,f,l)=>l<a&&l<s,intersectsTriangle:(m,f)=>{m.closestPointToPoint(t,Ye);const l=t.distanceToSquared(Ye);return l<a&&(Wt.copy(Ye),a=l,c=f),l<o}}),a===1/0)return null;const u=Math.sqrt(a);return e.point?e.point.copy(Wt):e.point=Wt.clone(),e.distance=u,e.faceIndex=c,e}const mt=parseInt(B.REVISION)>=169,Xo=parseInt(B.REVISION)<=161,Ie=new B.Vector3,Pe=new B.Vector3,Ee=new B.Vector3,pt=new B.Vector2,ht=new B.Vector2,yt=new B.Vector2,kn=new B.Vector3,Gn=new B.Vector3,On=new B.Vector3,je=new B.Vector3;function Ko(n,t,e,i,r,o,s,a){let c;if(o===B.BackSide?c=n.intersectTriangle(i,e,t,!0,r):c=n.intersectTriangle(t,e,i,o!==B.DoubleSide,r),c===null)return null;const u=n.origin.distanceTo(r);return u<s||u>a?null:{distance:u,point:r.clone()}}function Hn(n,t,e,i,r,o,s,a,c,u,m){Ie.fromBufferAttribute(t,o),Pe.fromBufferAttribute(t,s),Ee.fromBufferAttribute(t,a);const f=Ko(n,Ie,Pe,Ee,je,c,u,m);if(f){if(i){pt.fromBufferAttribute(i,o),ht.fromBufferAttribute(i,s),yt.fromBufferAttribute(i,a),f.uv=new B.Vector2;const d=B.Triangle.getInterpolation(je,Ie,Pe,Ee,pt,ht,yt,f.uv);mt||(f.uv=d)}if(r){pt.fromBufferAttribute(r,o),ht.fromBufferAttribute(r,s),yt.fromBufferAttribute(r,a),f.uv1=new B.Vector2;const d=B.Triangle.getInterpolation(je,Ie,Pe,Ee,pt,ht,yt,f.uv1);mt||(f.uv1=d),Xo&&(f.uv2=f.uv1)}if(e){kn.fromBufferAttribute(e,o),Gn.fromBufferAttribute(e,s),On.fromBufferAttribute(e,a),f.normal=new B.Vector3;const d=B.Triangle.getInterpolation(je,Ie,Pe,Ee,kn,Gn,On,f.normal);f.normal.dot(n.direction)>0&&f.normal.multiplyScalar(-1),mt||(f.normal=d)}const l={a:o,b:s,c:a,normal:new B.Vector3,materialIndex:0};if(B.Triangle.getNormal(Ie,Pe,Ee,l.normal),f.face=l,f.faceIndex=o,mt){const d=new B.Vector3;B.Triangle.getBarycoord(je,Ie,Pe,Ee,d),f.barycoord=d}}return f}function qn(n){return n&&n.isMaterial?n.side:n}function Lt(n,t,e,i,r,o,s){const a=i*3;let c=a+0,u=a+1,m=a+2;const{index:f,groups:l}=n;n.index&&(c=f.getX(c),u=f.getX(u),m=f.getX(m));const{position:d,normal:y,uv:w,uv1:b}=n.attributes;if(Array.isArray(t)){const M=i*3;for(let h=0,p=l.length;h<p;h++){const{start:x,count:g,materialIndex:A}=l[h];if(M>=x&&M<x+g){const T=qn(t[A]),I=Hn(e,d,y,w,b,c,u,m,T,o,s);if(I)if(I.faceIndex=i,I.face.materialIndex=A,r)r.push(I);else return I}}}else{const M=qn(t),h=Hn(e,d,y,w,b,c,u,m,M,o,s);if(h)if(h.faceIndex=i,h.face.materialIndex=0,r)r.push(h);else return h}return null}function Y(n,t,e,i){const r=n.a,o=n.b,s=n.c;let a=t,c=t+1,u=t+2;e&&(a=e.getX(a),c=e.getX(c),u=e.getX(u)),r.x=i.getX(a),r.y=i.getY(a),r.z=i.getZ(a),o.x=i.getX(c),o.y=i.getY(c),o.z=i.getZ(c),s.x=i.getX(u),s.y=i.getY(u),s.z=i.getZ(u)}function Jo(n,t,e,i,r,o,s,a){const{geometry:c,_indirectBuffer:u}=n;for(let m=i,f=i+r;m<f;m++)Lt(c,t,e,m,o,s,a)}function Zo(n,t,e,i,r,o,s){const{geometry:a,_indirectBuffer:c}=n;let u=1/0,m=null;for(let f=i,l=i+r;f<l;f++){let d;d=Lt(a,t,e,f,null,o,s),d&&d.distance<u&&(m=d,u=d.distance)}return m}function Qo(n,t,e,i,r,o,s){const{geometry:a}=e,{index:c}=a,u=a.attributes.position;for(let m=n,f=t+n;m<f;m++){let l;if(l=m,Y(s,l*3,c,u),s.needsUpdate=!0,i(s,l,r,o))return!0}return!1}function er(n,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=n.geometry,i=e.index?e.index.array:null,r=e.attributes.position;let o,s,a,c,u=0;const m=n._roots;for(let l=0,d=m.length;l<d;l++)o=m[l],s=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),f(0,u),u+=o.byteLength;function f(l,d,y=!1){const w=l*2;if($(w,a)){const b=X(l,s),M=Q(w,a);let h=1/0,p=1/0,x=1/0,g=-1/0,A=-1/0,T=-1/0;for(let I=3*b,E=3*(b+M);I<E;I++){let S=i[I];const P=r.getX(S),C=r.getY(S),F=r.getZ(S);P<h&&(h=P),P>g&&(g=P),C<p&&(p=C),C>A&&(A=C),F<x&&(x=F),F>T&&(T=F)}return c[l+0]!==h||c[l+1]!==p||c[l+2]!==x||c[l+3]!==g||c[l+4]!==A||c[l+5]!==T?(c[l+0]=h,c[l+1]=p,c[l+2]=x,c[l+3]=g,c[l+4]=A,c[l+5]=T,!0):!1}else{const b=K(l),M=J(l,s);let h=y,p=!1,x=!1;if(t){if(!h){const S=b/j+d/Z,P=M/j+d/Z;p=t.has(S),x=t.has(P),h=!p&&!x}}else p=!0,x=!0;const g=h||p,A=h||x;let T=!1;g&&(T=f(b,d,h));let I=!1;A&&(I=f(M,d,h));const E=T||I;if(E)for(let S=0;S<3;S++){const P=b+S,C=M+S,F=c[P],_=c[P+3],V=c[C],k=c[C+3];c[l+S]=F<V?F:V,c[l+S+3]=_>k?_:k}return E}}}function Te(n,t,e,i,r){let o,s,a,c,u,m;const f=1/e.direction.x,l=1/e.direction.y,d=1/e.direction.z,y=e.origin.x,w=e.origin.y,b=e.origin.z;let M=t[n],h=t[n+3],p=t[n+1],x=t[n+3+1],g=t[n+2],A=t[n+3+2];return f>=0?(o=(M-y)*f,s=(h-y)*f):(o=(h-y)*f,s=(M-y)*f),l>=0?(a=(p-w)*l,c=(x-w)*l):(a=(x-w)*l,c=(p-w)*l),o>c||a>s||((a>o||isNaN(o))&&(o=a),(c<s||isNaN(s))&&(s=c),d>=0?(u=(g-b)*d,m=(A-b)*d):(u=(A-b)*d,m=(g-b)*d),o>m||u>s)?!1:((u>o||o!==o)&&(o=u),(m<s||s!==s)&&(s=m),o<=r&&s>=i)}function tr(n,t,e,i,r,o,s,a){const{geometry:c,_indirectBuffer:u}=n;for(let m=i,f=i+r;m<f;m++){let l=u?u[m]:m;Lt(c,t,e,l,o,s,a)}}function nr(n,t,e,i,r,o,s){const{geometry:a,_indirectBuffer:c}=n;let u=1/0,m=null;for(let f=i,l=i+r;f<l;f++){let d;d=Lt(a,t,e,c?c[f]:f,null,o,s),d&&d.distance<u&&(m=d,u=d.distance)}return m}function ir(n,t,e,i,r,o,s){const{geometry:a}=e,{index:c}=a,u=a.attributes.position;for(let m=n,f=t+n;m<f;m++){let l;if(l=e.resolveTriangleIndex(m),Y(s,l*3,c,u),s.needsUpdate=!0,i(s,l,r,o))return!0}return!1}function or(n,t,e,i,r,o,s){O.setBuffer(n._roots[t]),nn(0,n,e,i,r,o,s),O.clearBuffer()}function nn(n,t,e,i,r,o,s){const{float32Array:a,uint16Array:c,uint32Array:u}=O,m=n*2;if($(m,c)){const l=X(n,u),d=Q(m,c);Jo(t,e,i,l,d,r,o,s)}else{const l=K(n);Te(l,a,i,o,s)&&nn(l,t,e,i,r,o,s);const d=J(n,u);Te(d,a,i,o,s)&&nn(d,t,e,i,r,o,s)}}const rr=["x","y","z"];function sr(n,t,e,i,r,o){O.setBuffer(n._roots[t]);const s=on(0,n,e,i,r,o);return O.clearBuffer(),s}function on(n,t,e,i,r,o){const{float32Array:s,uint16Array:a,uint32Array:c}=O;let u=n*2;if($(u,a)){const f=X(n,c),l=Q(u,a);return Zo(t,e,i,f,l,r,o)}else{const f=_t(n,c),l=rr[f],y=i.direction[l]>=0;let w,b;y?(w=K(n),b=J(n,c)):(w=J(n,c),b=K(n));const h=Te(w,s,i,r,o)?on(w,t,e,i,r,o):null;if(h){const g=h.point[l];if(y?g<=s[b+f]:g>=s[b+f+3])return h}const x=Te(b,s,i,r,o)?on(b,t,e,i,r,o):null;return h&&x?h.distance<=x.distance?h:x:h||x||null}}const gt=new B.Box3,Ne=new fe,Le=new fe,Xe=new B.Matrix4,$n=new ne,vt=new ne;function ar(n,t,e,i){O.setBuffer(n._roots[t]);const r=rn(0,n,e,i);return O.clearBuffer(),r}function rn(n,t,e,i,r=null){const{float32Array:o,uint16Array:s,uint32Array:a}=O;let c=n*2;if(r===null&&(e.boundingBox||e.computeBoundingBox(),$n.set(e.boundingBox.min,e.boundingBox.max,i),r=$n),$(c,s)){const m=t.geometry,f=m.index,l=m.attributes.position,d=e.index,y=e.attributes.position,w=X(n,a),b=Q(c,s);if(Xe.copy(i).invert(),e.boundsTree)return q(n,o,vt),vt.matrix.copy(Xe),vt.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:h=>vt.intersectsBox(h),intersectsTriangle:h=>{h.a.applyMatrix4(i),h.b.applyMatrix4(i),h.c.applyMatrix4(i),h.needsUpdate=!0;for(let p=w*3,x=(b+w)*3;p<x;p+=3)if(Y(Le,p,f,l),Le.needsUpdate=!0,h.intersectsTriangle(Le))return!0;return!1}});{const M=Nt(e);for(let h=w*3,p=(b+w)*3;h<p;h+=3){Y(Ne,h,f,l),Ne.a.applyMatrix4(Xe),Ne.b.applyMatrix4(Xe),Ne.c.applyMatrix4(Xe),Ne.needsUpdate=!0;for(let x=0,g=M*3;x<g;x+=3)if(Y(Le,x,d,y),Le.needsUpdate=!0,Ne.intersectsTriangle(Le))return!0}}}else{const m=K(n),f=J(n,a);return q(m,o,gt),!!(r.intersectsBox(gt)&&rn(m,t,e,i,r)||(q(f,o,gt),r.intersectsBox(gt)&&rn(f,t,e,i,r)))}}const bt=new B.Matrix4,Yt=new ne,Ke=new ne,cr=new B.Vector3,lr=new B.Vector3,ur=new B.Vector3,fr=new B.Vector3;function dr(n,t,e,i={},r={},o=0,s=1/0){t.boundingBox||t.computeBoundingBox(),Yt.set(t.boundingBox.min,t.boundingBox.max,e),Yt.needsUpdate=!0;const a=n.geometry,c=a.attributes.position,u=a.index,m=t.attributes.position,f=t.index,l=ce.getPrimitive(),d=ce.getPrimitive();let y=cr,w=lr,b=null,M=null;r&&(b=ur,M=fr);let h=1/0,p=null,x=null;return bt.copy(e).invert(),Ke.matrix.copy(bt),n.shapecast({boundsTraverseOrder:g=>Yt.distanceToBox(g),intersectsBounds:(g,A,T)=>T<h&&T<s?(A&&(Ke.min.copy(g.min),Ke.max.copy(g.max),Ke.needsUpdate=!0),!0):!1,intersectsRange:(g,A)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:I=>Ke.distanceToBox(I),intersectsBounds:(I,E,S)=>S<h&&S<s,intersectsRange:(I,E)=>{for(let S=I,P=I+E;S<P;S++){Y(d,3*S,f,m),d.a.applyMatrix4(e),d.b.applyMatrix4(e),d.c.applyMatrix4(e),d.needsUpdate=!0;for(let C=g,F=g+A;C<F;C++){Y(l,3*C,u,c),l.needsUpdate=!0;const _=l.distanceToTriangle(d,y,b);if(_<h&&(w.copy(y),M&&M.copy(b),h=_,p=C,x=S),_<o)return!0}}}});{const T=Nt(t);for(let I=0,E=T;I<E;I++){Y(d,3*I,f,m),d.a.applyMatrix4(e),d.b.applyMatrix4(e),d.c.applyMatrix4(e),d.needsUpdate=!0;for(let S=g,P=g+A;S<P;S++){Y(l,3*S,u,c),l.needsUpdate=!0;const C=l.distanceToTriangle(d,y,b);if(C<h&&(w.copy(y),M&&M.copy(b),h=C,p=S,x=I),C<o)return!0}}}}}),ce.releasePrimitive(l),ce.releasePrimitive(d),h===1/0?null:(i.point?i.point.copy(w):i.point=w.clone(),i.distance=h,i.faceIndex=p,r&&(r.point?r.point.copy(M):r.point=M.clone(),r.point.applyMatrix4(bt),w.applyMatrix4(bt),r.distance=w.sub(r.point).length(),r.faceIndex=x),i)}function mr(n,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=n.geometry,i=e.index?e.index.array:null,r=e.attributes.position;let o,s,a,c,u=0;const m=n._roots;for(let l=0,d=m.length;l<d;l++)o=m[l],s=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),f(0,u),u+=o.byteLength;function f(l,d,y=!1){const w=l*2;if($(w,a)){const b=X(l,s),M=Q(w,a);let h=1/0,p=1/0,x=1/0,g=-1/0,A=-1/0,T=-1/0;for(let I=b,E=b+M;I<E;I++){const S=3*n.resolveTriangleIndex(I);for(let P=0;P<3;P++){let C=S+P;C=i?i[C]:C;const F=r.getX(C),_=r.getY(C),V=r.getZ(C);F<h&&(h=F),F>g&&(g=F),_<p&&(p=_),_>A&&(A=_),V<x&&(x=V),V>T&&(T=V)}}return c[l+0]!==h||c[l+1]!==p||c[l+2]!==x||c[l+3]!==g||c[l+4]!==A||c[l+5]!==T?(c[l+0]=h,c[l+1]=p,c[l+2]=x,c[l+3]=g,c[l+4]=A,c[l+5]=T,!0):!1}else{const b=K(l),M=J(l,s);let h=y,p=!1,x=!1;if(t){if(!h){const S=b/j+d/Z,P=M/j+d/Z;p=t.has(S),x=t.has(P),h=!p&&!x}}else p=!0,x=!0;const g=h||p,A=h||x;let T=!1;g&&(T=f(b,d,h));let I=!1;A&&(I=f(M,d,h));const E=T||I;if(E)for(let S=0;S<3;S++){const P=b+S,C=M+S,F=c[P],_=c[P+3],V=c[C],k=c[C+3];c[l+S]=F<V?F:V,c[l+S+3]=_>k?_:k}return E}}}function pr(n,t,e,i,r,o,s){O.setBuffer(n._roots[t]),sn(0,n,e,i,r,o,s),O.clearBuffer()}function sn(n,t,e,i,r,o,s){const{float32Array:a,uint16Array:c,uint32Array:u}=O,m=n*2;if($(m,c)){const l=X(n,u),d=Q(m,c);tr(t,e,i,l,d,r,o,s)}else{const l=K(n);Te(l,a,i,o,s)&&sn(l,t,e,i,r,o,s);const d=J(n,u);Te(d,a,i,o,s)&&sn(d,t,e,i,r,o,s)}}const hr=["x","y","z"];function yr(n,t,e,i,r,o){O.setBuffer(n._roots[t]);const s=an(0,n,e,i,r,o);return O.clearBuffer(),s}function an(n,t,e,i,r,o){const{float32Array:s,uint16Array:a,uint32Array:c}=O;let u=n*2;if($(u,a)){const f=X(n,c),l=Q(u,a);return nr(t,e,i,f,l,r,o)}else{const f=_t(n,c),l=hr[f],y=i.direction[l]>=0;let w,b;y?(w=K(n),b=J(n,c)):(w=J(n,c),b=K(n));const h=Te(w,s,i,r,o)?an(w,t,e,i,r,o):null;if(h){const g=h.point[l];if(y?g<=s[b+f]:g>=s[b+f+3])return h}const x=Te(b,s,i,r,o)?an(b,t,e,i,r,o):null;return h&&x?h.distance<=x.distance?h:x:h||x||null}}const xt=new B.Box3,Ve=new fe,ze=new fe,Je=new B.Matrix4,Wn=new ne,wt=new ne;function gr(n,t,e,i){O.setBuffer(n._roots[t]);const r=cn(0,n,e,i);return O.clearBuffer(),r}function cn(n,t,e,i,r=null){const{float32Array:o,uint16Array:s,uint32Array:a}=O;let c=n*2;if(r===null&&(e.boundingBox||e.computeBoundingBox(),Wn.set(e.boundingBox.min,e.boundingBox.max,i),r=Wn),$(c,s)){const m=t.geometry,f=m.index,l=m.attributes.position,d=e.index,y=e.attributes.position,w=X(n,a),b=Q(c,s);if(Je.copy(i).invert(),e.boundsTree)return q(n,o,wt),wt.matrix.copy(Je),wt.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:h=>wt.intersectsBox(h),intersectsTriangle:h=>{h.a.applyMatrix4(i),h.b.applyMatrix4(i),h.c.applyMatrix4(i),h.needsUpdate=!0;for(let p=w,x=b+w;p<x;p++)if(Y(ze,3*t.resolveTriangleIndex(p),f,l),ze.needsUpdate=!0,h.intersectsTriangle(ze))return!0;return!1}});{const M=Nt(e);for(let h=w,p=b+w;h<p;h++){const x=t.resolveTriangleIndex(h);Y(Ve,3*x,f,l),Ve.a.applyMatrix4(Je),Ve.b.applyMatrix4(Je),Ve.c.applyMatrix4(Je),Ve.needsUpdate=!0;for(let g=0,A=M*3;g<A;g+=3)if(Y(ze,g,d,y),ze.needsUpdate=!0,Ve.intersectsTriangle(ze))return!0}}}else{const m=K(n),f=J(n,a);return q(m,o,xt),!!(r.intersectsBox(xt)&&cn(m,t,e,i,r)||(q(f,o,xt),r.intersectsBox(xt)&&cn(f,t,e,i,r)))}}const Mt=new B.Matrix4,jt=new ne,Ze=new ne,vr=new B.Vector3,br=new B.Vector3,xr=new B.Vector3,wr=new B.Vector3;function Mr(n,t,e,i={},r={},o=0,s=1/0){t.boundingBox||t.computeBoundingBox(),jt.set(t.boundingBox.min,t.boundingBox.max,e),jt.needsUpdate=!0;const a=n.geometry,c=a.attributes.position,u=a.index,m=t.attributes.position,f=t.index,l=ce.getPrimitive(),d=ce.getPrimitive();let y=vr,w=br,b=null,M=null;r&&(b=xr,M=wr);let h=1/0,p=null,x=null;return Mt.copy(e).invert(),Ze.matrix.copy(Mt),n.shapecast({boundsTraverseOrder:g=>jt.distanceToBox(g),intersectsBounds:(g,A,T)=>T<h&&T<s?(A&&(Ze.min.copy(g.min),Ze.max.copy(g.max),Ze.needsUpdate=!0),!0):!1,intersectsRange:(g,A)=>{if(t.boundsTree){const T=t.boundsTree;return T.shapecast({boundsTraverseOrder:I=>Ze.distanceToBox(I),intersectsBounds:(I,E,S)=>S<h&&S<s,intersectsRange:(I,E)=>{for(let S=I,P=I+E;S<P;S++){const C=T.resolveTriangleIndex(S);Y(d,3*C,f,m),d.a.applyMatrix4(e),d.b.applyMatrix4(e),d.c.applyMatrix4(e),d.needsUpdate=!0;for(let F=g,_=g+A;F<_;F++){const V=n.resolveTriangleIndex(F);Y(l,3*V,u,c),l.needsUpdate=!0;const k=l.distanceToTriangle(d,y,b);if(k<h&&(w.copy(y),M&&M.copy(b),h=k,p=F,x=S),k<o)return!0}}}})}else{const T=Nt(t);for(let I=0,E=T;I<E;I++){Y(d,3*I,f,m),d.a.applyMatrix4(e),d.b.applyMatrix4(e),d.c.applyMatrix4(e),d.needsUpdate=!0;for(let S=g,P=g+A;S<P;S++){const C=n.resolveTriangleIndex(S);Y(l,3*C,u,c),l.needsUpdate=!0;const F=l.distanceToTriangle(d,y,b);if(F<h&&(w.copy(y),M&&M.copy(b),h=F,p=S,x=I),F<o)return!0}}}}}),ce.releasePrimitive(l),ce.releasePrimitive(d),h===1/0?null:(i.point?i.point.copy(w):i.point=w.clone(),i.distance=h,i.faceIndex=p,r&&(r.point?r.point.copy(M):r.point=M.clone(),r.point.applyMatrix4(Mt),w.applyMatrix4(Mt),r.distance=w.sub(r.point).length(),r.faceIndex=x),i)}function Yn(n,t,e){return n===null?null:(n.point.applyMatrix4(t.matrixWorld),n.distance=n.point.distanceTo(e.ray.origin),n.object=t,n)}const At=new ne,St=new B.Ray,jn=new B.Vector3,Xn=new B.Matrix4,Kn=new B.Vector3,Xt=["getX","getY","getZ"];class It extends Ho{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,r=t._roots,o=t._indirectBuffer,s=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(a.roots=r.map(c=>c.slice()),a.index=s?s.array.slice():null,a.indirectBuffer=o?o.slice():null):(a.roots=r,a.index=s?s.array:null,a.indirectBuffer=o),a}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:r,roots:o,indirectBuffer:s}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),c(o));const a=new It(e,{...i,[yn]:!0});if(a._roots=o,a._indirectBuffer=s||null,i.setIndex){const u=e.getIndex();if(u===null){const m=new B.BufferAttribute(t.index,1,!1);e.setIndex(m)}else u.array!==r&&(u.array.set(r),u.needsUpdate=!0)}return a;function c(u){for(let m=0;m<u.length;m++){const f=u[m],l=new Uint32Array(f),d=new Uint16Array(f);for(let y=0,w=f.byteLength/Z;y<w;y++){const b=j*y,M=2*b;$(M,d)||(l[b+6]=l[b+6]/j-y)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const r=this.geometry,o=this._indirectBuffer,s=r.attributes.position,a=r.index?r.index.array:null,u=(o?o[t]:t)*3;let m=u+0,f=u+1,l=u+2;a&&(m=a[m],f=a[f],l=a[l]);for(let d=0;d<3;d++){const y=s[Xt[d]](m),w=s[Xt[d]](f),b=s[Xt[d]](l);let M=y;w<M&&(M=w),b<M&&(M=b);let h=y;w>h&&(h=w),b>h&&(h=b),e[i+d]=M,e[i+d+3]=h}return e}computePrimitiveBounds(t,e,i){const r=this.geometry,o=this._indirectBuffer,s=r.attributes.position,a=r.index?r.index.array:null,c=s.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const u=s.array,m=s.offset||0;let f=3;s.isInterleavedBufferAttribute&&(f=s.data.stride);const l=["getX","getY","getZ"],d=i.offset;for(let y=t,w=t+e;y<w;y++){const M=(o?o[y]:y)*3,h=(y-d)*6;let p=M+0,x=M+1,g=M+2;a&&(p=a[p],x=a[x],g=a[g]),c||(p=p*f+m,x=x*f+m,g=g*f+m);for(let A=0;A<3;A++){let T,I,E;c?(T=s[l[A]](p),I=s[l[A]](x),E=s[l[A]](g)):(T=u[p+A],I=u[x+A],E=u[g+A]);let S=T;I<S&&(S=I),E<S&&(S=E);let P=T;I>P&&(P=I),E>P&&(P=E);const C=(P-S)/2,F=A*2;i[h+F+0]=S+C,i[h+F+1]=C+(Math.abs(S)+C)*Tt}}return i}raycastObject3D(t,e,i=[]){const{material:r}=t;if(r===void 0)return;Xn.copy(t.matrixWorld).invert(),St.copy(e.ray).applyMatrix4(Xn),Kn.setFromMatrixScale(t.matrixWorld),jn.copy(St.direction).multiply(Kn);const o=jn.length(),s=e.near/o,a=e.far/o;if(e.firstHitOnly===!0){let c=this.raycastFirst(St,r,s,a);c=Yn(c,t,e),c&&i.push(c)}else{const c=this.raycast(St,r,s,a);for(let u=0,m=c.length;u<m;u++){const f=Yn(c[u],t,e);f&&i.push(f)}}return i}refit(t=null){return(this.indirect?mr:er)(this,t)}raycast(t,e=B.FrontSide,i=0,r=1/0){const o=this._roots,s=[],a=this.indirect?pr:or;for(let c=0,u=o.length;c<u;c++)a(this,c,e,t,s,i,r);return s}raycastFirst(t,e=B.FrontSide,i=0,r=1/0){const o=this._roots;let s=null;const a=this.indirect?yr:sr;for(let c=0,u=o.length;c<u;c++){const m=a(this,c,e,t,i,r);m!=null&&(s==null||m.distance<s.distance)&&(s=m)}return s}intersectsGeometry(t,e){let i=!1;const r=this._roots,o=this.indirect?gr:ar;for(let s=0,a=r.length;s<a&&(i=o(this,s,t,e),!i);s++);return i}shapecast(t){const e=ce.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?ir:Qo});return ce.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:r,intersectsTriangles:o}=i;const s=ce.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,u=this.indirect?y=>{const w=this.resolveTriangleIndex(y);Y(s,w*3,a,c)}:y=>{Y(s,y*3,a,c)},m=ce.getPrimitive(),f=t.geometry.index,l=t.geometry.attributes.position,d=t.indirect?y=>{const w=t.resolveTriangleIndex(y);Y(m,w*3,f,l)}:y=>{Y(m,y*3,f,l)};if(o){if(!(t instanceof It))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const y=(w,b,M,h,p,x,g,A)=>{for(let T=M,I=M+h;T<I;T++){d(T),m.a.applyMatrix4(e),m.b.applyMatrix4(e),m.c.applyMatrix4(e),m.needsUpdate=!0;for(let E=w,S=w+b;E<S;E++)if(u(E),s.needsUpdate=!0,o(s,m,E,T,p,x,g,A))return!0}return!1};if(r){const w=r;r=function(b,M,h,p,x,g,A,T){return w(b,M,h,p,x,g,A,T)?!0:y(b,M,h,p,x,g,A,T)}}else r=y}return super.bvhcast(t,e,{intersectsRanges:r})}intersectsBox(t,e){return At.set(t.min,t.max,e),At.needsUpdate=!0,this.shapecast({intersectsBounds:i=>At.intersectsBox(i),intersectsTriangle:i=>At.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},r={},o=0,s=1/0){return(this.indirect?Mr:dr)(this,t,e,i,r,o,s)}closestPointToPoint(t,e={},i=0,r=1/0){return jo(this,t,e,i,r)}}function Ar(n){switch(n){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function Sr(n){switch(n){case 1:return B.RedFormat;case 2:return B.RGFormat;case 3:return B.RGBAFormat;case 4:return B.RGBAFormat}}function Jn(n){switch(n){case 1:return B.RedIntegerFormat;case 2:return B.RGIntegerFormat;case 3:return B.RGBAIntegerFormat;case 4:return B.RGBAIntegerFormat}}class hi extends B.DataTexture{constructor(){super(),this.minFilter=B.NearestFilter,this.magFilter=B.NearestFilter,this.generateMipmaps=!1,this.overrideItemSize=null,this._forcedType=null}updateFrom(t){const e=this.overrideItemSize,i=t.itemSize,r=t.count;if(e!==null){if(i*r%e!==0)throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length.");t.itemSize=e,t.count=r*i/e}const o=t.itemSize,s=t.count,a=t.normalized,c=t.array.constructor,u=c.BYTES_PER_ELEMENT;let m=this._forcedType,f=o;if(m===null)switch(c){case Float32Array:m=B.FloatType;break;case Uint8Array:case Uint16Array:case Uint32Array:m=B.UnsignedIntType;break;case Int8Array:case Int16Array:case Int32Array:m=B.IntType;break}let l,d,y,w,b=Ar(o);switch(m){case B.FloatType:y=1,d=Sr(o),a&&u===1?(w=c,b+="8",c===Uint8Array?l=B.UnsignedByteType:(l=B.ByteType,b+="_SNORM")):(w=Float32Array,b+="32F",l=B.FloatType);break;case B.IntType:b+=u*8+"I",y=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,d=Jn(o),u===1?(w=Int8Array,l=B.ByteType):u===2?(w=Int16Array,l=B.ShortType):(w=Int32Array,l=B.IntType);break;case B.UnsignedIntType:b+=u*8+"UI",y=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,d=Jn(o),u===1?(w=Uint8Array,l=B.UnsignedByteType):u===2?(w=Uint16Array,l=B.UnsignedShortType):(w=Uint32Array,l=B.UnsignedIntType);break}f===3&&(d===B.RGBAFormat||d===B.RGBAIntegerFormat)&&(f=4);const M=Math.ceil(Math.sqrt(s))||1,h=f*M*M,p=new w(h),x=t.normalized;t.normalized=!1;for(let g=0;g<s;g++){const A=f*g;p[A]=t.getX(g)/y,o>=2&&(p[A+1]=t.getY(g)/y),o>=3&&(p[A+2]=t.getZ(g)/y,f===4&&(p[A+3]=1)),o>=4&&(p[A+3]=t.getW(g)/y)}t.normalized=x,this.internalFormat=b,this.format=d,this.type=l,this.image.width=M,this.image.height=M,this.image.data=p,this.needsUpdate=!0,this.dispose(),t.itemSize=i,t.count=r}}class Tr extends hi{constructor(){super(),this._forcedType=B.UnsignedIntType}}class Br extends hi{constructor(){super(),this._forcedType=B.FloatType}}class yi{constructor(){this.index=new Tr,this.position=new Br,this.bvhBounds=new B.DataTexture,this.bvhContents=new B.DataTexture,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(t){const{geometry:e}=t;if(Ir(t,this.bvhBounds,this.bvhContents),this.position.updateFrom(e.attributes.position),t.indirect){const i=t._indirectBuffer;if(this._cachedIndexAttr===null||this._cachedIndexAttr.count!==i.length)if(e.index)this._cachedIndexAttr=e.index.clone();else{const r=pi(Dt(e));this._cachedIndexAttr=new B.BufferAttribute(r,1,!1)}Cr(e,i,this._cachedIndexAttr),this.index.updateFrom(this._cachedIndexAttr)}else this.index.updateFrom(e.index)}dispose(){const{index:t,position:e,bvhBounds:i,bvhContents:r}=this;t&&t.dispose(),e&&e.dispose(),i&&i.dispose(),r&&r.dispose()}}function Cr(n,t,e){const i=e.array,r=n.index?n.index.array:null;for(let o=0,s=t.length;o<s;o++){const a=3*o,c=3*t[o];for(let u=0;u<3;u++)i[a+u]=r?r[c+u]:c+u}}function Ir(n,t,e){const i=n._roots;if(i.length!==1)throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported.");const r=i[0],o=new Uint16Array(r),s=new Uint32Array(r),a=new Float32Array(r),c=r.byteLength/Z,u=2*Math.ceil(Math.sqrt(c/2)),m=new Float32Array(4*u*u),f=Math.ceil(Math.sqrt(c)),l=new Uint32Array(2*f*f);for(let d=0;d<c;d++){const y=d*Z/4,w=y*2,b=y;for(let M=0;M<3;M++)m[8*d+0+M]=a[b+0+M],m[8*d+4+M]=a[b+3+M];if($(w,o)){const M=Q(w,o),h=X(y,s),p=To|M;l[d*2+0]=p,l[d*2+1]=h}else{const M=s[y+6],h=_t(y,s);l[d*2+0]=h,l[d*2+1]=M}}t.image.data=m,t.image.width=u,t.image.height=u,t.format=B.RGBAFormat,t.type=B.FloatType,t.internalFormat="RGBA32F",t.minFilter=B.NearestFilter,t.magFilter=B.NearestFilter,t.generateMipmaps=!1,t.needsUpdate=!0,t.dispose(),e.image.data=l,e.image.width=f,e.image.height=f,e.format=B.RGIntegerFormat,e.type=B.UnsignedIntType,e.internalFormat="RG32UI",e.minFilter=B.NearestFilter,e.magFilter=B.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e.dispose()}const Pr=`
1
+ "use strict";var Yi=Object.create;var Ht=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var ji=Object.getOwnPropertyNames;var Ki=Object.getPrototypeOf,Ji=Object.prototype.hasOwnProperty;var Zi=(n,t,e)=>t in n?Ht(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var Qi=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ji(t))!Ji.call(n,o)&&o!==e&&Ht(n,o,{get:()=>t[o],enumerable:!(i=Xi(t,o))||i.enumerable});return n};var lt=(n,t,e)=>(e=n!=null?Yi(Ki(n)):{},Qi(t||!n||!n.__esModule?Ht(e,"default",{value:n,enumerable:!0}):e,n));var re=(n,t,e)=>Zi(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("three"),eo=require("three/examples/jsm/loaders/GLTFLoader.js"),to=require("three/examples/jsm/loaders/DRACOLoader.js"),no=require("three/examples/jsm/libs/meshopt_decoder.module.js"),Fn=require("three/examples/jsm/loaders/RGBELoader.js"),_n=require("three/examples/jsm/loaders/EXRLoader.js"),io=require("three/examples/jsm/controls/OrbitControls.js");function oo(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const v=oo(C);class Ft extends Error{constructor(e){super(`Unsupported format: "${e}"`);re(this,"format");this.name="UnsupportedFormatError",this.format=e,Object.setPrototypeOf(this,Ft.prototype)}}class Ae extends Error{constructor(e,i){super(e);re(this,"cause");this.name="CorruptFileError",this.cause=i,Object.setPrototypeOf(this,Ae.prototype)}}class ot extends Error{constructor(e,i,o){super(e);re(this,"status");re(this,"url");this.name="NetworkError",this.status=i,this.url=o,Object.setPrototypeOf(this,ot.prototype)}}function _t(n){n.position.set(0,0,0),n.scale.set(1,1,1),n.updateMatrixWorld(!0);const t=new v.Box3().setFromObject(n),e=t.getCenter(new v.Vector3),i=t.getSize(new v.Vector3),o=Math.max(i.x,i.y,i.z),r=o>0?1/o:1;n.scale.setScalar(r),n.position.sub(e.multiplyScalar(r)),n.updateMatrixWorld(!0)}const gn="https://www.gstatic.com/draco/versioned/decoders/1.5.6/";if(typeof globalThis.FileReader>"u"){class n{constructor(){re(this,"result",null);re(this,"onloadend",null);re(this,"onload",null);re(this,"onerror",null)}readAsArrayBuffer(e){e.arrayBuffer().then(i=>{var o,r;this.result=i,(o=this.onload)==null||o.call(this),(r=this.onloadend)==null||r.call(this)},i=>{var o,r;(o=this.onerror)==null||o.call(this,i),(r=this.onloadend)==null||r.call(this)})}readAsDataURL(e){e.arrayBuffer().then(i=>{var s,a;const o=globalThis.Buffer,r=o?o.from(i).toString("base64"):"";this.result=`data:${e.type};base64,${r}`,(s=this.onload)==null||s.call(this),(a=this.onloadend)==null||a.call(this)},i=>{var o,r;(o=this.onerror)==null||o.call(this,i),(r=this.onloadend)==null||r.call(this)})}}globalThis.FileReader=n}const ro=50*1024*1024;async function so(n,t){const e=[];switch(n.data.byteLength>ro&&e.push("File exceeds 50 MB; performance may be affected"),n.format){case"glb":case"gltf":return ao(n,e,t);case"stl":return co(n,e);case"obj":return lo(n,e)}}function di(n){const t=new eo.GLTFLoader,e=new to.DRACOLoader;return e.setDecoderPath((n==null?void 0:n.dracoDecoderPath)??gn),t.setDRACOLoader(e),t.setMeshoptDecoder(no.MeshoptDecoder),{loader:t,dispose:()=>{e.dispose()}}}async function ao(n,t,e){const{loader:i,dispose:o}=di({dracoDecoderPath:e});try{const r=await new Promise((s,a)=>{i.parse(n.data,"",s,a)});return _t(r.scene),{scene:r.scene,animations:r.animations,warnings:t}}catch(r){throw new Ae("Failed to parse GLTF/GLB",r)}finally{o()}}async function co(n,t){let e;try{e=(await import("three/examples/jsm/loaders/STLLoader.js")).STLLoader}catch(c){throw new Ae("Failed to load STL parser module. Please check your network connection.",c)}const i=new e;let o;try{o=i.parse(n.data)}catch(c){throw new Ae("Failed to parse STL",c)}const r=new v.MeshPhysicalMaterial({name:"metal",color:12632256,metalness:1,roughness:.1,envMapIntensity:1}),s=new v.Mesh(o,r);s.name="metal";const a=new v.Group;return a.add(s),_t(a),{scene:a,warnings:t}}async function lo(n,t){let e,i;try{const[a,c]=await Promise.all([import("three/examples/jsm/loaders/OBJLoader.js"),import("three/examples/jsm/loaders/MTLLoader.js")]);e=a.OBJLoader,i=c.MTLLoader}catch(a){throw new Ae("Failed to load OBJ parser module. Please check your network connection.",a)}n.mtlData||t.push("No material file provided; default material applied");let o;if(n.mtlData){const a=new i,c=new TextDecoder().decode(n.mtlData);try{o=a.parse(c,""),o.preload()}catch{t.push("Failed to parse MTL file; default material applied"),o=void 0}}const r=new e;o&&r.setMaterials(o);let s;try{const a=new TextDecoder().decode(n.data);s=r.parse(a)}catch(a){throw new Ae("Failed to parse OBJ",a)}return _t(s),{scene:s,warnings:t}}async function uo(n){let t;try{t=(await import("three/examples/jsm/exporters/GLTFExporter.js")).GLTFExporter}catch(i){throw new Ae("Failed to load GLTFExporter module. Please check your network connection.",i)}const e=new t;return new Promise((i,o)=>{e.parse(n,r=>{if(r instanceof ArrayBuffer)i(r);else{const s=JSON.stringify(r),a=new TextEncoder().encode(s);i(a.buffer)}},o,{binary:!0})})}class fo{constructor(){re(this,"_listeners",new Map)}on(t,e){return this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var i;(i=this._listeners.get(t))==null||i.delete(e)}emit(t,e){var i;(i=this._listeners.get(t))==null||i.forEach(o=>{try{o(e)}catch(r){console.error(`[3d-viewer] uncaught listener error on "${String(t)}":`,r)}})}clear(){this._listeners.clear()}}const mo={".stl":"stl",".obj":"obj",".glb":"glb",".gltf":"gltf"},po={"model/gltf-binary":"glb","model/gltf+json":"gltf"};function ho(n){try{const t=new URL(n,"http://dummy").pathname,e=t.lastIndexOf(".");if(e===-1)return null;const i=t.slice(e).toLowerCase();return mo[i]??null}catch{return null}}function yo(n){const t=n.split(";")[0].trim().toLowerCase();return po[t]??null}function Dn(n){if(n.byteLength<4)return null;const t=new Uint8Array(n,0,Math.min(n.byteLength,80));return t[0]===103&&t[1]===108&&t[2]===84&&t[3]===70?"glb":t[0]===123?"gltf":String.fromCharCode(...t.slice(0,5)).toLowerCase()==="solid"?"stl":null}async function Nn(n){const t=new Uint8Array(n);if(t.length>=2&&t[0]===31&&t[1]===139&&typeof DecompressionStream<"u")try{const e=new DecompressionStream("gzip"),i=new Blob([n]).stream().pipeThrough(e),o=await new Response(i).arrayBuffer();if(o.byteLength>0)return o}catch(e){console.warn("[fetchSource] Decompression failed, proceeding with original buffer:",e)}return n}async function go(n,t){if("data"in n){let s=n.data instanceof Blob?await n.data.arrayBuffer():n.data;s=await Nn(s);const a=n.mtlData instanceof Blob?await n.mtlData.arrayBuffer():n.mtlData,c=n.format||Dn(s)||"glb";return{data:s,mtlData:a,format:c}}let e=n.format??ho(n.url);const i=await fetch(n.url,{headers:n.headers,signal:t}).catch(s=>{throw s.name==="AbortError"?s:new ot(`Fetch failed: ${s.message}`,void 0,n.url)});if(!i.ok)throw new ot(`HTTP ${i.status}`,i.status,n.url);if(!e){const s=i.headers.get("content-type")??"";e=yo(s)}let o=await i.arrayBuffer();if(o=await Nn(o),e||(e=Dn(o)),!e)throw new Ft("unknown");let r;if(n.mtlUrl){const s=await fetch(n.mtlUrl,{headers:n.headers,signal:t});s.ok&&(r=await s.arrayBuffer())}return{data:o,mtlData:r,format:e}}const vo=["glb","gltf","obj","stl"];function mi(n){var i;const e=(i=n.split("?")[0].split("#")[0].split(".").pop())==null?void 0:i.toLowerCase();return e&&vo.includes(e)?e:"glb"}function bo(n){if(!n)return null;if(typeof n=="string"){const t=n.trim();return t?{url:t,format:mi(t)}:null}return n}async function pi(n,t,e,i){e==null||e(0);const o=await go(n,t);e==null||e(.3);const{scene:r,animations:s,warnings:a}=await so(o,i==null?void 0:i.dracoDecoderPath);e==null||e(.7);const c=o.format==="glb"?o.data:await uo(r);e==null||e(1);let u=0;return r.traverse(f=>{f.isMesh&&u++}),{glb:c,scene:r,animations:s,sourceFormat:o.format,meshCount:u,warnings:a}}const xo=["stone","diamond","gem","jewel","crystal"],wo=["metal","gold","silver","platinum","band","ring","prong","shank"];function Ln(n,t){const e=n.toLowerCase();return t.some(i=>e.includes(i))}function Vn(n){return n.trim().replace(/[^a-zA-Z0-9_-]/g,"_")}function Mo(n,t,e){var a,c;if(typeof((a=n.userData)==null?void 0:a.partId)=="string"&&n.userData.partId.trim()){const u=n.userData.partId.trim();return e.add(u),u}if(typeof((c=n.userData)==null?void 0:c.id)=="string"&&n.userData.id.trim()){const u=n.userData.id.trim();return e.add(u),u}if(n.name&&n.name.trim()){const u=n.name.trim();if(!e.has(u))return e.add(u),u}let i=n.name?n.name.trim():"mesh",o=n.parent;for(;o&&o!==t;)o.name&&o.name.trim()&&(i=`${o.name.trim()}/${i}`),o=o.parent;let r=i,s=1;for(;e.has(r);)r=`${i}_${s++}`;return e.add(r),r}function Ao(n){var o,r,s;if(Array.isArray((o=n.userData)==null?void 0:o.originalSlots)&&n.userData.originalSlots.length>0)return n.userData.originalSlots;if(Array.isArray(n.material))return n.material.map((a,c)=>{var d,l;const u=((d=a==null?void 0:a.name)==null?void 0:d.trim())||`Material_${c}`;return{slotId:typeof((l=a==null?void 0:a.userData)==null?void 0:l.slotId)=="string"&&a.userData.slotId||`slot_${c}_${Vn(u)}`,materialName:u,index:c}});const t=n.material,e=((r=t==null?void 0:t.name)==null?void 0:r.trim())||(n.name?`${n.name}_mat`:"default");return[{slotId:typeof((s=t==null?void 0:t.userData)==null?void 0:s.slotId)=="string"&&t.userData.slotId||`slot_0_${Vn(e)}`,materialName:e,index:0}]}function So(n,t){const e=`${n} ${t}`,i=Ln(e,xo),o=Ln(e,wo);return i?"stone":"metal"}function zn(n,t){const e=[],i=new Set;return n.traverse(o=>{var l;if(!(o instanceof v.Mesh))return;const r=o,s=Mo(r,n,i);r.userData.partId=s;const a=Ao(r);r.userData.originalSlots=a;const c=((l=a[0])==null?void 0:l.materialName)??"";r.userData.originalMaterialName=c;const u=a.map(m=>m.materialName).join(" "),f=r.uuid in t||s in t,d=t[s]??t[r.uuid];f&&d?e.push({meshId:r.uuid,partId:s,meshName:r.name,materialName:c,slots:a,type:d,overridden:!0}):e.push({meshId:r.uuid,partId:s,meshName:r.name,materialName:c,slots:a,type:So(r.name,u),overridden:!1})}),e}function kn(n){const t=new Map;for(const e of n)for(const i of e.slots){const o=t.get(i.slotId);o?(o.partIds.includes(e.partId)||o.partIds.push(e.partId),o.meshIds.includes(e.meshId)||o.meshIds.push(e.meshId),o.type!=="stone"&&e.type==="stone"&&(o.type="stone")):t.set(i.slotId,{slotId:i.slotId,name:i.materialName,type:e.type,partIds:[e.partId],meshIds:[e.meshId]})}return Array.from(t.values())}const Se=[{id:"yellow-gold-18k",label:"18K Yellow Gold",hex:"#ffd566",metalness:1,roughness:.04,category:"gold",specularColor:"#fffdbf",density:15500,thumbnail:"/thumbnails/yellow-gold-18k.svg"},{id:"yellow-gold-14k",label:"14K Yellow Gold",hex:"#fed882",metalness:1,roughness:.05,category:"gold",specularColor:"#fffec9",density:13500,thumbnail:"/thumbnails/yellow-gold-14k.svg"},{id:"pure-gold-24k",label:"24K Pure Gold",hex:"#ffe496",metalness:1,roughness:.03,category:"gold",specularColor:"#fffdbf",density:19320,source:"physicallybased.info/gold",thumbnail:"/thumbnails/pure-gold-24k.svg"},{id:"rose-gold-18k",label:"18K Rose Gold",hex:"#e8927c",metalness:1,roughness:.04,category:"gold",specularColor:"#ffd7cb",density:15400,thumbnail:"/thumbnails/rose-gold-18k.svg"},{id:"rose-gold-14k",label:"14K Rose Gold",hex:"#f1a998",metalness:1,roughness:.05,category:"gold",specularColor:"#ffe4db",density:13300,thumbnail:"/thumbnails/rose-gold-14k.svg"},{id:"white-gold-18k",label:"18K White Gold",hex:"#f5f6f8",metalness:1,roughness:.03,category:"gold",specularColor:"#ffffff",density:15600,thumbnail:"/thumbnails/white-gold-18k.svg"},{id:"platinum-950",label:"Platinum 950",hex:"#e3ded7",metalness:1,roughness:.04,category:"platinum-silver",specularColor:"#edebe6",density:21450,source:"physicallybased.info/platinum",thumbnail:"/thumbnails/platinum-950.svg"},{id:"silver-925",label:"Sterling Silver 925",hex:"#fefdfc",metalness:1,roughness:.05,category:"platinum-silver",specularColor:"#ffffff",density:10360,source:"physicallybased.info/silver",thumbnail:"/thumbnails/silver-925.svg"},{id:"titanium",label:"Titanium",hex:"#b1aaa2",metalness:1,roughness:.1,category:"alternative",specularColor:"#c8c3bd",density:4506,source:"physicallybased.info/titanium",thumbnail:"/thumbnails/titanium.svg"},{id:"black-ruthenium",label:"Black Ruthenium",hex:"#28282c",metalness:.95,roughness:.06,category:"alternative",specularColor:"#444448",density:12450,thumbnail:"/thumbnails/black-ruthenium.svg"},{id:"rmj-custom-yellow-gold",label:"RMJ Custom Yellow Gold",hex:"#ffc766",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-custom-yellow-gold.svg"},{id:"rmj-custom-rose-gold",label:"RMJ Custom Rose Gold",hex:"#ffb6a3",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-custom-rose-gold.svg"},{id:"rmj-white-gold-polished",label:"RMJ White Gold Polished",hex:"#c2c2c3",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-white-gold-polished.svg"},{id:"rmj-gold-polished",label:"RMJ Gold Polished (18K)",hex:"#e5b377",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-gold-polished.svg"},{id:"rmj-rose-gold-polished",label:"RMJ Rose Gold Polished",hex:"#f2af83",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-rose-gold-polished.svg"},{id:"rmj-gold-22k",label:"RMJ Gold 22K",hex:"#eaa958",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-gold-22k.svg"},{id:"rmj-gold-14k",label:"RMJ Gold 14K",hex:"#d6af80",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-gold-14k.svg"},{id:"rmj-gold-09k",label:"RMJ Gold 9K",hex:"#d4b38c",metalness:1,roughness:0,category:"gold",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-gold-09k.svg"},{id:"rmj-silver-polished",label:"RMJ Silver Polished",hex:"#dedede",metalness:1,roughness:.1,category:"platinum-silver",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-silver-polished.svg"},{id:"rmj-platinum-polished",label:"RMJ Platinum Polished",hex:"#b9bbbc",metalness:1,roughness:0,category:"platinum-silver",specularColor:"#ffffff",ior:1.5,source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-platinum-polished.svg"},{id:"yellow-gold",label:"Yellow Gold",hex:"#ffc766",metalness:1,roughness:.06,thumbnail:"/thumbnails/yellow-gold.svg"},{id:"rose-gold",label:"Rose Gold",hex:"#ffb6a3",metalness:1,roughness:.06,thumbnail:"/thumbnails/rose-gold.svg"},{id:"white-gold",label:"White Gold",hex:"#f0f0f0",metalness:1,roughness:.05,thumbnail:"/thumbnails/white-gold.svg"},{id:"platinum",label:"Platinum",hex:"#e5e5e5",metalness:1,roughness:.05,thumbnail:"/thumbnails/platinum.svg"},{id:"silver",label:"Silver",hex:"#dcdcdc",metalness:1,roughness:.08,thumbnail:"/thumbnails/silver.svg"}],de=[{id:"diamond-d",label:"White Diamond",hex:"#ffffff",ior:2.417,transmission:.98,roughness:0,category:"diamond",grade:"D-F Colorless",dispersion:.024,absorptionFactor:0,ambientFloor:.05,source:"physicallybased.info/diamond",thumbnail:"/thumbnails/diamond-d.svg"},{id:"diamond-gh",label:"Near Colorless Diamond",hex:"#fbf9f5",ior:2.417,transmission:.97,roughness:0,category:"diamond",grade:"G-H Near Colorless",dispersion:.012,absorptionFactor:0,ambientFloor:.05,thumbnail:"/thumbnails/diamond-gh.svg"},{id:"diamond-fancy-yellow",label:"Yellow Diamond",hex:"#fdd835",ior:2.417,transmission:.95,roughness:0,category:"diamond",grade:"Fancy Yellow",dispersion:.01,absorptionFactor:.11,thumbnail:"/thumbnails/diamond-fancy-yellow.svg"},{id:"diamond-fancy-pink",label:"Pink Diamond",hex:"#f472b6",ior:2.417,transmission:.94,roughness:0,category:"diamond",grade:"Fancy Pink",dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-pink.svg"},{id:"diamond-fancy-blue",label:"Blue Diamond",hex:"#38bdf8",ior:2.417,transmission:.94,roughness:0,category:"diamond",grade:"Fancy Blue",dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-blue.svg"},{id:"diamond-fancy-green",label:"Green Diamond",hex:"#34d399",ior:2.417,transmission:.94,roughness:0,category:"diamond",grade:"Fancy Green",dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-green.svg"},{id:"diamond-fancy-champagne",label:"Champagne Diamond",hex:"#c28b51",ior:2.417,transmission:.93,roughness:0,category:"diamond",grade:"Fancy Champagne",dispersion:.01,absorptionFactor:.18,thumbnail:"/thumbnails/diamond-fancy-champagne.svg"},{id:"diamond-fancy-black",label:"Black Diamond",hex:"#151515",ior:2.417,transmission:0,roughness:.05,category:"diamond",grade:"Fancy Black",dispersion:0,absorptionFactor:0,thumbnail:"/thumbnails/diamond-fancy-black.svg"},{id:"ruby",label:"Ruby",hex:"#e14276",ior:1.77,transmission:.88,roughness:.03,category:"gemstone",dispersion:0,absorptionFactor:.5,thumbnail:"/thumbnails/ruby.svg"},{id:"sapphire",label:"Sapphire",hex:"#1a4fb4",ior:1.77,transmission:.88,roughness:.03,category:"gemstone",dispersion:0,absorptionFactor:.45,source:"physicallybased.info/sapphire",thumbnail:"/thumbnails/sapphire.svg"},{id:"emerald",label:"Emerald",hex:"#20cc95",ior:1.58,transmission:.9,roughness:.04,category:"gemstone",dispersion:0,absorptionFactor:.4,thumbnail:"/thumbnails/emerald.svg"},{id:"aquamarine",label:"Aquamarine",hex:"#5eead4",ior:1.577,transmission:.94,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:.1,thumbnail:"/thumbnails/aquamarine.svg"},{id:"amethyst",label:"Amethyst",hex:"#9333ea",ior:1.544,transmission:.91,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:.35,source:"physicallybased.info/quartz",thumbnail:"/thumbnails/amethyst.svg"},{id:"tanzanite",label:"Tanzanite",hex:"#6366f1",ior:1.691,transmission:.9,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:.42,thumbnail:"/thumbnails/tanzanite.svg"},{id:"rmj-diamond-d-colorless",label:"RMJ Diamond D Colorless",hex:"#ececec",ior:2.4,transmission:.98,roughness:0,category:"diamond",dispersion:.004,absorptionFactor:1,boostFactors:[2,2,2],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-diamond-d-colorless.svg"},{id:"rmj-ruby-1",label:"RMJ Ruby 1",hex:"#e14276",ior:1.77,transmission:.88,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:1.6,boostFactors:[1.3,.16,.9],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-ruby-1.svg"},{id:"rmj-emerald-1",label:"RMJ Emerald 1",hex:"#20cc95",ior:1.577,transmission:.9,roughness:0,category:"gemstone",dispersion:.012,absorptionFactor:1,boostFactors:[.892,.892,.986],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-emerald-1.svg"},{id:"rmj-sapphire-cabachon-2",label:"RMJ Sapphire Cabochon 2",hex:"#45b1e1",ior:1.66,transmission:.88,roughness:0,category:"gemstone",dispersion:0,absorptionFactor:2.51,boostFactors:[1,1,1],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-sapphire-cabachon-2.svg"},{id:"rmj-diamond-pink-2",label:"RMJ Diamond Pink 2",hex:"#f1bcd5",ior:2.6,transmission:.94,roughness:0,category:"diamond",dispersion:.012,absorptionFactor:1,boostFactors:[1.3,1,1],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-diamond-pink-2.svg"},{id:"rmj-diamond-yellow-2",label:"RMJ Diamond Yellow 2",hex:"#fce88c",ior:2.6,transmission:.94,roughness:0,category:"diamond",dispersion:.012,absorptionFactor:1.3,boostFactors:[1,1,1],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-diamond-yellow-2.svg"},{id:"rmj-diamond-blue-2",label:"RMJ Diamond Blue 2",hex:"#80c9fc",ior:2.6,transmission:.94,roughness:0,category:"diamond",dispersion:.013,absorptionFactor:1,boostFactors:[.9,1,1],source:"app.rendermyjewelry.com",thumbnail:"/thumbnails/rmj-diamond-blue-2.svg"},{id:"diamond",label:"White Diamond",hex:"#ffffff",ior:2.417,transmission:.95,roughness:.02,dispersion:.012,absorptionFactor:0,ambientFloor:.05,thumbnail:"/thumbnails/diamond-d.svg"},{id:"yellow-diamond",label:"Yellow Diamond",hex:"#fcd34d",ior:2.42,transmission:.94,roughness:.02,dispersion:.01,absorptionFactor:.11,thumbnail:"/thumbnails/diamond-fancy-yellow.svg"},{id:"pink-diamond",label:"Pink Diamond",hex:"#f472b6",ior:2.42,transmission:.94,roughness:.02,dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-pink.svg"},{id:"blue-diamond",label:"Blue Diamond",hex:"#60a5fa",ior:2.42,transmission:.94,roughness:.02,dispersion:.01,absorptionFactor:.14,thumbnail:"/thumbnails/diamond-fancy-blue.svg"},{id:"black-diamond",label:"Black Diamond",hex:"#1a1a1a",ior:2.42,transmission:0,roughness:.05,dispersion:0,absorptionFactor:0,thumbnail:"/thumbnails/diamond-fancy-black.svg"}],vn=Se,bn=de,To=Se.filter(n=>n.category!==void 0&&!n.id.startsWith("rmj-"));Se.filter(n=>n.id.startsWith("rmj-"));const Co=de.filter(n=>n.category==="diamond"&&!n.id.startsWith("rmj-")&&n.id.startsWith("diamond-")),Bo=de.filter(n=>n.category==="gemstone"&&!n.id.startsWith("rmj-"));de.filter(n=>n.id.startsWith("rmj-"));const Po=new Set(["yellow-gold","rose-gold","white-gold","platinum","silver"]),Io=new Set(["diamond","yellow-diamond","pink-diamond","blue-diamond","black-diamond"]),Ro=Se.filter(n=>!Po.has(n.id)),Eo=de.filter(n=>!Io.has(n.id));function Fo(n){if(!n)return;const t=n.toLowerCase().trim();return Se.find(e=>e.id.toLowerCase()===t||e.hex.toLowerCase()===t)}function _o(n){if(!n)return;const t=n.toLowerCase().trim();return de.find(e=>e.id.toLowerCase()===t||e.hex.toLowerCase()===t)}const Un=new WeakMap;function Do(n){var g,x;n.boundingSphere||n.computeBoundingSphere();const t=(g=n.boundingSphere)!=null&&g.center?n.boundingSphere.center.clone():new v.Vector3,e=((x=n.boundingSphere)==null?void 0:x.radius)??1,i=Math.max(e,.01),o=n.getAttribute("position");if(!o||o.count===0)return{centroid:t,radius:i,triangleCount:0,starConvexFailureArea:1,isBakeable:!1,flippedWinding:!1};const r=n.getIndex(),s=r?r.count/3:o.count/3;let a=0,c=0,u=0;const f=new v.Vector3,d=new v.Vector3,l=new v.Vector3,m=new v.Vector3,p=new v.Vector3,w=new v.Vector3,y=new v.Vector3;for(let b=0;b<s;b++){const A=r?r.getX(b*3):b*3,S=r?r.getX(b*3+1):b*3+1,P=r?r.getX(b*3+2):b*3+2;f.fromBufferAttribute(o,A).sub(t).divideScalar(i),d.fromBufferAttribute(o,S).sub(t).divideScalar(i),l.fromBufferAttribute(o,P).sub(t).divideScalar(i),m.subVectors(d,f),p.subVectors(l,f),w.crossVectors(m,p);const E=w.length();if(E<1e-12)continue;const T=E*.5;a+=T,w.divideScalar(E);const R=f.dot(w);y.crossVectors(d,l),u+=f.dot(y)/6,R<=1e-4&&(c+=T)}const M=a>0?c/a:1,h=u<0;return{centroid:t,radius:i,triangleCount:s,starConvexFailureArea:M,isBakeable:M<=.005&&!isNaN(a)&&a>0,flippedWinding:h}}function No(n,t){const e=n.getIndex()!==null,i=e?n.toNonIndexed():n;try{const o=i.getAttribute("position");if(!o)return new Float32Array(0);const r=o.count,s=new Float32Array(r*4),a=new v.Vector3,c=new v.Vector3,u=new v.Vector3,f=new v.Vector3,d=new v.Vector3,l=new v.Vector3,m=t.flippedWinding?-1:1;for(let p=0;p<r;p+=3){a.fromBufferAttribute(o,p).sub(t.centroid).divideScalar(t.radius),c.fromBufferAttribute(o,p+1).sub(t.centroid).divideScalar(t.radius),u.fromBufferAttribute(o,p+2).sub(t.centroid).divideScalar(t.radius),f.subVectors(c,a),d.subVectors(u,a),l.crossVectors(f,d).multiplyScalar(m);const w=l.length();w>1e-12?l.divideScalar(w):l.set(0,1,0);const y=a.dot(l);for(let M=0;M<3;M++){const h=(p+M)*4;s[h]=l.x,s[h+1]=l.y,s[h+2]=l.z,s[h+3]=y}}return s}finally{e&&i.dispose()}}function Lo(n,t){const e=Un.get(n);if(e)return e;const i=n.getAttribute("position"),o=n.getIndex();let r=2166136261;const s=u=>{r^=u&255,r=Math.imul(r,16777619),r^=u>>8&255,r=Math.imul(r,16777619),r^=u>>16&255,r=Math.imul(r,16777619),r^=u>>24&255,r=Math.imul(r,16777619)};if(s(t.triangleCount),o)for(let u=0;u<o.count;u++)s(o.getX(u));const a=new v.Vector3;for(let u=0;u<i.count;u++)a.fromBufferAttribute(i,u).sub(t.centroid).divideScalar(t.radius),s(Math.round(a.x*1e4)),s(Math.round(a.y*1e4)),s(Math.round(a.z*1e4));const c=(r>>>0).toString(16);return Un.set(n,c),c}const hi=0,Vo=1,yi=2,Gn=2,qt=1.25,On=1,te=6*4+4+4,J=te/4,xn=65535,zo=xn<<16,Ct=Math.pow(2,-24),wn=Symbol("SKIP_GENERATION"),gi={strategy:hi,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[wn]:!1};function W(n,t,e){return e.min.x=t[n],e.min.y=t[n+1],e.min.z=t[n+2],e.max.x=t[n+3],e.max.y=t[n+4],e.max.z=t[n+5],e}function nn(n){let t=-1,e=-1/0;for(let i=0;i<3;i++){const o=n[i+3]-n[i];o>e&&(e=o,t=i)}return t}function Hn(n,t){t.set(n)}function qn(n,t,e){let i,o;for(let r=0;r<3;r++){const s=r+3;i=n[r],o=t[r],e[r]=i<o?i:o,i=n[s],o=t[s],e[s]=i>o?i:o}}function ut(n,t,e){for(let i=0;i<3;i++){const o=t[n+2*i],r=t[n+2*i+1],s=o-r,a=o+r;s<e[i]&&(e[i]=s),a>e[i+3]&&(e[i+3]=a)}}function je(n){const t=n[3]-n[0],e=n[4]-n[1],i=n[5]-n[2];return 2*(t*e+e*i+i*t)}function Y(n,t){return t[n+15]===xn}function Z(n,t){return t[n+6]}function ie(n,t){return t[n+14]}function Q(n){return n+J}function ee(n,t){const e=t[n+6];return n+e*J}function Dt(n,t){return t[n+7]}function $t(n,t,e,i,o){let r=1/0,s=1/0,a=1/0,c=-1/0,u=-1/0,f=-1/0,d=1/0,l=1/0,m=1/0,p=-1/0,w=-1/0,y=-1/0;const M=n.offset||0;for(let h=(t-M)*6,g=(t+e-M)*6;h<g;h+=6){const x=n[h+0],b=n[h+1],A=x-b,S=x+b;A<r&&(r=A),S>c&&(c=S),x<d&&(d=x),x>p&&(p=x);const P=n[h+2],E=n[h+3],T=P-E,R=P+E;T<s&&(s=T),R>u&&(u=R),P<l&&(l=P),P>w&&(w=P);const B=n[h+4],F=n[h+5],_=B-F,V=B+F;_<a&&(a=_),V>f&&(f=V),B<m&&(m=B),B>y&&(y=B)}i[0]=r,i[1]=s,i[2]=a,i[3]=c,i[4]=u,i[5]=f,o[0]=d,o[1]=l,o[2]=m,o[3]=p,o[4]=w,o[5]=y}const xe=32,ko=(n,t)=>n.candidate-t.candidate,Be=new Array(xe).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),ft=new Float32Array(6);function Uo(n,t,e,i,o,r){let s=-1,a=0;if(r===hi)s=nn(t),s!==-1&&(a=(t[s]+t[s+3])/2);else if(r===Vo)s=nn(n),s!==-1&&(a=Go(e,i,o,s));else if(r===yi){const c=je(n);let u=qt*o;const f=e.offset||0,d=(i-f)*6,l=(i+o-f)*6;for(let m=0;m<3;m++){const p=t[m],M=(t[m+3]-p)/xe;if(o<xe/4){const h=[...Be];h.length=o;let g=0;for(let b=d;b<l;b+=6,g++){const A=h[g];A.candidate=e[b+2*m],A.count=0;const{bounds:S,leftCacheBounds:P,rightCacheBounds:E}=A;for(let T=0;T<3;T++)E[T]=1/0,E[T+3]=-1/0,P[T]=1/0,P[T+3]=-1/0,S[T]=1/0,S[T+3]=-1/0;ut(b,e,S)}h.sort(ko);let x=o;for(let b=0;b<x;b++){const A=h[b];for(;b+1<x&&h[b+1].candidate===A.candidate;)h.splice(b+1,1),x--}for(let b=d;b<l;b+=6){const A=e[b+2*m];for(let S=0;S<x;S++){const P=h[S];A>=P.candidate?ut(b,e,P.rightCacheBounds):(ut(b,e,P.leftCacheBounds),P.count++)}}for(let b=0;b<x;b++){const A=h[b],S=A.count,P=o-A.count,E=A.leftCacheBounds,T=A.rightCacheBounds;let R=0;S!==0&&(R=je(E)/c);let B=0;P!==0&&(B=je(T)/c);const F=On+qt*(R*S+B*P);F<u&&(s=m,u=F,a=A.candidate)}}else{for(let x=0;x<xe;x++){const b=Be[x];b.count=0,b.candidate=p+M+x*M;const A=b.bounds;for(let S=0;S<3;S++)A[S]=1/0,A[S+3]=-1/0}for(let x=d;x<l;x+=6){let S=~~((e[x+2*m]-p)/M);S>=xe&&(S=xe-1);const P=Be[S];P.count++,ut(x,e,P.bounds)}const h=Be[xe-1];Hn(h.bounds,h.rightCacheBounds);for(let x=xe-2;x>=0;x--){const b=Be[x],A=Be[x+1];qn(b.bounds,A.rightCacheBounds,b.rightCacheBounds)}let g=0;for(let x=0;x<xe-1;x++){const b=Be[x],A=b.count,S=b.bounds,E=Be[x+1].rightCacheBounds;A!==0&&(g===0?Hn(S,ft):qn(S,ft,ft)),g+=A;let T=0,R=0;g!==0&&(T=je(ft)/c);const B=o-g;B!==0&&(R=je(E)/c);const F=On+qt*(T*g+R*B);F<u&&(s=m,u=F,a=b.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:s,pos:a}}function Go(n,t,e,i){let o=0;const r=n.offset;for(let s=t,a=t+e;s<a;s++)o+=n[(s-r)*6+i*2];return o/e}class Wt{constructor(){this.boundingData=new Float32Array(6)}}function Oo(n,t,e,i,o,r){let s=i,a=i+o-1;const c=r.pos,u=r.axis*2,f=e.offset||0;for(;;){for(;s<=a&&e[(s-f)*6+u]<c;)s++;for(;s<=a&&e[(a-f)*6+u]>=c;)a--;if(s<a){for(let d=0;d<t;d++){let l=n[s*t+d];n[s*t+d]=n[a*t+d],n[a*t+d]=l}for(let d=0;d<6;d++){const l=s-f,m=a-f,p=e[l*6+d];e[l*6+d]=e[m*6+d],e[m*6+d]=p}s++,a--}else return s}}let vi,Bt,on,bi;const Ho=Math.pow(2,32);function rn(n){return"count"in n?1:1+rn(n.left)+rn(n.right)}function qo(n,t,e){return vi=new Float32Array(e),Bt=new Uint32Array(e),on=new Uint16Array(e),bi=new Uint8Array(e),sn(n,t)}function sn(n,t){const e=n/4,i=n/2,o="count"in t,r=t.boundingData;for(let s=0;s<6;s++)vi[e+s]=r[s];if(o)return t.buffer?(bi.set(new Uint8Array(t.buffer),n),n+t.buffer.byteLength):(Bt[e+6]=t.offset,on[i+14]=t.count,on[i+15]=xn,n+te);{const{left:s,right:a,splitAxis:c}=t,u=n+te;let f=sn(u,s);const d=n/te,m=f/te-d;if(m>Ho)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Bt[e+6]=m,Bt[e+7]=c,sn(f,a)}}function $o(n,t,e,i,o,r){const{maxDepth:s,verbose:a,targetLeafSize:c,_strictLeafSize:u=1/0,strategy:f,onProgress:d}=o,l=n.primitiveBuffer,m=n.primitiveBufferStride,p=new Float32Array(6);let w=!1;const y=new Wt;return $t(t,e,i,y.boundingData,p),h(y,e,i,p),y;function M(g){d&&d((g-r.offset)/r.count)}function h(g,x,b,A=null,S=0){!w&&S>=s&&(w=!0,a&&console.warn(`BVH: Max depth of ${s} reached when generating BVH. Consider increasing maxDepth.`));const P=b>u;if(b<=c&&!P||S>=s)return M(x+b),g.offset=x,g.count=b,g;const E=Uo(g.boundingData,A,t,x,b,f);let T=E.axis===-1?-1:Oo(l,m,t,x,b,E);if(E.axis===-1||T===x||T===x+b){if(!P)return M(x+b),g.offset=x,g.count=b,g;E.axis=Math.max(0,nn(g.boundingData)),T=x+Math.max(1,Math.floor(b/2))}g.splitAxis=E.axis;const R=new Wt,B=x,F=T-x;g.left=R,$t(t,B,F,R.boundingData,p),h(R,B,F,p,S+1);const _=new Wt,V=T,U=b-F;return g.right=_,$t(t,V,U,_.boundingData,p),h(_,V,U,p,S+1),g}}function Wo(n,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=n.getRootRanges(t.range),o=i[0],r=i[i.length-1],s={offset:o.offset,count:r.offset+r.count-o.offset},a=new Float32Array(6*s.count);a.offset=s.offset,n.computePrimitiveBounds(s.offset,s.count,a),n._roots=i.map(c=>{const u=$o(n,a,c.offset,c.count,t,s),f=rn(u),d=new e(te*f);return qo(0,u,d),d})}class Mn{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class Yo{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const H=new Yo;let Ie,Ye;const Ve=[],dt=new Mn(()=>new C.Box3);function Xo(n,t,e,i,o,r){Ie=dt.getPrimitive(),Ye=dt.getPrimitive(),Ve.push(Ie,Ye),H.setBuffer(n._roots[t]);const s=an(0,n.geometry,e,i,o,r);H.clearBuffer(),dt.releasePrimitive(Ie),dt.releasePrimitive(Ye),Ve.pop(),Ve.pop();const a=Ve.length;return a>0&&(Ye=Ve[a-1],Ie=Ve[a-2]),s}function an(n,t,e,i,o=null,r=0,s=0){const{float32Array:a,uint16Array:c,uint32Array:u}=H;let f=n*2;if(Y(f,c)){const l=Z(n,u),m=ie(f,c);return W(n,a,Ie),i(l,m,!1,s,r+n/J,Ie)}else{let T=function(B){const{uint16Array:F,uint32Array:_}=H;let V=B*2;for(;!Y(V,F);)B=Q(B),V=B*2;return Z(B,_)},R=function(B){const{uint16Array:F,uint32Array:_}=H;let V=B*2;for(;!Y(V,F);)B=ee(B,_),V=B*2;return Z(B,_)+ie(V,F)};const l=Q(n),m=ee(n,u);let p=l,w=m,y,M,h,g;if(o&&(h=Ie,g=Ye,W(p,a,h),W(w,a,g),y=o(h),M=o(g),M<y)){p=m,w=l;const B=y;y=M,M=B,h=g}h||(h=Ie,W(p,a,h));const x=Y(p*2,c),b=e(h,x,y,s+1,r+p/J);let A;if(b===Gn){const B=T(p),_=R(p)-B;A=i(B,_,!0,s+1,r+p/J,h)}else A=b&&an(p,t,e,i,o,r,s+1);if(A)return!0;g=Ye,W(w,a,g);const S=Y(w*2,c),P=e(g,S,M,s+1,r+w/J);let E;if(P===Gn){const B=T(w),_=R(w)-B;E=i(B,_,!0,s+1,r+w/J,g)}else E=P&&an(w,t,e,i,o,r,s+1);return!!E}}const it=new H.constructor,Pt=new H.constructor,Pe=new Mn(()=>new C.Box3),ze=new C.Box3,ke=new C.Box3,Yt=new C.Box3,Xt=new C.Box3;let jt=!1;function jo(n,t,e,i){if(jt)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");jt=!0;const o=n._roots,r=t._roots;let s,a=0,c=0;const u=new C.Matrix4().copy(e).invert();for(let f=0,d=o.length;f<d;f++){it.setBuffer(o[f]),c=0;const l=Pe.getPrimitive();W(0,it.float32Array,l),l.applyMatrix4(u);for(let m=0,p=r.length;m<p&&(Pt.setBuffer(r[m]),s=pe(0,0,e,u,i,a,c,0,0,l),Pt.clearBuffer(),c+=r[m].byteLength/te,!s);m++);if(Pe.releasePrimitive(l),it.clearBuffer(),a+=o[f].byteLength/te,s)break}return jt=!1,s}function pe(n,t,e,i,o,r=0,s=0,a=0,c=0,u=null,f=!1){let d,l;f?(d=Pt,l=it):(d=it,l=Pt);const m=d.float32Array,p=d.uint32Array,w=d.uint16Array,y=l.float32Array,M=l.uint32Array,h=l.uint16Array,g=n*2,x=t*2,b=Y(g,w),A=Y(x,h);let S=!1;if(A&&b)f?S=o(Z(t,M),ie(t*2,h),Z(n,p),ie(n*2,w),c,s+t/J,a,r+n/J):S=o(Z(n,p),ie(n*2,w),Z(t,M),ie(t*2,h),a,r+n/J,c,s+t/J);else if(A){const P=Pe.getPrimitive();W(t,y,P),P.applyMatrix4(e);const E=Q(n),T=ee(n,p);W(E,m,ze),W(T,m,ke);const R=P.intersectsBox(ze),B=P.intersectsBox(ke);S=R&&pe(t,E,i,e,o,s,r,c,a+1,P,!f)||B&&pe(t,T,i,e,o,s,r,c,a+1,P,!f),Pe.releasePrimitive(P)}else{const P=Q(t),E=ee(t,M);W(P,y,Yt),W(E,y,Xt);const T=u.intersectsBox(Yt),R=u.intersectsBox(Xt);if(T&&R)S=pe(n,P,e,i,o,r,s,a,c+1,u,f)||pe(n,E,e,i,o,r,s,a,c+1,u,f);else if(T)if(b)S=pe(n,P,e,i,o,r,s,a,c+1,u,f);else{const B=Pe.getPrimitive();B.copy(Yt).applyMatrix4(e);const F=Q(n),_=ee(n,p);W(F,m,ze),W(_,m,ke);const V=B.intersectsBox(ze),U=B.intersectsBox(ke);S=V&&pe(P,F,i,e,o,s,r,c,a+1,B,!f)||U&&pe(P,_,i,e,o,s,r,c,a+1,B,!f),Pe.releasePrimitive(B)}else if(R)if(b)S=pe(n,E,e,i,o,r,s,a,c+1,u,f);else{const B=Pe.getPrimitive();B.copy(Xt).applyMatrix4(e);const F=Q(n),_=ee(n,p);W(F,m,ze),W(_,m,ke);const V=B.intersectsBox(ze),U=B.intersectsBox(ke);S=V&&pe(E,F,i,e,o,s,r,c,a+1,B,!f)||U&&pe(E,_,i,e,o,s,r,c,a+1,B,!f),Pe.releasePrimitive(B)}}return S}const Kt=new class{constructor(){let n=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(r,s)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=s,this.buffer=n=r._roots[s],this.uint16Array=e=new Uint16Array(n),this.uint32Array=t=new Uint32Array(n)},this.reset=()=>{this.root=null,this.buffer=n=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=r=>{let s=r*2;for(;!Y(s,e);)r=Q(r),s=r*2;return Z(r,t)},this.getRangeEnd=r=>{let s=r*2;for(;!Y(s,e);)r=ee(r,t),s=r*2;return Z(r,t)+ie(s,e)};const o=(r,s,a)=>{const c=s*2,u=Y(c,e);if(!r(a,u,s)&&!u){const d=Q(s),l=ee(s,t);o(r,d,a+1),o(r,l,a+1)}};this.traverseBuffer=r=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{o(r,0,0)}finally{i=!1}},this.traverse=r=>{this.traverseBuffer((s,a,c)=>{if(a){const u=c*2,f=t[c+6],d=e[u+14];return r(s,a,new Float32Array(n,c*4,6),f,d)}else{const u=Dt(c,t);return r(s,a,new Float32Array(n,c*4,6),u)}})}}},$n=new C.Box3,Ue=new Float32Array(6);class Ko{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...gi,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),Wo(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,o){let r=1/0,s=1/0,a=1/0,c=-1/0,u=-1/0,f=-1/0;for(let d=t,l=t+e;d<l;d++){this.writePrimitiveBounds(d,Ue,0);const[m,p,w,y,M,h]=Ue;m<r&&(r=m),y>c&&(c=y),p<s&&(s=p),M>u&&(u=M),w<a&&(a=w),h>f&&(f=h)}return i[o+0]=r,i[o+1]=s,i[o+2]=a,i[o+3]=c,i[o+4]=u,i[o+5]=f,i}computePrimitiveBounds(t,e,i){const o=i.offset||0;for(let r=t,s=t+e;r<s;r++){this.writePrimitiveBounds(r,Ue,0);const[a,c,u,f,d,l]=Ue,m=(a+f)/2,p=(c+d)/2,w=(u+l)/2,y=(f-a)/2,M=(d-c)/2,h=(l-u)/2,g=(r-o)*6;i[g+0]=m,i[g+1]=y+(Math.abs(m)+y)*Ct,i[g+2]=p,i[g+3]=M+(Math.abs(p)+M)*Ct,i[g+4]=w,i[g+5]=h+(Math.abs(w)+h)*Ct}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,o=e.length;i<o;i++)e[i]+=t;else{const i=this._roots;for(let o=0;o<i.length;o++){const r=i[o],s=new Uint32Array(r),a=new Uint16Array(r),c=r.byteLength/te;for(let u=0;u<c;u++){const f=J*u,d=2*f;Y(d,a)&&(s[f+6]+=t)}}}}traverse(t,e=0){Kt.setBVH(this,e),Kt.traverse(t),Kt.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const o=t[e],r=new Uint32Array(o),s=new Uint16Array(o),a=new Float32Array(o),c=o.byteLength/te;for(let u=c-1;u>=0;u--){const f=u*J,d=f*2;if(Y(d,s)){const m=Z(f,r),p=ie(d,s);this.writePrimitiveRangeBounds(m,p,Ue,0),a.set(Ue,f)}else{const m=Q(f),p=ee(f,r);for(let w=0;w<3;w++){const y=a[m+w],M=a[m+w+3],h=a[p+w],g=a[p+w+3];a[f+w]=y<h?y:h,a[f+w+3]=M>g?M:g}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{W(0,new Float32Array(i),$n),t.union($n)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:o,intersectsPrimitive:r,scratchPrimitive:s,iterate:a}=t;if(o&&r){const d=o;o=(l,m,p,w,y)=>d(l,m,p,w,y)?!0:a(l,m,this,r,p,w,s)}else o||(r?o=(d,l,m,p)=>a(d,l,this,r,m,p,s):o=(d,l,m)=>m);let c=!1,u=0;const f=this._roots;for(let d=0,l=f.length;d<l;d++){const m=f[d];if(c=Xo(this,d,i,o,e,u),c)break;u+=m.byteLength/te}return c}bvhcast(t,e,i){let{intersectsRanges:o}=i;return jo(this,t,e,o)}}function Jo(){return typeof SharedArrayBuffer<"u"}function Nt(n){return n.index?n.index.count:n.attributes.position.count}function Lt(n){return Nt(n)/3}function xi(n,t=ArrayBuffer){return n>65535?new Uint32Array(new t(4*n)):new Uint16Array(new t(2*n))}function Zo(n,t){if(!n.index){const e=n.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,o=xi(e,i);n.setIndex(new C.BufferAttribute(o,1));for(let r=0;r<e;r++)o[r]=r}}function Qo(n,t,e){const i=Nt(n)/e,o=t||n.drawRange,r=o.start/e,s=(o.start+o.count)/e,a=Math.max(0,r),c=Math.min(i,s)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function er(n,t){return n.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function Wn(n,t,e){const i=Qo(n,t,e),o=er(n,e);if(!o.length)return[i];const r=[],s=i.offset,a=i.offset+i.count,c=Nt(n)/e,u=[];for(const l of o){const{offset:m,count:p}=l,w=m,y=isFinite(p)?p:c-m,M=m+y;w<a&&M>s&&(u.push({pos:Math.max(s,w),isStart:!0}),u.push({pos:Math.min(a,M),isStart:!1}))}u.sort((l,m)=>l.pos!==m.pos?l.pos-m.pos:l.type==="end"?-1:1);let f=0,d=null;for(const l of u){const m=l.pos;f!==0&&m!==d&&r.push({offset:d,count:m-d}),f+=l.isStart?1:-1,d=m}return r}function tr(n,t){const e=n[n.length-1],i=e.offset+e.count>2**16,o=n.reduce((u,f)=>u+f.count,0),r=i?4:2,s=t?new SharedArrayBuffer(o*r):new ArrayBuffer(o*r),a=i?new Uint32Array(s):new Uint16Array(s);let c=0;for(let u=0;u<n.length;u++){const{offset:f,count:d}=n[u];for(let l=0;l<d;l++)a[c+l]=f+l;c+=d}return a}class nr extends Ko{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!Jo())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...gi,...e},e[wn]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const o=Wn(e,t.range,i),r=tr(o,t.useSharedArrayBuffer);this._indirectBuffer=r}else Zo(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new C.Box3))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Wn(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Te{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,o=-1/0;for(let r=0,s=t.length;r<s;r++){const c=t[r][e];i=c<i?c:i,o=c>o?c:o}this.min=i,this.max=o}setFromPoints(t,e){let i=1/0,o=-1/0;for(let r=0,s=e.length;r<s;r++){const a=e[r],c=t.dot(a);i=c<i?c:i,o=c>o?c:o}this.min=i,this.max=o}isSeparated(t){return this.min>t.max||t.min>this.max}}Te.prototype.setFromBox=function(){const n=new C.Vector3;return function(e,i){const o=i.min,r=i.max;let s=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let u=0;u<=1;u++)for(let f=0;f<=1;f++){n.x=o.x*c+r.x*(1-c),n.y=o.y*u+r.y*(1-u),n.z=o.z*f+r.z*(1-f);const d=e.dot(n);s=Math.min(d,s),a=Math.max(d,a)}this.min=s,this.max=a}}();const ir=function(){const n=new C.Vector3,t=new C.Vector3,e=new C.Vector3;return function(o,r,s){const a=o.start,c=n,u=r.start,f=t;e.subVectors(a,u),n.subVectors(o.end,o.start),t.subVectors(r.end,r.start);const d=e.dot(f),l=f.dot(c),m=f.dot(f),p=e.dot(c),y=c.dot(c)*m-l*l;let M,h;y!==0?M=(d*l-p*m)/y:M=0,h=(d+M*l)/m,s.x=M,s.y=h}}(),An=function(){const n=new C.Vector2,t=new C.Vector3,e=new C.Vector3;return function(o,r,s,a){ir(o,r,n);let c=n.x,u=n.y;if(c>=0&&c<=1&&u>=0&&u<=1){o.at(c,s),r.at(u,a);return}else if(c>=0&&c<=1){u<0?r.at(0,a):r.at(1,a),o.closestPointToPoint(a,!0,s);return}else if(u>=0&&u<=1){c<0?o.at(0,s):o.at(1,s),r.closestPointToPoint(s,!0,a);return}else{let f;c<0?f=o.start:f=o.end;let d;u<0?d=r.start:d=r.end;const l=t,m=e;if(o.closestPointToPoint(d,!0,t),r.closestPointToPoint(f,!0,e),l.distanceToSquared(d)<=m.distanceToSquared(f)){s.copy(l),a.copy(d);return}else{s.copy(f),a.copy(m);return}}}}(),or=function(){const n=new C.Vector3,t=new C.Vector3,e=new C.Plane,i=new C.Line3;return function(r,s){const{radius:a,center:c}=r,{a:u,b:f,c:d}=s;if(i.start=u,i.end=f,i.closestPointToPoint(c,!0,n).distanceTo(c)<=a||(i.start=u,i.end=d,i.closestPointToPoint(c,!0,n).distanceTo(c)<=a)||(i.start=f,i.end=d,i.closestPointToPoint(c,!0,n).distanceTo(c)<=a))return!0;const w=s.getPlane(e);if(Math.abs(w.distanceToPoint(c))<=a){const M=w.projectPoint(c,t);if(s.containsPoint(M))return!0}return!1}}(),rr=["x","y","z"],we=1e-15,Yn=we*we;function ue(n){return Math.abs(n)<we}class he extends C.Triangle{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new C.Vector3),this.satBounds=new Array(4).fill().map(()=>new Te),this.points=[this.a,this.b,this.c],this.plane=new C.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new C.Line3,this.needsUpdate=!0}intersectsSphere(t){return or(t,this)}update(){const t=this.a,e=this.b,i=this.c,o=this.points,r=this.satAxes,s=this.satBounds,a=r[0],c=s[0];this.getNormal(a),c.setFromPoints(a,o);const u=r[1],f=s[1];u.subVectors(t,e),f.setFromPoints(u,o);const d=r[2],l=s[2];d.subVectors(e,i),l.setFromPoints(d,o);const m=r[3],p=s[3];m.subVectors(i,t),p.setFromPoints(m,o);const w=u.length(),y=d.length(),M=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,w<we?y<we||M<we?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):y<we?M<we?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):M<we&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}he.prototype.closestPointToSegment=function(){const n=new C.Vector3,t=new C.Vector3,e=new C.Line3;return function(o,r=null,s=null){const{start:a,end:c}=o,u=this.points;let f,d=1/0;for(let l=0;l<3;l++){const m=(l+1)%3;e.start.copy(u[l]),e.end.copy(u[m]),An(e,o,n,t),f=n.distanceToSquared(t),f<d&&(d=f,r&&r.copy(n),s&&s.copy(t))}return this.closestPointToPoint(a,n),f=a.distanceToSquared(n),f<d&&(d=f,r&&r.copy(n),s&&s.copy(a)),this.closestPointToPoint(c,n),f=c.distanceToSquared(n),f<d&&(d=f,r&&r.copy(n),s&&s.copy(c)),Math.sqrt(d)}}();he.prototype.intersectsTriangle=function(){const n=new he,t=new Te,e=new Te,i=new C.Vector3,o=new C.Vector3,r=new C.Vector3,s=new C.Vector3,a=new C.Line3,c=new C.Line3,u=new C.Vector3,f=new C.Vector2,d=new C.Vector2;function l(g,x,b,A){const S=i;!g.isDegenerateIntoPoint&&!g.isDegenerateIntoSegment?S.copy(g.plane.normal):S.copy(x.plane.normal);const P=g.satBounds,E=g.satAxes;for(let B=1;B<4;B++){const F=P[B],_=E[B];if(t.setFromPoints(_,x.points),F.isSeparated(t)||(s.copy(S).cross(_),t.setFromPoints(s,g.points),e.setFromPoints(s,x.points),t.isSeparated(e)))return!1}const T=x.satBounds,R=x.satAxes;for(let B=1;B<4;B++){const F=T[B],_=R[B];if(t.setFromPoints(_,g.points),F.isSeparated(t)||(s.crossVectors(S,_),t.setFromPoints(s,g.points),e.setFromPoints(s,x.points),t.isSeparated(e)))return!1}return b&&(A||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),b.start.set(0,0,0),b.end.set(0,0,0)),!0}function m(g,x,b,A,S,P,E,T,R,B,F){let _=E/(E-T);B.x=A+(S-A)*_,F.start.subVectors(x,g).multiplyScalar(_).add(g),_=E/(E-R),B.y=A+(P-A)*_,F.end.subVectors(b,g).multiplyScalar(_).add(g)}function p(g,x,b,A,S,P,E,T,R,B,F){if(S>0)m(g.c,g.a,g.b,A,x,b,R,E,T,B,F);else if(P>0)m(g.b,g.a,g.c,b,x,A,T,E,R,B,F);else if(T*R>0||E!=0)m(g.a,g.b,g.c,x,b,A,E,T,R,B,F);else if(T!=0)m(g.b,g.a,g.c,b,x,A,T,E,R,B,F);else if(R!=0)m(g.c,g.a,g.b,A,x,b,R,E,T,B,F);else return!0;return!1}function w(g,x,b,A){const S=x.degenerateSegment,P=g.plane.distanceToPoint(S.start),E=g.plane.distanceToPoint(S.end);return ue(P)?ue(E)?l(g,x,b,A):(b&&(b.start.copy(S.start),b.end.copy(S.start)),g.containsPoint(S.start)):ue(E)?(b&&(b.start.copy(S.end),b.end.copy(S.end)),g.containsPoint(S.end)):g.plane.intersectLine(S,i)!=null?(b&&(b.start.copy(i),b.end.copy(i)),g.containsPoint(i)):!1}function y(g,x,b){const A=x.a;return ue(g.plane.distanceToPoint(A))&&g.containsPoint(A)?(b&&(b.start.copy(A),b.end.copy(A)),!0):!1}function M(g,x,b){const A=g.degenerateSegment,S=x.a;return A.closestPointToPoint(S,!0,i),S.distanceToSquared(i)<Yn?(b&&(b.start.copy(S),b.end.copy(S)),!0):!1}function h(g,x,b,A){if(g.isDegenerateIntoSegment)if(x.isDegenerateIntoSegment){const S=g.degenerateSegment,P=x.degenerateSegment,E=o,T=r;S.delta(E),P.delta(T);const R=i.subVectors(P.start,S.start),B=E.x*T.y-E.y*T.x;if(ue(B))return!1;const F=(R.x*T.y-R.y*T.x)/B,_=-(E.x*R.y-E.y*R.x)/B;if(F<0||F>1||_<0||_>1)return!1;const V=S.start.z+E.z*F,U=P.start.z+T.z*_;return ue(V-U)?(b&&(b.start.copy(S.start).addScaledVector(E,F),b.end.copy(S.start).addScaledVector(E,F)),!0):!1}else return x.isDegenerateIntoPoint?M(g,x,b):w(x,g,b,A);else{if(g.isDegenerateIntoPoint)return x.isDegenerateIntoPoint?x.a.distanceToSquared(g.a)<Yn?(b&&(b.start.copy(g.a),b.end.copy(g.a)),!0):!1:x.isDegenerateIntoSegment?M(x,g,b):y(x,g,b);if(x.isDegenerateIntoPoint)return y(g,x,b);if(x.isDegenerateIntoSegment)return w(g,x,b,A)}}return function(x,b=null,A=!1){this.needsUpdate&&this.update(),x.isExtendedTriangle?x.needsUpdate&&x.update():(n.copy(x),n.update(),x=n);const S=h(this,x,b,A);if(S!==void 0)return S;const P=this.plane,E=x.plane;let T=E.distanceToPoint(this.a),R=E.distanceToPoint(this.b),B=E.distanceToPoint(this.c);ue(T)&&(T=0),ue(R)&&(R=0),ue(B)&&(B=0);const F=T*R,_=T*B;if(F>0&&_>0)return!1;let V=P.distanceToPoint(x.a),U=P.distanceToPoint(x.b),ne=P.distanceToPoint(x.c);ue(V)&&(V=0),ue(U)&&(U=0),ue(ne)&&(ne=0);const q=V*U,$=V*ne;if(q>0&&$>0)return!1;o.copy(P.normal),r.copy(E.normal);const G=o.cross(r);let X=0,se=Math.abs(G.x);const ce=Math.abs(G.y);ce>se&&(se=ce,X=1),Math.abs(G.z)>se&&(X=2);const oe=rr[X],ye=this.a[oe],zt=this.b[oe],ve=this.c[oe],kt=x.a[oe],rt=x.b[oe],st=x.c[oe];if(p(this,ye,zt,ve,F,_,T,R,B,f,a))return l(this,x,b,A);if(p(x,kt,rt,st,q,$,V,U,ne,d,c))return l(this,x,b,A);if(f.y<f.x){const Le=f.y;f.y=f.x,f.x=Le,u.copy(a.start),a.start.copy(a.end),a.end.copy(u)}if(d.y<d.x){const Le=d.y;d.y=d.x,d.x=Le,u.copy(c.start),c.start.copy(c.end),c.end.copy(u)}return f.y<d.x||d.y<f.x?!1:(b&&(d.x>f.x?b.start.copy(c.start):b.start.copy(a.start),d.y<f.y?b.end.copy(c.end):b.end.copy(a.end)),!0)}}();he.prototype.distanceToPoint=function(){const n=new C.Vector3;return function(e){return this.closestPointToPoint(e,n),e.distanceTo(n)}}();he.prototype.distanceToTriangle=function(){const n=new C.Vector3,t=new C.Vector3,e=["a","b","c"],i=new C.Line3,o=new C.Line3;return function(s,a=null,c=null){const u=a||c?i:null;if(this.intersectsTriangle(s,u,!0))return(a||c)&&(a&&u.getCenter(a),c&&u.getCenter(c)),0;let f=1/0;for(let d=0;d<3;d++){let l;const m=e[d],p=s[m];this.closestPointToPoint(p,n),l=p.distanceToSquared(n),l<f&&(f=l,a&&a.copy(n),c&&c.copy(p));const w=this[m];s.closestPointToPoint(w,n),l=w.distanceToSquared(n),l<f&&(f=l,a&&a.copy(w),c&&c.copy(n))}for(let d=0;d<3;d++){const l=e[d],m=e[(d+1)%3];i.set(this[l],this[m]);for(let p=0;p<3;p++){const w=e[p],y=e[(p+1)%3];o.set(s[w],s[y]),An(i,o,n,t);const M=n.distanceToSquared(t);M<f&&(f=M,a&&a.copy(n),c&&c.copy(t))}}return Math.sqrt(f)}}();class ae{constructor(t,e,i){this.isOrientedBox=!0,this.min=new C.Vector3,this.max=new C.Vector3,this.matrix=new C.Matrix4,this.invMatrix=new C.Matrix4,this.points=new Array(8).fill().map(()=>new C.Vector3),this.satAxes=new Array(3).fill().map(()=>new C.Vector3),this.satBounds=new Array(3).fill().map(()=>new Te),this.alignedSatBounds=new Array(3).fill().map(()=>new Te),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}ae.prototype.update=function(){return function(){const t=this.matrix,e=this.min,i=this.max,o=this.points;for(let u=0;u<=1;u++)for(let f=0;f<=1;f++)for(let d=0;d<=1;d++){const l=1*u|2*f|4*d,m=o[l];m.x=u?i.x:e.x,m.y=f?i.y:e.y,m.z=d?i.z:e.z,m.applyMatrix4(t)}const r=this.satBounds,s=this.satAxes,a=o[0];for(let u=0;u<3;u++){const f=s[u],d=r[u],l=1<<u,m=o[l];f.subVectors(a,m),d.setFromPoints(f,o)}const c=this.alignedSatBounds;c[0].setFromPointsField(o,"x"),c[1].setFromPointsField(o,"y"),c[2].setFromPointsField(o,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}();ae.prototype.intersectsBox=function(){const n=new Te;return function(e){this.needsUpdate&&this.update();const i=e.min,o=e.max,r=this.satBounds,s=this.satAxes,a=this.alignedSatBounds;if(n.min=i.x,n.max=o.x,a[0].isSeparated(n)||(n.min=i.y,n.max=o.y,a[1].isSeparated(n))||(n.min=i.z,n.max=o.z,a[2].isSeparated(n)))return!1;for(let c=0;c<3;c++){const u=s[c],f=r[c];if(n.setFromBox(u,e),f.isSeparated(n))return!1}return!0}}();ae.prototype.intersectsTriangle=function(){const n=new he,t=new Array(3),e=new Te,i=new Te,o=new C.Vector3;return function(s){this.needsUpdate&&this.update(),s.isExtendedTriangle?s.needsUpdate&&s.update():(n.copy(s),n.update(),s=n);const a=this.satBounds,c=this.satAxes;t[0]=s.a,t[1]=s.b,t[2]=s.c;for(let l=0;l<3;l++){const m=a[l],p=c[l];if(e.setFromPoints(p,t),m.isSeparated(e))return!1}const u=s.satBounds,f=s.satAxes,d=this.points;for(let l=0;l<3;l++){const m=u[l],p=f[l];if(e.setFromPoints(p,d),m.isSeparated(e))return!1}for(let l=0;l<3;l++){const m=c[l];for(let p=0;p<4;p++){const w=f[p];if(o.crossVectors(m,w),e.setFromPoints(o,t),i.setFromPoints(o,d),e.isSeparated(i))return!1}}return!0}}();ae.prototype.closestPointToPoint=function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}}();ae.prototype.distanceToPoint=function(){const n=new C.Vector3;return function(e){return this.closestPointToPoint(e,n),e.distanceTo(n)}}();ae.prototype.distanceToBox=function(){const n=["x","y","z"],t=new Array(12).fill().map(()=>new C.Line3),e=new Array(12).fill().map(()=>new C.Line3),i=new C.Vector3,o=new C.Vector3;return function(s,a=0,c=null,u=null){if(this.needsUpdate&&this.update(),this.intersectsBox(s))return(c||u)&&(s.getCenter(o),this.closestPointToPoint(o,i),s.closestPointToPoint(i,o),c&&c.copy(i),u&&u.copy(o)),0;const f=a*a,d=s.min,l=s.max,m=this.points;let p=1/0;for(let y=0;y<8;y++){const M=m[y];o.copy(M).clamp(d,l);const h=M.distanceToSquared(o);if(h<p&&(p=h,c&&c.copy(M),u&&u.copy(o),h<f))return Math.sqrt(h)}let w=0;for(let y=0;y<3;y++)for(let M=0;M<=1;M++)for(let h=0;h<=1;h++){const g=(y+1)%3,x=(y+2)%3,b=M<<g|h<<x,A=1<<y|M<<g|h<<x,S=m[b],P=m[A];t[w].set(S,P);const T=n[y],R=n[g],B=n[x],F=e[w],_=F.start,V=F.end;_[T]=d[T],_[R]=M?d[R]:l[R],_[B]=h?d[B]:l[R],V[T]=l[T],V[R]=M?d[R]:l[R],V[B]=h?d[B]:l[R],w++}for(let y=0;y<=1;y++)for(let M=0;M<=1;M++)for(let h=0;h<=1;h++){o.x=y?l.x:d.x,o.y=M?l.y:d.y,o.z=h?l.z:d.z,this.closestPointToPoint(o,i);const g=o.distanceToSquared(i);if(g<p&&(p=g,c&&c.copy(i),u&&u.copy(o),g<f))return Math.sqrt(g)}for(let y=0;y<12;y++){const M=t[y];for(let h=0;h<12;h++){const g=e[h];An(M,g,i,o);const x=i.distanceToSquared(o);if(x<p&&(p=x,c&&c.copy(i),u&&u.copy(o),x<f))return Math.sqrt(x)}}return Math.sqrt(p)}}();class sr extends Mn{constructor(){super(()=>new he)}}const fe=new sr,Ke=new C.Vector3,Jt=new C.Vector3;function ar(n,t,e={},i=0,o=1/0){const r=i*i,s=o*o;let a=1/0,c=null;if(n.shapecast({boundsTraverseOrder:f=>(Ke.copy(t).clamp(f.min,f.max),Ke.distanceToSquared(t)),intersectsBounds:(f,d,l)=>l<a&&l<s,intersectsTriangle:(f,d)=>{f.closestPointToPoint(t,Ke);const l=t.distanceToSquared(Ke);return l<a&&(Jt.copy(Ke),a=l,c=d),l<r}}),a===1/0)return null;const u=Math.sqrt(a);return e.point?e.point.copy(Jt):e.point=Jt.clone(),e.distance=u,e.faceIndex=c,e}const mt=parseInt(C.REVISION)>=169,cr=parseInt(C.REVISION)<=161,_e=new C.Vector3,De=new C.Vector3,Ne=new C.Vector3,pt=new C.Vector2,ht=new C.Vector2,yt=new C.Vector2,Xn=new C.Vector3,jn=new C.Vector3,Kn=new C.Vector3,Je=new C.Vector3;function lr(n,t,e,i,o,r,s,a){let c;if(r===C.BackSide?c=n.intersectTriangle(i,e,t,!0,o):c=n.intersectTriangle(t,e,i,r!==C.DoubleSide,o),c===null)return null;const u=n.origin.distanceTo(o);return u<s||u>a?null:{distance:u,point:o.clone()}}function Jn(n,t,e,i,o,r,s,a,c,u,f){_e.fromBufferAttribute(t,r),De.fromBufferAttribute(t,s),Ne.fromBufferAttribute(t,a);const d=lr(n,_e,De,Ne,Je,c,u,f);if(d){if(i){pt.fromBufferAttribute(i,r),ht.fromBufferAttribute(i,s),yt.fromBufferAttribute(i,a),d.uv=new C.Vector2;const m=C.Triangle.getInterpolation(Je,_e,De,Ne,pt,ht,yt,d.uv);mt||(d.uv=m)}if(o){pt.fromBufferAttribute(o,r),ht.fromBufferAttribute(o,s),yt.fromBufferAttribute(o,a),d.uv1=new C.Vector2;const m=C.Triangle.getInterpolation(Je,_e,De,Ne,pt,ht,yt,d.uv1);mt||(d.uv1=m),cr&&(d.uv2=d.uv1)}if(e){Xn.fromBufferAttribute(e,r),jn.fromBufferAttribute(e,s),Kn.fromBufferAttribute(e,a),d.normal=new C.Vector3;const m=C.Triangle.getInterpolation(Je,_e,De,Ne,Xn,jn,Kn,d.normal);d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1),mt||(d.normal=m)}const l={a:r,b:s,c:a,normal:new C.Vector3,materialIndex:0};if(C.Triangle.getNormal(_e,De,Ne,l.normal),d.face=l,d.faceIndex=r,mt){const m=new C.Vector3;C.Triangle.getBarycoord(Je,_e,De,Ne,m),d.barycoord=m}}return d}function Zn(n){return n&&n.isMaterial?n.side:n}function Vt(n,t,e,i,o,r,s){const a=i*3;let c=a+0,u=a+1,f=a+2;const{index:d,groups:l}=n;n.index&&(c=d.getX(c),u=d.getX(u),f=d.getX(f));const{position:m,normal:p,uv:w,uv1:y}=n.attributes;if(Array.isArray(t)){const M=i*3;for(let h=0,g=l.length;h<g;h++){const{start:x,count:b,materialIndex:A}=l[h];if(M>=x&&M<x+b){const S=Zn(t[A]),P=Jn(e,m,p,w,y,c,u,f,S,r,s);if(P)if(P.faceIndex=i,P.face.materialIndex=A,o)o.push(P);else return P}}}else{const M=Zn(t),h=Jn(e,m,p,w,y,c,u,f,M,r,s);if(h)if(h.faceIndex=i,h.face.materialIndex=0,o)o.push(h);else return h}return null}function K(n,t,e,i){const o=n.a,r=n.b,s=n.c;let a=t,c=t+1,u=t+2;e&&(a=e.getX(a),c=e.getX(c),u=e.getX(u)),o.x=i.getX(a),o.y=i.getY(a),o.z=i.getZ(a),r.x=i.getX(c),r.y=i.getY(c),r.z=i.getZ(c),s.x=i.getX(u),s.y=i.getY(u),s.z=i.getZ(u)}function ur(n,t,e,i,o,r,s,a){const{geometry:c,_indirectBuffer:u}=n;for(let f=i,d=i+o;f<d;f++)Vt(c,t,e,f,r,s,a)}function fr(n,t,e,i,o,r,s){const{geometry:a,_indirectBuffer:c}=n;let u=1/0,f=null;for(let d=i,l=i+o;d<l;d++){let m;m=Vt(a,t,e,d,null,r,s),m&&m.distance<u&&(f=m,u=m.distance)}return f}function dr(n,t,e,i,o,r,s){const{geometry:a}=e,{index:c}=a,u=a.attributes.position;for(let f=n,d=t+n;f<d;f++){let l;if(l=f,K(s,l*3,c,u),s.needsUpdate=!0,i(s,l,o,r))return!0}return!1}function mr(n,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=n.geometry,i=e.index?e.index.array:null,o=e.attributes.position;let r,s,a,c,u=0;const f=n._roots;for(let l=0,m=f.length;l<m;l++)r=f[l],s=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),d(0,u),u+=r.byteLength;function d(l,m,p=!1){const w=l*2;if(Y(w,a)){const y=Z(l,s),M=ie(w,a);let h=1/0,g=1/0,x=1/0,b=-1/0,A=-1/0,S=-1/0;for(let P=3*y,E=3*(y+M);P<E;P++){let T=i[P];const R=o.getX(T),B=o.getY(T),F=o.getZ(T);R<h&&(h=R),R>b&&(b=R),B<g&&(g=B),B>A&&(A=B),F<x&&(x=F),F>S&&(S=F)}return c[l+0]!==h||c[l+1]!==g||c[l+2]!==x||c[l+3]!==b||c[l+4]!==A||c[l+5]!==S?(c[l+0]=h,c[l+1]=g,c[l+2]=x,c[l+3]=b,c[l+4]=A,c[l+5]=S,!0):!1}else{const y=Q(l),M=ee(l,s);let h=p,g=!1,x=!1;if(t){if(!h){const T=y/J+m/te,R=M/J+m/te;g=t.has(T),x=t.has(R),h=!g&&!x}}else g=!0,x=!0;const b=h||g,A=h||x;let S=!1;b&&(S=d(y,m,h));let P=!1;A&&(P=d(M,m,h));const E=S||P;if(E)for(let T=0;T<3;T++){const R=y+T,B=M+T,F=c[R],_=c[R+3],V=c[B],U=c[B+3];c[l+T]=F<V?F:V,c[l+T+3]=_>U?_:U}return E}}}function Re(n,t,e,i,o){let r,s,a,c,u,f;const d=1/e.direction.x,l=1/e.direction.y,m=1/e.direction.z,p=e.origin.x,w=e.origin.y,y=e.origin.z;let M=t[n],h=t[n+3],g=t[n+1],x=t[n+3+1],b=t[n+2],A=t[n+3+2];return d>=0?(r=(M-p)*d,s=(h-p)*d):(r=(h-p)*d,s=(M-p)*d),l>=0?(a=(g-w)*l,c=(x-w)*l):(a=(x-w)*l,c=(g-w)*l),r>c||a>s||((a>r||isNaN(r))&&(r=a),(c<s||isNaN(s))&&(s=c),m>=0?(u=(b-y)*m,f=(A-y)*m):(u=(A-y)*m,f=(b-y)*m),r>f||u>s)?!1:((u>r||r!==r)&&(r=u),(f<s||s!==s)&&(s=f),r<=o&&s>=i)}function pr(n,t,e,i,o,r,s,a){const{geometry:c,_indirectBuffer:u}=n;for(let f=i,d=i+o;f<d;f++){let l=u?u[f]:f;Vt(c,t,e,l,r,s,a)}}function hr(n,t,e,i,o,r,s){const{geometry:a,_indirectBuffer:c}=n;let u=1/0,f=null;for(let d=i,l=i+o;d<l;d++){let m;m=Vt(a,t,e,c?c[d]:d,null,r,s),m&&m.distance<u&&(f=m,u=m.distance)}return f}function yr(n,t,e,i,o,r,s){const{geometry:a}=e,{index:c}=a,u=a.attributes.position;for(let f=n,d=t+n;f<d;f++){let l;if(l=e.resolveTriangleIndex(f),K(s,l*3,c,u),s.needsUpdate=!0,i(s,l,o,r))return!0}return!1}function gr(n,t,e,i,o,r,s){H.setBuffer(n._roots[t]),cn(0,n,e,i,o,r,s),H.clearBuffer()}function cn(n,t,e,i,o,r,s){const{float32Array:a,uint16Array:c,uint32Array:u}=H,f=n*2;if(Y(f,c)){const l=Z(n,u),m=ie(f,c);ur(t,e,i,l,m,o,r,s)}else{const l=Q(n);Re(l,a,i,r,s)&&cn(l,t,e,i,o,r,s);const m=ee(n,u);Re(m,a,i,r,s)&&cn(m,t,e,i,o,r,s)}}const vr=["x","y","z"];function br(n,t,e,i,o,r){H.setBuffer(n._roots[t]);const s=ln(0,n,e,i,o,r);return H.clearBuffer(),s}function ln(n,t,e,i,o,r){const{float32Array:s,uint16Array:a,uint32Array:c}=H;let u=n*2;if(Y(u,a)){const d=Z(n,c),l=ie(u,a);return fr(t,e,i,d,l,o,r)}else{const d=Dt(n,c),l=vr[d],p=i.direction[l]>=0;let w,y;p?(w=Q(n),y=ee(n,c)):(w=ee(n,c),y=Q(n));const h=Re(w,s,i,o,r)?ln(w,t,e,i,o,r):null;if(h){const b=h.point[l];if(p?b<=s[y+d]:b>=s[y+d+3])return h}const x=Re(y,s,i,o,r)?ln(y,t,e,i,o,r):null;return h&&x?h.distance<=x.distance?h:x:h||x||null}}const gt=new C.Box3,Ge=new he,Oe=new he,Ze=new C.Matrix4,Qn=new ae,vt=new ae;function xr(n,t,e,i){H.setBuffer(n._roots[t]);const o=un(0,n,e,i);return H.clearBuffer(),o}function un(n,t,e,i,o=null){const{float32Array:r,uint16Array:s,uint32Array:a}=H;let c=n*2;if(o===null&&(e.boundingBox||e.computeBoundingBox(),Qn.set(e.boundingBox.min,e.boundingBox.max,i),o=Qn),Y(c,s)){const f=t.geometry,d=f.index,l=f.attributes.position,m=e.index,p=e.attributes.position,w=Z(n,a),y=ie(c,s);if(Ze.copy(i).invert(),e.boundsTree)return W(n,r,vt),vt.matrix.copy(Ze),vt.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:h=>vt.intersectsBox(h),intersectsTriangle:h=>{h.a.applyMatrix4(i),h.b.applyMatrix4(i),h.c.applyMatrix4(i),h.needsUpdate=!0;for(let g=w*3,x=(y+w)*3;g<x;g+=3)if(K(Oe,g,d,l),Oe.needsUpdate=!0,h.intersectsTriangle(Oe))return!0;return!1}});{const M=Lt(e);for(let h=w*3,g=(y+w)*3;h<g;h+=3){K(Ge,h,d,l),Ge.a.applyMatrix4(Ze),Ge.b.applyMatrix4(Ze),Ge.c.applyMatrix4(Ze),Ge.needsUpdate=!0;for(let x=0,b=M*3;x<b;x+=3)if(K(Oe,x,m,p),Oe.needsUpdate=!0,Ge.intersectsTriangle(Oe))return!0}}}else{const f=Q(n),d=ee(n,a);return W(f,r,gt),!!(o.intersectsBox(gt)&&un(f,t,e,i,o)||(W(d,r,gt),o.intersectsBox(gt)&&un(d,t,e,i,o)))}}const bt=new C.Matrix4,Zt=new ae,Qe=new ae,wr=new C.Vector3,Mr=new C.Vector3,Ar=new C.Vector3,Sr=new C.Vector3;function Tr(n,t,e,i={},o={},r=0,s=1/0){t.boundingBox||t.computeBoundingBox(),Zt.set(t.boundingBox.min,t.boundingBox.max,e),Zt.needsUpdate=!0;const a=n.geometry,c=a.attributes.position,u=a.index,f=t.attributes.position,d=t.index,l=fe.getPrimitive(),m=fe.getPrimitive();let p=wr,w=Mr,y=null,M=null;o&&(y=Ar,M=Sr);let h=1/0,g=null,x=null;return bt.copy(e).invert(),Qe.matrix.copy(bt),n.shapecast({boundsTraverseOrder:b=>Zt.distanceToBox(b),intersectsBounds:(b,A,S)=>S<h&&S<s?(A&&(Qe.min.copy(b.min),Qe.max.copy(b.max),Qe.needsUpdate=!0),!0):!1,intersectsRange:(b,A)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:P=>Qe.distanceToBox(P),intersectsBounds:(P,E,T)=>T<h&&T<s,intersectsRange:(P,E)=>{for(let T=P,R=P+E;T<R;T++){K(m,3*T,d,f),m.a.applyMatrix4(e),m.b.applyMatrix4(e),m.c.applyMatrix4(e),m.needsUpdate=!0;for(let B=b,F=b+A;B<F;B++){K(l,3*B,u,c),l.needsUpdate=!0;const _=l.distanceToTriangle(m,p,y);if(_<h&&(w.copy(p),M&&M.copy(y),h=_,g=B,x=T),_<r)return!0}}}});{const S=Lt(t);for(let P=0,E=S;P<E;P++){K(m,3*P,d,f),m.a.applyMatrix4(e),m.b.applyMatrix4(e),m.c.applyMatrix4(e),m.needsUpdate=!0;for(let T=b,R=b+A;T<R;T++){K(l,3*T,u,c),l.needsUpdate=!0;const B=l.distanceToTriangle(m,p,y);if(B<h&&(w.copy(p),M&&M.copy(y),h=B,g=T,x=P),B<r)return!0}}}}}),fe.releasePrimitive(l),fe.releasePrimitive(m),h===1/0?null:(i.point?i.point.copy(w):i.point=w.clone(),i.distance=h,i.faceIndex=g,o&&(o.point?o.point.copy(M):o.point=M.clone(),o.point.applyMatrix4(bt),w.applyMatrix4(bt),o.distance=w.sub(o.point).length(),o.faceIndex=x),i)}function Cr(n,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=n.geometry,i=e.index?e.index.array:null,o=e.attributes.position;let r,s,a,c,u=0;const f=n._roots;for(let l=0,m=f.length;l<m;l++)r=f[l],s=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),d(0,u),u+=r.byteLength;function d(l,m,p=!1){const w=l*2;if(Y(w,a)){const y=Z(l,s),M=ie(w,a);let h=1/0,g=1/0,x=1/0,b=-1/0,A=-1/0,S=-1/0;for(let P=y,E=y+M;P<E;P++){const T=3*n.resolveTriangleIndex(P);for(let R=0;R<3;R++){let B=T+R;B=i?i[B]:B;const F=o.getX(B),_=o.getY(B),V=o.getZ(B);F<h&&(h=F),F>b&&(b=F),_<g&&(g=_),_>A&&(A=_),V<x&&(x=V),V>S&&(S=V)}}return c[l+0]!==h||c[l+1]!==g||c[l+2]!==x||c[l+3]!==b||c[l+4]!==A||c[l+5]!==S?(c[l+0]=h,c[l+1]=g,c[l+2]=x,c[l+3]=b,c[l+4]=A,c[l+5]=S,!0):!1}else{const y=Q(l),M=ee(l,s);let h=p,g=!1,x=!1;if(t){if(!h){const T=y/J+m/te,R=M/J+m/te;g=t.has(T),x=t.has(R),h=!g&&!x}}else g=!0,x=!0;const b=h||g,A=h||x;let S=!1;b&&(S=d(y,m,h));let P=!1;A&&(P=d(M,m,h));const E=S||P;if(E)for(let T=0;T<3;T++){const R=y+T,B=M+T,F=c[R],_=c[R+3],V=c[B],U=c[B+3];c[l+T]=F<V?F:V,c[l+T+3]=_>U?_:U}return E}}}function Br(n,t,e,i,o,r,s){H.setBuffer(n._roots[t]),fn(0,n,e,i,o,r,s),H.clearBuffer()}function fn(n,t,e,i,o,r,s){const{float32Array:a,uint16Array:c,uint32Array:u}=H,f=n*2;if(Y(f,c)){const l=Z(n,u),m=ie(f,c);pr(t,e,i,l,m,o,r,s)}else{const l=Q(n);Re(l,a,i,r,s)&&fn(l,t,e,i,o,r,s);const m=ee(n,u);Re(m,a,i,r,s)&&fn(m,t,e,i,o,r,s)}}const Pr=["x","y","z"];function Ir(n,t,e,i,o,r){H.setBuffer(n._roots[t]);const s=dn(0,n,e,i,o,r);return H.clearBuffer(),s}function dn(n,t,e,i,o,r){const{float32Array:s,uint16Array:a,uint32Array:c}=H;let u=n*2;if(Y(u,a)){const d=Z(n,c),l=ie(u,a);return hr(t,e,i,d,l,o,r)}else{const d=Dt(n,c),l=Pr[d],p=i.direction[l]>=0;let w,y;p?(w=Q(n),y=ee(n,c)):(w=ee(n,c),y=Q(n));const h=Re(w,s,i,o,r)?dn(w,t,e,i,o,r):null;if(h){const b=h.point[l];if(p?b<=s[y+d]:b>=s[y+d+3])return h}const x=Re(y,s,i,o,r)?dn(y,t,e,i,o,r):null;return h&&x?h.distance<=x.distance?h:x:h||x||null}}const xt=new C.Box3,He=new he,qe=new he,et=new C.Matrix4,ei=new ae,wt=new ae;function Rr(n,t,e,i){H.setBuffer(n._roots[t]);const o=mn(0,n,e,i);return H.clearBuffer(),o}function mn(n,t,e,i,o=null){const{float32Array:r,uint16Array:s,uint32Array:a}=H;let c=n*2;if(o===null&&(e.boundingBox||e.computeBoundingBox(),ei.set(e.boundingBox.min,e.boundingBox.max,i),o=ei),Y(c,s)){const f=t.geometry,d=f.index,l=f.attributes.position,m=e.index,p=e.attributes.position,w=Z(n,a),y=ie(c,s);if(et.copy(i).invert(),e.boundsTree)return W(n,r,wt),wt.matrix.copy(et),wt.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:h=>wt.intersectsBox(h),intersectsTriangle:h=>{h.a.applyMatrix4(i),h.b.applyMatrix4(i),h.c.applyMatrix4(i),h.needsUpdate=!0;for(let g=w,x=y+w;g<x;g++)if(K(qe,3*t.resolveTriangleIndex(g),d,l),qe.needsUpdate=!0,h.intersectsTriangle(qe))return!0;return!1}});{const M=Lt(e);for(let h=w,g=y+w;h<g;h++){const x=t.resolveTriangleIndex(h);K(He,3*x,d,l),He.a.applyMatrix4(et),He.b.applyMatrix4(et),He.c.applyMatrix4(et),He.needsUpdate=!0;for(let b=0,A=M*3;b<A;b+=3)if(K(qe,b,m,p),qe.needsUpdate=!0,He.intersectsTriangle(qe))return!0}}}else{const f=Q(n),d=ee(n,a);return W(f,r,xt),!!(o.intersectsBox(xt)&&mn(f,t,e,i,o)||(W(d,r,xt),o.intersectsBox(xt)&&mn(d,t,e,i,o)))}}const Mt=new C.Matrix4,Qt=new ae,tt=new ae,Er=new C.Vector3,Fr=new C.Vector3,_r=new C.Vector3,Dr=new C.Vector3;function Nr(n,t,e,i={},o={},r=0,s=1/0){t.boundingBox||t.computeBoundingBox(),Qt.set(t.boundingBox.min,t.boundingBox.max,e),Qt.needsUpdate=!0;const a=n.geometry,c=a.attributes.position,u=a.index,f=t.attributes.position,d=t.index,l=fe.getPrimitive(),m=fe.getPrimitive();let p=Er,w=Fr,y=null,M=null;o&&(y=_r,M=Dr);let h=1/0,g=null,x=null;return Mt.copy(e).invert(),tt.matrix.copy(Mt),n.shapecast({boundsTraverseOrder:b=>Qt.distanceToBox(b),intersectsBounds:(b,A,S)=>S<h&&S<s?(A&&(tt.min.copy(b.min),tt.max.copy(b.max),tt.needsUpdate=!0),!0):!1,intersectsRange:(b,A)=>{if(t.boundsTree){const S=t.boundsTree;return S.shapecast({boundsTraverseOrder:P=>tt.distanceToBox(P),intersectsBounds:(P,E,T)=>T<h&&T<s,intersectsRange:(P,E)=>{for(let T=P,R=P+E;T<R;T++){const B=S.resolveTriangleIndex(T);K(m,3*B,d,f),m.a.applyMatrix4(e),m.b.applyMatrix4(e),m.c.applyMatrix4(e),m.needsUpdate=!0;for(let F=b,_=b+A;F<_;F++){const V=n.resolveTriangleIndex(F);K(l,3*V,u,c),l.needsUpdate=!0;const U=l.distanceToTriangle(m,p,y);if(U<h&&(w.copy(p),M&&M.copy(y),h=U,g=F,x=T),U<r)return!0}}}})}else{const S=Lt(t);for(let P=0,E=S;P<E;P++){K(m,3*P,d,f),m.a.applyMatrix4(e),m.b.applyMatrix4(e),m.c.applyMatrix4(e),m.needsUpdate=!0;for(let T=b,R=b+A;T<R;T++){const B=n.resolveTriangleIndex(T);K(l,3*B,u,c),l.needsUpdate=!0;const F=l.distanceToTriangle(m,p,y);if(F<h&&(w.copy(p),M&&M.copy(y),h=F,g=T,x=P),F<r)return!0}}}}}),fe.releasePrimitive(l),fe.releasePrimitive(m),h===1/0?null:(i.point?i.point.copy(w):i.point=w.clone(),i.distance=h,i.faceIndex=g,o&&(o.point?o.point.copy(M):o.point=M.clone(),o.point.applyMatrix4(Mt),w.applyMatrix4(Mt),o.distance=w.sub(o.point).length(),o.faceIndex=x),i)}function ti(n,t,e){return n===null?null:(n.point.applyMatrix4(t.matrixWorld),n.distance=n.point.distanceTo(e.ray.origin),n.object=t,n)}const At=new ae,St=new C.Ray,ni=new C.Vector3,ii=new C.Matrix4,oi=new C.Vector3,en=["getX","getY","getZ"];class It extends nr{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,o=t._roots,r=t._indirectBuffer,s=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(a.roots=o.map(c=>c.slice()),a.index=s?s.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=o,a.index=s?s.array:null,a.indirectBuffer=r),a}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:o,roots:r,indirectBuffer:s}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),c(r));const a=new It(e,{...i,[wn]:!0});if(a._roots=r,a._indirectBuffer=s||null,i.setIndex){const u=e.getIndex();if(u===null){const f=new C.BufferAttribute(t.index,1,!1);e.setIndex(f)}else u.array!==o&&(u.array.set(o),u.needsUpdate=!0)}return a;function c(u){for(let f=0;f<u.length;f++){const d=u[f],l=new Uint32Array(d),m=new Uint16Array(d);for(let p=0,w=d.byteLength/te;p<w;p++){const y=J*p,M=2*y;Y(M,m)||(l[y+6]=l[y+6]/J-p)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const o=this.geometry,r=this._indirectBuffer,s=o.attributes.position,a=o.index?o.index.array:null,u=(r?r[t]:t)*3;let f=u+0,d=u+1,l=u+2;a&&(f=a[f],d=a[d],l=a[l]);for(let m=0;m<3;m++){const p=s[en[m]](f),w=s[en[m]](d),y=s[en[m]](l);let M=p;w<M&&(M=w),y<M&&(M=y);let h=p;w>h&&(h=w),y>h&&(h=y),e[i+m]=M,e[i+m+3]=h}return e}computePrimitiveBounds(t,e,i){const o=this.geometry,r=this._indirectBuffer,s=o.attributes.position,a=o.index?o.index.array:null,c=s.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const u=s.array,f=s.offset||0;let d=3;s.isInterleavedBufferAttribute&&(d=s.data.stride);const l=["getX","getY","getZ"],m=i.offset;for(let p=t,w=t+e;p<w;p++){const M=(r?r[p]:p)*3,h=(p-m)*6;let g=M+0,x=M+1,b=M+2;a&&(g=a[g],x=a[x],b=a[b]),c||(g=g*d+f,x=x*d+f,b=b*d+f);for(let A=0;A<3;A++){let S,P,E;c?(S=s[l[A]](g),P=s[l[A]](x),E=s[l[A]](b)):(S=u[g+A],P=u[x+A],E=u[b+A]);let T=S;P<T&&(T=P),E<T&&(T=E);let R=S;P>R&&(R=P),E>R&&(R=E);const B=(R-T)/2,F=A*2;i[h+F+0]=T+B,i[h+F+1]=B+(Math.abs(T)+B)*Ct}}return i}raycastObject3D(t,e,i=[]){const{material:o}=t;if(o===void 0)return;ii.copy(t.matrixWorld).invert(),St.copy(e.ray).applyMatrix4(ii),oi.setFromMatrixScale(t.matrixWorld),ni.copy(St.direction).multiply(oi);const r=ni.length(),s=e.near/r,a=e.far/r;if(e.firstHitOnly===!0){let c=this.raycastFirst(St,o,s,a);c=ti(c,t,e),c&&i.push(c)}else{const c=this.raycast(St,o,s,a);for(let u=0,f=c.length;u<f;u++){const d=ti(c[u],t,e);d&&i.push(d)}}return i}refit(t=null){return(this.indirect?Cr:mr)(this,t)}raycast(t,e=C.FrontSide,i=0,o=1/0){const r=this._roots,s=[],a=this.indirect?Br:gr;for(let c=0,u=r.length;c<u;c++)a(this,c,e,t,s,i,o);return s}raycastFirst(t,e=C.FrontSide,i=0,o=1/0){const r=this._roots;let s=null;const a=this.indirect?Ir:br;for(let c=0,u=r.length;c<u;c++){const f=a(this,c,e,t,i,o);f!=null&&(s==null||f.distance<s.distance)&&(s=f)}return s}intersectsGeometry(t,e){let i=!1;const o=this._roots,r=this.indirect?Rr:xr;for(let s=0,a=o.length;s<a&&(i=r(this,s,t,e),!i);s++);return i}shapecast(t){const e=fe.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?yr:dr});return fe.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:o,intersectsTriangles:r}=i;const s=fe.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,u=this.indirect?p=>{const w=this.resolveTriangleIndex(p);K(s,w*3,a,c)}:p=>{K(s,p*3,a,c)},f=fe.getPrimitive(),d=t.geometry.index,l=t.geometry.attributes.position,m=t.indirect?p=>{const w=t.resolveTriangleIndex(p);K(f,w*3,d,l)}:p=>{K(f,p*3,d,l)};if(r){if(!(t instanceof It))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(w,y,M,h,g,x,b,A)=>{for(let S=M,P=M+h;S<P;S++){m(S),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let E=w,T=w+y;E<T;E++)if(u(E),s.needsUpdate=!0,r(s,f,E,S,g,x,b,A))return!0}return!1};if(o){const w=o;o=function(y,M,h,g,x,b,A,S){return w(y,M,h,g,x,b,A,S)?!0:p(y,M,h,g,x,b,A,S)}}else o=p}return super.bvhcast(t,e,{intersectsRanges:o})}intersectsBox(t,e){return At.set(t.min,t.max,e),At.needsUpdate=!0,this.shapecast({intersectsBounds:i=>At.intersectsBox(i),intersectsTriangle:i=>At.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},o={},r=0,s=1/0){return(this.indirect?Nr:Tr)(this,t,e,i,o,r,s)}closestPointToPoint(t,e={},i=0,o=1/0){return ar(this,t,e,i,o)}}function Lr(n){switch(n){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function Vr(n){switch(n){case 1:return C.RedFormat;case 2:return C.RGFormat;case 3:return C.RGBAFormat;case 4:return C.RGBAFormat}}function ri(n){switch(n){case 1:return C.RedIntegerFormat;case 2:return C.RGIntegerFormat;case 3:return C.RGBAIntegerFormat;case 4:return C.RGBAIntegerFormat}}class wi extends C.DataTexture{constructor(){super(),this.minFilter=C.NearestFilter,this.magFilter=C.NearestFilter,this.generateMipmaps=!1,this.overrideItemSize=null,this._forcedType=null}updateFrom(t){const e=this.overrideItemSize,i=t.itemSize,o=t.count;if(e!==null){if(i*o%e!==0)throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length.");t.itemSize=e,t.count=o*i/e}const r=t.itemSize,s=t.count,a=t.normalized,c=t.array.constructor,u=c.BYTES_PER_ELEMENT;let f=this._forcedType,d=r;if(f===null)switch(c){case Float32Array:f=C.FloatType;break;case Uint8Array:case Uint16Array:case Uint32Array:f=C.UnsignedIntType;break;case Int8Array:case Int16Array:case Int32Array:f=C.IntType;break}let l,m,p,w,y=Lr(r);switch(f){case C.FloatType:p=1,m=Vr(r),a&&u===1?(w=c,y+="8",c===Uint8Array?l=C.UnsignedByteType:(l=C.ByteType,y+="_SNORM")):(w=Float32Array,y+="32F",l=C.FloatType);break;case C.IntType:y+=u*8+"I",p=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,m=ri(r),u===1?(w=Int8Array,l=C.ByteType):u===2?(w=Int16Array,l=C.ShortType):(w=Int32Array,l=C.IntType);break;case C.UnsignedIntType:y+=u*8+"UI",p=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,m=ri(r),u===1?(w=Uint8Array,l=C.UnsignedByteType):u===2?(w=Uint16Array,l=C.UnsignedShortType):(w=Uint32Array,l=C.UnsignedIntType);break}d===3&&(m===C.RGBAFormat||m===C.RGBAIntegerFormat)&&(d=4);const M=Math.ceil(Math.sqrt(s))||1,h=d*M*M,g=new w(h),x=t.normalized;t.normalized=!1;for(let b=0;b<s;b++){const A=d*b;g[A]=t.getX(b)/p,r>=2&&(g[A+1]=t.getY(b)/p),r>=3&&(g[A+2]=t.getZ(b)/p,d===4&&(g[A+3]=1)),r>=4&&(g[A+3]=t.getW(b)/p)}t.normalized=x,this.internalFormat=y,this.format=m,this.type=l,this.image.width=M,this.image.height=M,this.image.data=g,this.needsUpdate=!0,this.dispose(),t.itemSize=i,t.count=o}}class zr extends wi{constructor(){super(),this._forcedType=C.UnsignedIntType}}class kr extends wi{constructor(){super(),this._forcedType=C.FloatType}}class Mi{constructor(){this.index=new zr,this.position=new kr,this.bvhBounds=new C.DataTexture,this.bvhContents=new C.DataTexture,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(t){const{geometry:e}=t;if(Gr(t,this.bvhBounds,this.bvhContents),this.position.updateFrom(e.attributes.position),t.indirect){const i=t._indirectBuffer;if(this._cachedIndexAttr===null||this._cachedIndexAttr.count!==i.length)if(e.index)this._cachedIndexAttr=e.index.clone();else{const o=xi(Nt(e));this._cachedIndexAttr=new C.BufferAttribute(o,1,!1)}Ur(e,i,this._cachedIndexAttr),this.index.updateFrom(this._cachedIndexAttr)}else this.index.updateFrom(e.index)}dispose(){const{index:t,position:e,bvhBounds:i,bvhContents:o}=this;t&&t.dispose(),e&&e.dispose(),i&&i.dispose(),o&&o.dispose()}}function Ur(n,t,e){const i=e.array,o=n.index?n.index.array:null;for(let r=0,s=t.length;r<s;r++){const a=3*r,c=3*t[r];for(let u=0;u<3;u++)i[a+u]=o?o[c+u]:c+u}}function Gr(n,t,e){const i=n._roots;if(i.length!==1)throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported.");const o=i[0],r=new Uint16Array(o),s=new Uint32Array(o),a=new Float32Array(o),c=o.byteLength/te,u=2*Math.ceil(Math.sqrt(c/2)),f=new Float32Array(4*u*u),d=Math.ceil(Math.sqrt(c)),l=new Uint32Array(2*d*d);for(let m=0;m<c;m++){const p=m*te/4,w=p*2,y=p;for(let M=0;M<3;M++)f[8*m+0+M]=a[y+0+M],f[8*m+4+M]=a[y+3+M];if(Y(w,r)){const M=ie(w,r),h=Z(p,s),g=zo|M;l[m*2+0]=g,l[m*2+1]=h}else{const M=s[p+6],h=Dt(p,s);l[m*2+0]=h,l[m*2+1]=M}}t.image.data=f,t.image.width=u,t.image.height=u,t.format=C.RGBAFormat,t.type=C.FloatType,t.internalFormat="RGBA32F",t.minFilter=C.NearestFilter,t.magFilter=C.NearestFilter,t.generateMipmaps=!1,t.needsUpdate=!0,t.dispose(),e.image.data=l,e.image.width=d,e.image.height=d,e.format=C.RGIntegerFormat,e.type=C.UnsignedIntType,e.internalFormat="RG32UI",e.minFilter=C.NearestFilter,e.magFilter=C.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e.dispose()}const Or=`
2
2
 
3
3
  // A stack of uint32 indices can can store the indices for
4
4
  // a perfectly balanced tree with a depth up to 31. Lower stack
@@ -80,7 +80,7 @@ void ndcToCameraRay(
80
80
  rayDirection = direction.xyz;
81
81
 
82
82
  }
83
- `,Er=`
83
+ `,Hr=`
84
84
 
85
85
  #ifndef TRI_INTERSECT_EPSILON
86
86
  #define TRI_INTERSECT_EPSILON 1e-5
@@ -284,7 +284,7 @@ bool _bvhIntersectFirstHit(
284
284
  return found;
285
285
 
286
286
  }
287
- `,Rr=`
287
+ `,qr=`
288
288
  struct BVH {
289
289
 
290
290
  usampler2D index;
@@ -294,10 +294,10 @@ struct BVH {
294
294
  usampler2D bvhContents;
295
295
 
296
296
  };
297
- `,Fr=Rr,_r=`
298
- ${Pr}
299
- ${Er}
300
- `,Dr=`
297
+ `,$r=qr,Wr=`
298
+ ${Or}
299
+ ${Hr}
300
+ `,Yr=`
301
301
  uniform vec3 uCentroid;
302
302
  uniform float uRadius;
303
303
  attribute vec4 aFacet;
@@ -307,13 +307,13 @@ void main() {
307
307
  vFacet = aFacet;
308
308
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
309
309
  }
310
- `,Nr=`
310
+ `,Xr=`
311
311
  varying vec4 vFacet;
312
312
 
313
313
  void main() {
314
314
  gl_FragColor = vFacet;
315
315
  }
316
- `,Lr=`
316
+ `,jr=`
317
317
  varying vec3 vWorldPos;
318
318
  varying vec3 vLocalPos;
319
319
  varying vec3 vLocalNormal;
@@ -335,7 +335,7 @@ void main() {
335
335
  vLocalCameraPos = (inverse(modelMatrix) * vec4(cameraPos, 1.0)).xyz;
336
336
  gl_Position = projectionMatrix * viewMatrix * worldPosition;
337
337
  }
338
- `,Vr=`
338
+ `,Kr=`
339
339
  precision highp float;
340
340
  precision highp int;
341
341
  precision highp usampler2D;
@@ -365,8 +365,8 @@ uniform float facetSharpness;
365
365
  uniform int rayBounces;
366
366
  uniform float uRadius;
367
367
 
368
- ${Fr}
369
- ${_r}
368
+ ${$r}
369
+ ${Wr}
370
370
  uniform BVH bvh;
371
371
 
372
372
  varying vec3 vWorldPos;
@@ -583,7 +583,7 @@ void main() {
583
583
 
584
584
  pc_fragColor = vec4(aces(hdrColor), 1.0);
585
585
  }
586
- `;class zr{constructor(){ee(this,"cache",new Map)}get cacheSize(){return this.cache.size}getEntry(t){return this.cache.get(t)}acquire(t,e,i){const r=wo(t);if(!r.isBakeable)return null;const o=(i==null?void 0:i.resolution)??256,s=`${Ao(t,r)}_${o}`,a=this.cache.get(s);return a?(a.disposalTimer!==null&&(clearTimeout(a.disposalTimer),a.disposalTimer=null),a.refCount++,a.handle):this.bake(t,r,s,e,o)}bake(t,e,i,r,o){var u;const s=!((u=r.capabilities)!=null&&u.isWebGL2),a=new v.WebGLCubeRenderTarget(o,{type:s?v.UnsignedByteType:v.HalfFloatType,format:v.RGBAFormat,depthBuffer:!0,generateMipmaps:!1,minFilter:v.NearestFilter,magFilter:v.NearestFilter});this.renderToTarget(t,e,r,a,s);const c={key:i,texture:a.texture,centroid:e.centroid.clone(),radius:e.radius,encoding:s?"unorm":"signed"};return this.cache.set(i,{handle:c,renderTarget:a,refCount:1,disposalTimer:null,geometryRef:new WeakRef(t),resolution:o,analysis:e}),c}renderToTarget(t,e,i,r,o){var x,g,A;const s=Mo(t,e),a=t.getIndex()?t.toNonIndexed():t.clone();a.setAttribute("aFacet",new v.BufferAttribute(s,4)),console.log("[DiamondBaker] renderToTarget called",{isUnorm:o,triangleCount:e.triangleCount,centroid:e.centroid.toArray(),radius:e.radius,facetDataLength:s.length,facetSample:Array.from(s.slice(0,8)),bakeGeoVertexCount:a.getAttribute("position").count,rendererCapabilities:(x=i.capabilities)==null?void 0:x.isWebGL2});const c=new v.ShaderMaterial({vertexShader:Dr,fragmentShader:Nr,side:v.DoubleSide,blending:v.NoBlending,transparent:!1,depthTest:!0,depthWrite:!0,toneMapped:!1,defines:o?{GEM_NORMALS_UNORM:1}:{},uniforms:{uCentroid:{value:e.centroid},uRadius:{value:e.radius}}}),u=new v.Scene,m=new v.Mesh(a,c);u.add(m);const f=Math.max(.001,e.radius*.001),l=Math.max(2.5,e.radius*3),d=new v.CubeCamera(f,l,r);d.position.copy(e.centroid);const y=((g=i.getRenderTarget)==null?void 0:g.call(i))??null,w=i.autoClear,b=i.toneMapping,M=new v.Color;i.getClearColor&&i.getClearColor(M);const h=i.getClearAlpha?i.getClearAlpha():1;i.toneMapping=v.NoToneMapping,i.autoClear=!0,i.setClearColor&&i.setClearColor(0,0);const p=(A=i.getContext)==null?void 0:A.call(i);if(p){const T=p.getError();T!==0&&console.warn("[DiamondBaker] GL error BEFORE camera.update:",T)}if(d.update(i,u),p){const T=p.getError();T!==0&&console.error("[DiamondBaker] GL error AFTER camera.update:",T,"— bake likely failed!")}i.setRenderTarget&&i.setRenderTarget(y),i.autoClear=w,i.toneMapping=b,i.setClearColor&&i.setClearColor(M,h),a.dispose(),c.dispose()}release(t){const e=this.cache.get(t.key);e&&(e.refCount--,e.refCount<=0&&(e.refCount=0,e.disposalTimer!==null&&clearTimeout(e.disposalTimer),e.disposalTimer=setTimeout(()=>{e.renderTarget.dispose(),this.cache.delete(t.key)},1e3)))}clearCache(){for(const t of this.cache.values())t.disposalTimer!==null&&(clearTimeout(t.disposalTimer),t.disposalTimer=null),t.renderTarget.dispose();this.cache.clear()}onContextRestored(t){var e;for(const[i,r]of this.cache.entries()){const o=r.geometryRef.deref();if(!o){r.disposalTimer!==null&&(clearTimeout(r.disposalTimer),r.disposalTimer=null),r.renderTarget.dispose(),this.cache.delete(i);continue}const s=!((e=t.capabilities)!=null&&e.isWebGL2);r.renderTarget.dispose();const a=new v.WebGLCubeRenderTarget(r.resolution,{type:s?v.UnsignedByteType:v.HalfFloatType,format:v.RGBAFormat,depthBuffer:!0,generateMipmaps:!1,minFilter:v.NearestFilter,magFilter:v.NearestFilter});r.renderTarget=a,r.handle.texture=a.texture,r.handle.encoding=s?"unorm":"signed",this.renderToTarget(o,r.analysis,t,a,s)}}}const Qe=new zr,Zn=new v.Matrix4;class Oe extends v.ShaderMaterial{constructor(e,i,r,o={}){const s=e.bvh??new yi;super({vertexShader:Lr,fragmentShader:Vr,glslVersion:v.GLSL3,defines:{USE_CUBE_ENV:1,MAX_BOUNCES:5,...e.encoding==="unorm"?{GEM_NORMALS_UNORM:1}:{},...o.useCorrectFresnel?{USE_CORRECT_FRESNEL:1}:{},...o.correctDispersionSign?{CORRECT_DISPERSION_SIGN:1}:{},...o.accumulateTIR?{ACCUMULATE_TIR:1}:{}},uniforms:{bvh:{value:s},envMap:{value:i},envRotationMatrix:{value:new v.Matrix3},cameraPos:{value:new v.Vector3},ior:{value:r.ior??2.417},dispersion:{value:r.dispersion??.012},absorption:{value:1+(r.absorptionFactor??0)*2},envIntensity:{value:r.envMapIntensity??2.2},gamma:{value:1},color:{value:new v.Color(r.hex)},rgbBoost:{value:new v.Vector3(...r.boostFactors??[1.3,1.3,1.3])},transmission:{value:0},reflectivity:{value:.46},facetSharpness:{value:1},rayBounces:{value:8},tCubeMapNormals:{value:e.texture},uEnvFlip:{value:i!=null&&i.isRenderTargetTexture?1:-1},uCentroid:{value:e.centroid?e.centroid.clone():new v.Vector3},uRadius:{value:e.radius??1},uCamLocal:{value:new v.Vector3},refractiveIndex:{value:r.ior??2.417},rIndexDelta:{value:r.dispersion??.012},absorptionFactor:{value:r.absorptionFactor??0},gemColor:{value:new v.Color(r.hex)},uExhaustionResidual:{value:.5},bounces:{value:5},uSplitBounces:{value:2},uDebugMode:{value:0}},side:v.FrontSide,transparent:!1,depthTest:!0,depthWrite:!0,toneMapped:!0,extensions:{derivatives:!0}});ee(this,"bakeHandle");ee(this,"onBeforeRender");this.bakeHandle=e,this.onBeforeRender=(a,c,u,m,f)=>{this.uniforms.cameraPos.value.copy(u.position),Zn.copy(f.matrixWorld).invert(),this.uniforms.uCamLocal.value.copy(u.position).applyMatrix4(Zn)}}updatePreset(e){if(this.uniforms.color&&this.uniforms.color.value.set(e.hex),this.uniforms.gemColor&&this.uniforms.gemColor.value.set(e.hex),this.uniforms.ior&&(this.uniforms.ior.value=e.ior??2.417),this.uniforms.refractiveIndex&&(this.uniforms.refractiveIndex.value=e.ior??2.417),this.uniforms.dispersion&&(this.uniforms.dispersion.value=e.dispersion??.012),this.uniforms.rIndexDelta&&(this.uniforms.rIndexDelta.value=e.dispersion??.012),this.uniforms.absorption&&(this.uniforms.absorption.value=1+(e.absorptionFactor??0)*2),this.uniforms.absorptionFactor&&(this.uniforms.absorptionFactor.value=e.absorptionFactor??0),this.uniforms.rgbBoost){const[i,r,o]=e.boostFactors??[2,2,2];this.uniforms.rgbBoost.value.set(i,r,o)}this.uniformsNeedUpdate=!0}}const Pt=new Map;function bn(n,t,e,i={}){const r=`${i.useCorrectFresnel?"_cf":""}${i.correctDispersionSign?"_cd":""}${i.accumulateTIR?"_at":""}`,o=`${n.key}_${e.id}_${e.hex}${r}`,s=Pt.get(o);if(s)return s.refCount++,s.material;const a=new Oe(n,t,e,i);return Pt.set(o,{material:a,refCount:1}),a}function gi(n){for(const[t,e]of Pt.entries())if(e.material===n){e.refCount--,e.refCount<=0&&(n.dispose(),Pt.delete(t));return}}class Ur extends v.Scene{constructor(){super();const t=new v.SphereGeometry(30,32,16),e=new v.MeshBasicMaterial({color:9476262,side:v.BackSide}),i=new v.Mesh(t,e);this.add(i);const r=new v.PlaneGeometry(16,16),o=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});o.color.setScalar(4);const s=new v.Mesh(r,o);s.position.set(0,14,0),s.rotation.x=Math.PI/2,this.add(s);const a=new v.PlaneGeometry(12,16),c=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});c.color.setScalar(3);const u=new v.Mesh(a,c);u.position.set(-10,8,10),u.lookAt(0,0,0),this.add(u);const m=new v.PlaneGeometry(12,16),f=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});f.color.setScalar(2.8);const l=new v.Mesh(m,f);l.position.set(10,8,10),l.lookAt(0,0,0),this.add(l);const d=new v.PlaneGeometry(2,22),y=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});y.color.setScalar(4.5);const w=new v.Mesh(d,y);w.position.set(-14,2,-2),w.lookAt(0,0,0),this.add(w);const b=new v.Mesh(d,y);b.position.set(14,2,-2),b.lookAt(0,0,0),this.add(b);const M=new v.PlaneGeometry(24,24),h=new v.MeshBasicMaterial({color:16119802,side:v.DoubleSide});h.color.setScalar(1.2);const p=new v.Mesh(M,h);p.position.set(0,-12,0),p.rotation.x=-Math.PI/2,this.add(p);const x=new v.PlaneGeometry(1.2,16),g=new v.MeshBasicMaterial({color:1184278,side:v.DoubleSide}),A=new v.Mesh(x,g);A.position.set(-5,4,-9),A.lookAt(0,0,0),this.add(A);const T=new v.Mesh(x,g);T.position.set(5,4,-9),T.lookAt(0,0,0),this.add(T)}dispose(){const t=new Set;this.traverse(e=>{e instanceof v.Mesh&&(e.geometry&&t.add(e.geometry),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>t.add(i)):t.add(e.material)))});for(const e of t)e.dispose();this.clear()}}function kr(n,t){const e=new v.PMREMGenerator(t);e.compileEquirectangularShader();const i=new Ur,r=e.fromScene(i).texture;return n.environment=r,i.dispose(),e.dispose(),r}class Qn extends v.Scene{constructor(){super();const t=new v.SphereGeometry(30,32,16),e=new v.MeshBasicMaterial({color:10528949,side:v.BackSide}),i=new v.Mesh(t,e);this.add(i);const r=[{pos:[0,15,8],size:[10,8],intensity:4.5},{pos:[0,15,-8],size:[10,8],intensity:4},{pos:[-9,14,0],size:[8,10],intensity:4},{pos:[9,14,0],size:[8,10],intensity:4}];for(const b of r){const M=new v.PlaneGeometry(b.size[0],b.size[1]),h=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});h.color.setScalar(b.intensity);const p=new v.Mesh(M,h);p.position.set(b.pos[0],b.pos[1],b.pos[2]),p.lookAt(0,0,0),this.add(p)}const o=[{pos:[-13,8,6],size:[8,9],intensity:3.5},{pos:[13,8,6],size:[8,9],intensity:3.5},{pos:[0,8,14],size:[10,7],intensity:3.8},{pos:[0,8,-14],size:[10,7],intensity:3.2}];for(const b of o){const M=new v.PlaneGeometry(b.size[0],b.size[1]),h=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});h.color.setScalar(b.intensity);const p=new v.Mesh(M,h);p.position.set(b.pos[0],b.pos[1],b.pos[2]),p.lookAt(0,0,0),this.add(p)}const s=new v.PlaneGeometry(5,5),a=new v.MeshBasicMaterial({color:4212048,side:v.DoubleSide}),c=new v.Mesh(s,a);c.position.set(0,18,0),c.rotation.x=Math.PI/2,this.add(c);const u=new v.PlaneGeometry(24,24),m=new v.MeshBasicMaterial({color:5264994,side:v.DoubleSide}),f=new v.Mesh(u,m);f.position.set(0,-12,0),f.rotation.x=-Math.PI/2,this.add(f);const l=new v.PlaneGeometry(1.4,15),d=new v.MeshBasicMaterial({color:3685962,side:v.DoubleSide}),y=[[7,11,7],[-7,11,7],[7,11,-7],[-7,11,-7]];for(const[b,M,h]of y){const p=new v.Mesh(l,d);p.position.set(b,M,h),p.lookAt(0,0,0),this.add(p)}const w=[[10,13,7],[-10,13,7],[10,13,-7],[-10,13,-7],[14,6,9],[-14,6,9],[14,6,-9],[-14,6,-9],[0,6,17],[7,-6,8]];for(const[b,M,h]of w){const p=new v.PlaneGeometry(2.6,2.6),x=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});x.color.setScalar(45);const g=new v.Mesh(p,x);g.position.set(b,M,h),g.lookAt(0,0,0),this.add(g)}}dispose(){const t=new Set;this.traverse(e=>{e instanceof v.Mesh&&(e.geometry&&t.add(e.geometry),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>t.add(i)):t.add(e.material)))});for(const e of t)e.dispose();this.clear()}}function ln(n,t,e=512){const i=new v.WebGLCubeRenderTarget(e,{format:v.RGBAFormat,type:v.HalfFloatType,generateMipmaps:!1,minFilter:v.LinearFilter,magFilter:v.LinearFilter}),r=new v.CubeCamera(.1,100,i),o=new Qn,s=n!=null&&n.getRenderTarget?n.getRenderTarget():null;return r.update(n,o),n!=null&&n.setRenderTarget&&n.setRenderTarget(s),o instanceof Qn&&o.dispose(),i.texture}async function un(n,t){const e=new v.PMREMGenerator(t);e.compileEquirectangularShader();function i(o){const s=e.fromEquirectangular(o);let a;try{a=new v.WebGLCubeRenderTarget(512,{format:v.RGBAFormat,type:v.HalfFloatType,generateMipmaps:!0,minFilter:v.LinearMipmapLinearFilter,magFilter:v.LinearFilter}),a.fromEquirectangularTexture(t,o)}catch{}return o.dispose(),e.dispose(),{renderTarget:s,texture:s.texture,gemRenderTarget:a,gemTexture:a?a.texture:s.texture,dispose:()=>{s.dispose(),a==null||a.dispose()}}}const r=typeof n=="string"?n.toLowerCase().includes(".exr"):n instanceof ArrayBuffer&&n.byteLength>=4&&new Uint8Array(n,0,4)[0]===118&&new Uint8Array(n,0,4)[1]===47;if(n instanceof ArrayBuffer)try{if(r){const o=new Tn.EXRLoader().parse(n),s=new v.DataTexture(o.data,o.width,o.height,o.format,o.type);return s.needsUpdate=!0,i(s)}else{const o=new Sn.RGBELoader().parse(n);return i(o)}}catch(o){throw e.dispose(),o}return new Promise((o,s)=>{r?new Tn.EXRLoader().load(n,a=>{try{o(i(a))}catch(c){a.dispose(),e.dispose(),s(c)}},void 0,a=>{e.dispose(),s(a)}):new Sn.RGBELoader().load(n,a=>{try{o(i(a))}catch(c){a.dispose(),e.dispose(),s(c)}},void 0,a=>{e.dispose(),s(a)})})}const ei=new WeakMap;function Gr(n){const t=ei.get(n);if(t)return t;let e=n;n.groups&&n.groups.length>1&&(e=n.clone(),e.clearGroups());const i=e.boundsTree??new It(e,{strategy:ui,setBoundingBox:!1});e.boundsTree=i;const r=new yi;return r.updateFrom(i),ei.set(n,r),r}function vi(n){return typeof n=="string"?JSON.parse(n):n}function fn(n){return typeof n=="string"?n.startsWith("#")?n:`#${n}`:"#"+(n>>>0).toString(16).padStart(6,"0")}function Or(n){const t=vi(n),e=t.side===2?v.DoubleSide:t.side===1?v.BackSide:v.FrontSide,i=new v.MeshPhysicalMaterial({name:t.name??"pmat-metal",color:new v.Color(fn(t.color)),roughness:t.roughness??0,metalness:t.metalness??1,envMapIntensity:t.envMapIntensity??1,clearcoat:t.clearcoat??0,clearcoatRoughness:t.clearcoatRoughness??0,side:e});return t.specularColor!==void 0&&(i.specularColor=new v.Color(fn(t.specularColor))),t.specularIntensity!==void 0&&(i.specularIntensity=t.specularIntensity),t.reflectivity!==void 0&&(i.reflectivity=t.reflectivity),i}function bi(n){const t=vi(n),e=fn(t.color??16777215),i=t.boostFactors??{x:1,y:1,z:1};return{id:t.name?`dmat-${t.name.toLowerCase().replace(/\s+/g,"-")}`:"dmat-custom",label:t.name??"Custom Diamond",hex:e,ior:t.refractiveIndex??2.6,dispersion:t.dispersion??.01,absorptionFactor:t.absorptionFactor??0,roughness:0,transmission:t.transmission??0,boostFactors:[i.x,i.y,i.z],category:"diamond",...t.squashFactor!==void 0?{squashFactor:t.squashFactor}:{},...t.geometryFactor!==void 0?{geometryFactor:t.geometryFactor}:{},...t.gammaFactor!==void 0?{gammaFactor:t.gammaFactor}:{}}}function Hr(n,t,e){const i=bi(n);return bn(t,e,i)}const qr=`
586
+ `;class Jr{constructor(){re(this,"cache",new Map)}get cacheSize(){return this.cache.size}getEntry(t){return this.cache.get(t)}acquire(t,e,i){const o=Do(t);if(!o.isBakeable)return null;const r=(i==null?void 0:i.resolution)??256,s=`${Lo(t,o)}_${r}`,a=this.cache.get(s);return a?(a.disposalTimer!==null&&(clearTimeout(a.disposalTimer),a.disposalTimer=null),a.refCount++,a.handle):this.bake(t,o,s,e,r)}bake(t,e,i,o,r){var u;const s=!((u=o.capabilities)!=null&&u.isWebGL2),a=new v.WebGLCubeRenderTarget(r,{type:s?v.UnsignedByteType:v.HalfFloatType,format:v.RGBAFormat,depthBuffer:!0,generateMipmaps:!1,minFilter:v.NearestFilter,magFilter:v.NearestFilter});this.renderToTarget(t,e,o,a,s);const c={key:i,texture:a.texture,centroid:e.centroid.clone(),radius:e.radius,encoding:s?"unorm":"signed"};return this.cache.set(i,{handle:c,renderTarget:a,refCount:1,disposalTimer:null,geometryRef:new WeakRef(t),resolution:r,analysis:e}),c}renderToTarget(t,e,i,o,r){var u,f;const s=t.getIndex()?t.toNonIndexed():t.clone(),a=No(s,e);s.setAttribute("aFacet",new v.BufferAttribute(a,4)),console.log("[DiamondBaker] renderToTarget called",{isUnorm:r,triangleCount:e.triangleCount,centroid:e.centroid.toArray(),radius:e.radius,facetDataLength:a.length,facetSample:Array.from(a.slice(0,8)),bakeGeoVertexCount:s.getAttribute("position").count,rendererCapabilities:(u=i.capabilities)==null?void 0:u.isWebGL2});const c=new v.ShaderMaterial({vertexShader:Yr,fragmentShader:Xr,side:v.DoubleSide,blending:v.NoBlending,transparent:!1,depthTest:!0,depthWrite:!0,toneMapped:!1,defines:r?{GEM_NORMALS_UNORM:1}:{},uniforms:{uCentroid:{value:e.centroid},uRadius:{value:e.radius}}});try{const d=new v.Scene,l=new v.Mesh(s,c);d.add(l);const m=Math.max(.001,e.radius*.001),p=Math.max(2.5,e.radius*3),w=new v.CubeCamera(m,p,o);w.position.copy(e.centroid);const y=((f=i.getRenderTarget)==null?void 0:f.call(i))??null,M=i.autoClear,h=i.toneMapping,g=new v.Color;i.getClearColor&&i.getClearColor(g);const x=i.getClearAlpha?i.getClearAlpha():1;i.toneMapping=v.NoToneMapping,i.autoClear=!0,i.setClearColor&&i.setClearColor(0,0);try{w.update(i,d)}finally{i.setRenderTarget&&i.setRenderTarget(y),i.autoClear=M,i.toneMapping=h,i.setClearColor&&i.setClearColor(g,x)}}finally{s.dispose(),c.dispose()}}release(t){const e=this.cache.get(t.key);e&&(e.refCount--,e.refCount<=0&&(e.refCount=0,e.disposalTimer!==null&&clearTimeout(e.disposalTimer),e.disposalTimer=setTimeout(()=>{e.renderTarget.dispose(),this.cache.delete(t.key)},1e3)))}clearCache(){for(const t of this.cache.values())t.disposalTimer!==null&&(clearTimeout(t.disposalTimer),t.disposalTimer=null),t.renderTarget.dispose();this.cache.clear()}onContextRestored(t){var e;for(const[i,o]of this.cache.entries()){const r=o.geometryRef.deref();if(!r){o.disposalTimer!==null&&(clearTimeout(o.disposalTimer),o.disposalTimer=null),o.renderTarget.dispose(),this.cache.delete(i);continue}const s=!((e=t.capabilities)!=null&&e.isWebGL2);o.renderTarget.dispose();const a=new v.WebGLCubeRenderTarget(o.resolution,{type:s?v.UnsignedByteType:v.HalfFloatType,format:v.RGBAFormat,depthBuffer:!0,generateMipmaps:!1,minFilter:v.NearestFilter,magFilter:v.NearestFilter});o.renderTarget=a,o.handle.texture=a.texture,o.handle.encoding=s?"unorm":"signed",this.renderToTarget(r,o.analysis,t,a,s)}}}const nt=new Jr,si=new v.Matrix4;class Xe extends v.ShaderMaterial{constructor(e,i,o,r={}){const s=e.bvh??new Mi;super({vertexShader:jr,fragmentShader:Kr,glslVersion:v.GLSL3,defines:{USE_CUBE_ENV:1,MAX_BOUNCES:5,...e.encoding==="unorm"?{GEM_NORMALS_UNORM:1}:{},...r.useCorrectFresnel?{USE_CORRECT_FRESNEL:1}:{},...r.correctDispersionSign?{CORRECT_DISPERSION_SIGN:1}:{},...r.accumulateTIR?{ACCUMULATE_TIR:1}:{}},uniforms:{bvh:{value:s},envMap:{value:i},envRotationMatrix:{value:new v.Matrix3},cameraPos:{value:new v.Vector3},ior:{value:o.ior??2.417},dispersion:{value:o.dispersion??.012},absorption:{value:1+(o.absorptionFactor??0)*2},envIntensity:{value:o.envMapIntensity??2.2},gamma:{value:1},color:{value:new v.Color(o.hex)},rgbBoost:{value:new v.Vector3(...o.boostFactors??[1.3,1.3,1.3])},transmission:{value:0},reflectivity:{value:.46},facetSharpness:{value:1},rayBounces:{value:8},tCubeMapNormals:{value:e.texture},uEnvFlip:{value:i!=null&&i.isRenderTargetTexture?1:-1},uCentroid:{value:e.centroid?e.centroid.clone():new v.Vector3},uRadius:{value:e.radius??1},uCamLocal:{value:new v.Vector3},refractiveIndex:{value:o.ior??2.417},rIndexDelta:{value:o.dispersion??.012},absorptionFactor:{value:o.absorptionFactor??0},gemColor:{value:new v.Color(o.hex)},uExhaustionResidual:{value:.5},bounces:{value:5},uSplitBounces:{value:2},uDebugMode:{value:0}},side:v.FrontSide,transparent:!1,depthTest:!0,depthWrite:!0,toneMapped:!0,extensions:{derivatives:!0}});re(this,"bakeHandle");re(this,"onBeforeRender");this.bakeHandle=e,this.onBeforeRender=(a,c,u,f,d)=>{this.uniforms.cameraPos.value.copy(u.position),si.copy(d.matrixWorld).invert(),this.uniforms.uCamLocal.value.copy(u.position).applyMatrix4(si)}}updatePreset(e){if(this.uniforms.color&&this.uniforms.color.value.set(e.hex),this.uniforms.gemColor&&this.uniforms.gemColor.value.set(e.hex),this.uniforms.ior&&(this.uniforms.ior.value=e.ior??2.417),this.uniforms.refractiveIndex&&(this.uniforms.refractiveIndex.value=e.ior??2.417),this.uniforms.dispersion&&(this.uniforms.dispersion.value=e.dispersion??.012),this.uniforms.rIndexDelta&&(this.uniforms.rIndexDelta.value=e.dispersion??.012),this.uniforms.absorption&&(this.uniforms.absorption.value=1+(e.absorptionFactor??0)*2),this.uniforms.absorptionFactor&&(this.uniforms.absorptionFactor.value=e.absorptionFactor??0),this.uniforms.rgbBoost){const[i,o,r]=e.boostFactors??[2,2,2];this.uniforms.rgbBoost.value.set(i,o,r)}this.uniformsNeedUpdate=!0}}const Rt=new Map;function Sn(n,t,e,i={}){const o=`${i.useCorrectFresnel?"_cf":""}${i.correctDispersionSign?"_cd":""}${i.accumulateTIR?"_at":""}`,r=`${n.key}_${e.id}_${e.hex}${o}`,s=Rt.get(r);if(s)return s.refCount++,s.material;const a=new Xe(n,t,e,i);return Rt.set(r,{material:a,refCount:1}),a}function Ai(n){for(const[t,e]of Rt.entries())if(e.material===n){e.refCount--,e.refCount<=0&&(n.dispose(),Rt.delete(t));return}}class Zr extends v.Scene{constructor(){super();const t=new v.SphereGeometry(30,32,16),e=new v.MeshBasicMaterial({color:9476262,side:v.BackSide}),i=new v.Mesh(t,e);this.add(i);const o=new v.PlaneGeometry(16,16),r=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});r.color.setScalar(4);const s=new v.Mesh(o,r);s.position.set(0,14,0),s.rotation.x=Math.PI/2,this.add(s);const a=new v.PlaneGeometry(12,16),c=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});c.color.setScalar(3);const u=new v.Mesh(a,c);u.position.set(-10,8,10),u.lookAt(0,0,0),this.add(u);const f=new v.PlaneGeometry(12,16),d=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});d.color.setScalar(2.8);const l=new v.Mesh(f,d);l.position.set(10,8,10),l.lookAt(0,0,0),this.add(l);const m=new v.PlaneGeometry(2,22),p=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});p.color.setScalar(4.5);const w=new v.Mesh(m,p);w.position.set(-14,2,-2),w.lookAt(0,0,0),this.add(w);const y=new v.Mesh(m,p);y.position.set(14,2,-2),y.lookAt(0,0,0),this.add(y);const M=new v.PlaneGeometry(24,24),h=new v.MeshBasicMaterial({color:16119802,side:v.DoubleSide});h.color.setScalar(1.2);const g=new v.Mesh(M,h);g.position.set(0,-12,0),g.rotation.x=-Math.PI/2,this.add(g);const x=new v.PlaneGeometry(1.2,16),b=new v.MeshBasicMaterial({color:1184278,side:v.DoubleSide}),A=new v.Mesh(x,b);A.position.set(-5,4,-9),A.lookAt(0,0,0),this.add(A);const S=new v.Mesh(x,b);S.position.set(5,4,-9),S.lookAt(0,0,0),this.add(S)}dispose(){const t=new Set;this.traverse(e=>{e instanceof v.Mesh&&(e.geometry&&t.add(e.geometry),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>t.add(i)):t.add(e.material)))});for(const e of t)e.dispose();this.clear()}}function Qr(n,t){const e=new v.PMREMGenerator(t);e.compileEquirectangularShader();const i=new Zr,o=e.fromScene(i).texture;return n.environment=o,i.dispose(),e.dispose(),o}class ai extends v.Scene{constructor(){super();const t=new v.SphereGeometry(30,32,16),e=new v.MeshBasicMaterial({color:10528949,side:v.BackSide}),i=new v.Mesh(t,e);this.add(i);const o=[{pos:[0,15,8],size:[10,8],intensity:4.5},{pos:[0,15,-8],size:[10,8],intensity:4},{pos:[-9,14,0],size:[8,10],intensity:4},{pos:[9,14,0],size:[8,10],intensity:4}];for(const y of o){const M=new v.PlaneGeometry(y.size[0],y.size[1]),h=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});h.color.setScalar(y.intensity);const g=new v.Mesh(M,h);g.position.set(y.pos[0],y.pos[1],y.pos[2]),g.lookAt(0,0,0),this.add(g)}const r=[{pos:[-13,8,6],size:[8,9],intensity:3.5},{pos:[13,8,6],size:[8,9],intensity:3.5},{pos:[0,8,14],size:[10,7],intensity:3.8},{pos:[0,8,-14],size:[10,7],intensity:3.2}];for(const y of r){const M=new v.PlaneGeometry(y.size[0],y.size[1]),h=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});h.color.setScalar(y.intensity);const g=new v.Mesh(M,h);g.position.set(y.pos[0],y.pos[1],y.pos[2]),g.lookAt(0,0,0),this.add(g)}const s=new v.PlaneGeometry(5,5),a=new v.MeshBasicMaterial({color:4212048,side:v.DoubleSide}),c=new v.Mesh(s,a);c.position.set(0,18,0),c.rotation.x=Math.PI/2,this.add(c);const u=new v.PlaneGeometry(24,24),f=new v.MeshBasicMaterial({color:5264994,side:v.DoubleSide}),d=new v.Mesh(u,f);d.position.set(0,-12,0),d.rotation.x=-Math.PI/2,this.add(d);const l=new v.PlaneGeometry(1.4,15),m=new v.MeshBasicMaterial({color:3685962,side:v.DoubleSide}),p=[[7,11,7],[-7,11,7],[7,11,-7],[-7,11,-7]];for(const[y,M,h]of p){const g=new v.Mesh(l,m);g.position.set(y,M,h),g.lookAt(0,0,0),this.add(g)}const w=[[10,13,7],[-10,13,7],[10,13,-7],[-10,13,-7],[14,6,9],[-14,6,9],[14,6,-9],[-14,6,-9],[0,6,17],[7,-6,8]];for(const[y,M,h]of w){const g=new v.PlaneGeometry(2.6,2.6),x=new v.MeshBasicMaterial({color:16777215,side:v.DoubleSide});x.color.setScalar(45);const b=new v.Mesh(g,x);b.position.set(y,M,h),b.lookAt(0,0,0),this.add(b)}}dispose(){const t=new Set;this.traverse(e=>{e instanceof v.Mesh&&(e.geometry&&t.add(e.geometry),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>t.add(i)):t.add(e.material)))});for(const e of t)e.dispose();this.clear()}}function pn(n,t,e=512){const i=new v.WebGLCubeRenderTarget(e,{format:v.RGBAFormat,type:v.HalfFloatType,generateMipmaps:!1,minFilter:v.LinearFilter,magFilter:v.LinearFilter}),o=new v.CubeCamera(.1,100,i),r=new ai,s=n!=null&&n.getRenderTarget?n.getRenderTarget():null;return o.update(n,r),n!=null&&n.setRenderTarget&&n.setRenderTarget(s),r instanceof ai&&r.dispose(),i.texture}async function hn(n,t){const e=new v.PMREMGenerator(t);e.compileEquirectangularShader();function i(r){const s=e.fromEquirectangular(r);let a;try{a=new v.WebGLCubeRenderTarget(512,{format:v.RGBAFormat,type:v.HalfFloatType,generateMipmaps:!0,minFilter:v.LinearMipmapLinearFilter,magFilter:v.LinearFilter}),a.fromEquirectangularTexture(t,r)}catch{}return r.dispose(),e.dispose(),{renderTarget:s,texture:s.texture,gemRenderTarget:a,gemTexture:a?a.texture:s.texture,dispose:()=>{s.dispose(),a==null||a.dispose()}}}const o=typeof n=="string"?n.toLowerCase().includes(".exr"):n instanceof ArrayBuffer&&n.byteLength>=4&&new Uint8Array(n,0,4)[0]===118&&new Uint8Array(n,0,4)[1]===47;if(n instanceof ArrayBuffer)try{if(o){const r=new _n.EXRLoader().parse(n),s=new v.DataTexture(r.data,r.width,r.height,r.format,r.type);return s.needsUpdate=!0,i(s)}else{const r=new Fn.RGBELoader().parse(n);return i(r)}}catch(r){throw e.dispose(),r}return new Promise((r,s)=>{o?new _n.EXRLoader().load(n,a=>{try{r(i(a))}catch(c){a.dispose(),e.dispose(),s(c)}},void 0,a=>{e.dispose(),s(a)}):new Fn.RGBELoader().load(n,a=>{try{r(i(a))}catch(c){a.dispose(),e.dispose(),s(c)}},void 0,a=>{e.dispose(),s(a)})})}const ci=new WeakMap;function es(n){const t=ci.get(n);if(t)return t;let e=n;n.groups&&n.groups.length>1&&(e=n.clone(),e.clearGroups());const i=e.boundsTree??new It(e,{strategy:yi,setBoundingBox:!1});e.boundsTree=i;const o=new Mi;return o.updateFrom(i),ci.set(n,o),o}function Si(n){return typeof n=="string"?JSON.parse(n):n}function yn(n){return typeof n=="string"?n.startsWith("#")?n:`#${n}`:"#"+(n>>>0).toString(16).padStart(6,"0")}function ts(n){const t=Si(n),e=t.side===2?v.DoubleSide:t.side===1?v.BackSide:v.FrontSide,i=new v.MeshPhysicalMaterial({name:t.name??"pmat-metal",color:new v.Color(yn(t.color)),roughness:t.roughness??0,metalness:t.metalness??1,envMapIntensity:t.envMapIntensity??1,clearcoat:t.clearcoat??0,clearcoatRoughness:t.clearcoatRoughness??0,side:e});return t.specularColor!==void 0&&(i.specularColor=new v.Color(yn(t.specularColor))),t.specularIntensity!==void 0&&(i.specularIntensity=t.specularIntensity),t.reflectivity!==void 0&&(i.reflectivity=t.reflectivity),i}function Ti(n){const t=Si(n),e=yn(t.color??16777215),i=t.boostFactors??{x:1,y:1,z:1};return{id:t.name?`dmat-${t.name.toLowerCase().replace(/\s+/g,"-")}`:"dmat-custom",label:t.name??"Custom Diamond",hex:e,ior:t.refractiveIndex??2.6,dispersion:t.dispersion??.01,absorptionFactor:t.absorptionFactor??0,roughness:0,transmission:t.transmission??0,boostFactors:[i.x,i.y,i.z],category:"diamond",...t.squashFactor!==void 0?{squashFactor:t.squashFactor}:{},...t.geometryFactor!==void 0?{geometryFactor:t.geometryFactor}:{},...t.gammaFactor!==void 0?{gammaFactor:t.gammaFactor}:{}}}function ns(n,t,e){const i=Ti(n);return Sn(t,e,i)}const is=`
587
587
  precision highp float;
588
588
 
589
589
  out vec3 vWorldNormal;
@@ -595,7 +595,7 @@ void main() {
595
595
  vWorldNormal = normalize(mat3(modelMatrix) * normal);
596
596
  gl_Position = projectionMatrix * viewMatrix * worldPos;
597
597
  }
598
- `,$r=`
598
+ `,os=`
599
599
  precision highp float;
600
600
  precision highp sampler2D;
601
601
  precision highp samplerCube;
@@ -844,5 +844,5 @@ void main() {
844
844
  #define gl_FragColor fragColor
845
845
  #include <colorspace_fragment>
846
846
  }
847
- `;function xn(n){switch(n){case"low":return{rayBounces:3,cubeResolution:128};case"medium":return{rayBounces:5,cubeResolution:256};case"high":return{rayBounces:6,cubeResolution:256};case"ultra":return{rayBounces:8,cubeResolution:512}}}const ti=new v.Matrix4;class ye extends v.ShaderMaterial{constructor(e,i,r,o={}){const a=o.quality?xn(o.quality).rayBounces:o.rayBounces??5,c=i.isCubeTexture===!0,u=r.boostFactors??[1,1,1],[m,f,l]=u;super({vertexShader:qr,fragmentShader:$r,glslVersion:v.GLSL3,defines:{RAY_BOUNCES:a,ENV_MAP_TYPE:c?0:1,DIA_ORIENT_ENVMAP:o.orientEnvMap?1:0,HAS_GEM_INCLUSIONS:0,GEM_NORMALS_UNORM:e.encoding==="unorm"?1:0},uniforms:{modelOffsetMatrix:{value:new v.Matrix4},modelOffsetMatrixInv:{value:new v.Matrix4},viewMatrixUniform:{value:new v.Matrix4},cameraPosition:{value:new v.Vector3},tCubeMapNormals:{value:e.texture},radius:{value:e.radius??1},centerOffset:{value:e.centroid?e.centroid.clone():new v.Vector3},envMap:{value:i},envMapRotation:{value:0},envMapIntensity:{value:r.envMapIntensity??1},refractiveIndex:{value:r.ior??2.6},rIndexDelta:{value:r.dispersion??.012},absorptionFactor:{value:r.absorptionFactor??1},squashFactor:{value:r.squashFactor??.98},geometryFactor:{value:r.geometryFactor??.5},gammaFactor:{value:r.gammaFactor??1},ambientFloor:{value:r.ambientFloor??.05},reflectivity:{value:.5},boostFactors:{value:new v.Vector3(m,f,l)},color:{value:new v.Color(r.hex)},colorCorrection:{value:new v.Vector3(1,1,1)},transmission:{value:0},clampHDR:{value:!1},useInclusion:{value:!1}},side:v.FrontSide,transparent:!1,depthTest:!0,depthWrite:!0,toneMapped:!0});ee(this,"bakeHandle");ee(this,"preset");ee(this,"onBeforeRender");this.bakeHandle=e,this.preset={...r},this.onBeforeRender=(d,y,w,b,M)=>{w.getWorldPosition(this.uniforms.cameraPosition.value),this.uniforms.modelOffsetMatrix.value.copy(M.matrixWorld),ti.copy(M.matrixWorld).invert(),this.uniforms.modelOffsetMatrixInv.value.copy(ti),this.uniforms.viewMatrixUniform.value.copy(w.matrixWorldInverse)}}updatePreset(e){if(this.preset={...this.preset,...e},this.uniforms.refractiveIndex.value=e.ior??2.6,this.uniforms.rIndexDelta.value=e.dispersion??.012,this.uniforms.absorptionFactor.value=e.absorptionFactor??1,this.uniforms.color.value.set(e.hex),e.squashFactor!==void 0&&(this.uniforms.squashFactor.value=e.squashFactor),e.geometryFactor!==void 0&&(this.uniforms.geometryFactor.value=e.geometryFactor),e.gammaFactor!==void 0&&(this.uniforms.gammaFactor.value=e.gammaFactor),e.envMapIntensity!==void 0&&(this.uniforms.envMapIntensity.value=e.envMapIntensity),e.ambientFloor!==void 0&&(this.uniforms.ambientFloor.value=e.ambientFloor),e.boostFactors){const[i,r,o]=e.boostFactors;this.uniforms.boostFactors.value.set(i,r,o)}this.uniformsNeedUpdate=!0}setEnvMap(e){this.uniforms.envMap.value=e;const r=e.isCubeTexture===!0?0:1;this.defines.ENV_MAP_TYPE!==r&&(this.defines.ENV_MAP_TYPE=r,this.needsUpdate=!0)}clone(){var i;const e=new ye(this.bakeHandle,this.uniforms.envMap.value,this.preset,{orientEnvMap:this.defines.DIA_ORIENT_ENVMAP===1,rayBounces:this.defines.RAY_BOUNCES});return e.name=this.name,(i=this.uniforms.color)!=null&&i.value&&e.uniforms.color.value.copy(this.uniforms.color.value),e}}const Et=new Map;function xi(n,t,e,i={}){const r=i.quality??`b${i.rayBounces??5}`,o=i.orientEnvMap?"_o1":"_o0",s=`ref_${n.key}_${e.id}_${e.hex}_${r}${o}`,a=Et.get(s);if(a)return a.refCount++,a.material;const c=new ye(n,t,e,i);return Et.set(s,{material:c,refCount:1}),c}function wi(n){for(const[t,e]of Et.entries())if(e.material===n){e.refCount--,e.refCount<=0&&(n.dispose(),Et.delete(t));return}}function Ue(n,t,e){const i=mn.find(o=>o.id===t)??ge.find(o=>o.id===t),r=Array.isArray(n.material)?e!==void 0?n.material[e]?[n.material[e]]:[]:n.material:e===void 0||e===0?n.material?[n.material]:[]:[];for(const o of r)o&&o instanceof v.MeshStandardMaterial&&(o.color.set(i?i.hex:t),o.metalness=(i==null?void 0:i.metalness)??o.metalness??1,o.roughness=(i==null?void 0:i.roughness)??o.roughness,o.envMapIntensity=1.2,o instanceof v.MeshPhysicalMaterial&&(o.clearcoat=0,i!=null&&i.specularColor&&(o.specularColor=new v.Color(i.specularColor)),i!=null&&i.ior&&(o.ior=i.ior)),o.needsUpdate=!0)}function ke(n,t,e){const i=pn.find(o=>o.id===t)??le.find(o=>o.id===t),r=Array.isArray(n.material)?e!==void 0?n.material[e]?[n.material[e]]:[]:n.material:e===void 0||e===0?n.material?[n.material]:[]:[];for(const o of r)if(o)if(o instanceof ye)i?o.updatePreset(i):(o.uniforms.color.value.set(t),o.uniformsNeedUpdate=!0);else if(o instanceof Oe)if(i){const s=o.bakeHandle,a=bn(s,o.uniforms.envMap.value,i);if(a!==o)if(gi(o),Array.isArray(n.material)){const c=n.material.indexOf(o);c!==-1&&(n.material[c]=a)}else n.material=a;else o.updatePreset(i)}else o.uniforms.color.value.set(t),o.uniformsNeedUpdate=!0;else o instanceof v.MeshPhysicalMaterial&&(o.color.set(i?i.hex:t),i&&(o.ior=i.ior,o.roughness=i.roughness,i.specularColor&&(o.specularColor=new v.Color(i.specularColor)),i.attenuationColor&&(o.attenuationColor=new v.Color(i.attenuationColor),o.attenuationDistance=i.attenuationDistance??.5)),o.transmission=0,o.transparent=!1,o.envMapIntensity=3,o.needsUpdate=!0)}function ni(n,t,e,i,r="reference"){var m,f,l;const o=Array.isArray(n.material)?n.material[0]:n.material,s=o instanceof v.MeshPhysicalMaterial,a=o instanceof Oe,c=s&&o.metalness>.5;if(t==="metal"){if(!s||!c){const d=o,y=new v.MeshPhysicalMaterial({color:d instanceof v.MeshStandardMaterial?d.color.clone():new v.Color("#C0C0C0"),metalness:1,roughness:0,clearcoat:0,envMapIntensity:1,side:v.DoubleSide});o instanceof Oe?gi(o):o instanceof ye?wi(o):d==null||d.dispose(),d!=null&&d.name&&(y.name=d.name),d!=null&&d.userData&&(y.userData={...d.userData,...y.userData}),n.material=y}return}const u=o instanceof ye;if(a||u){i&&(u?o.setEnvMap(i):o.uniforms.envMap.value=i);return}if(e){let d=Qe.acquire(n.geometry,e);if(!d&&(n.geometry.index?n.geometry.index.count:((m=n.geometry.attributes.position)==null?void 0:m.count)??0)/3<5e3){n.geometry.boundingSphere||n.geometry.computeBoundingSphere();const w=Gr(n.geometry),b=i??ln(e);d={key:`bvh_${n.geometry.id}`,texture:b instanceof v.CubeTexture?b:new v.WebGLCubeRenderTarget(1).texture,centroid:(f=n.geometry.boundingSphere)!=null&&f.center?n.geometry.boundingSphere.center.clone():new v.Vector3,radius:((l=n.geometry.boundingSphere)==null?void 0:l.radius)??1,encoding:"signed",bvh:w}}if(d){const y=i??ln(e);let w;r==="reference"&&!d.key.startsWith("bvh_")?w=xi(d,y,le[0]):w=bn(d,y,le[0]);const b=o;b==null||b.dispose(),b!=null&&b.name&&(w.name=b.name),b!=null&&b.userData&&(w.userData={...b.userData,...w.userData}),n.material=w;return}}if(!s||c){const d=o,y=new v.MeshPhysicalMaterial({color:d instanceof v.MeshStandardMaterial?d.color.clone():new v.Color("#FFFFFF"),metalness:0,transmission:0,ior:2.417,roughness:0,thickness:.5,envMapIntensity:3,transparent:!1});d==null||d.dispose(),d!=null&&d.name&&(y.name=d.name),d!=null&&d.userData&&(y.userData={...d.userData,...y.userData}),n.material=y}}function Wr(n,t,e=!0){let i,r=!0,o="high";t instanceof v.PerspectiveCamera?(i=t,typeof e=="boolean"?r=e:e&&typeof e=="object"&&(r=e.antialias??!0,e.quality&&(o=e.quality))):typeof t=="boolean"?r=t:t&&typeof t=="object"&&(r=t.antialias??!0,t.quality&&(o=t.quality));const s=new v.WebGLRenderer({antialias:r,alpha:!1});s.outputColorSpace=v.SRGBColorSpace,s.toneMapping=v.ACESFilmicToneMapping,s.toneMappingExposure=1,s.setSize(n.clientWidth,n.clientHeight),s.shadowMap.enabled=!1,n.appendChild(s.domElement);function a(u){const m=typeof window<"u"?window.devicePixelRatio:1;let f=1;u==="low"?f=1:u==="medium"?f=Math.min(m,1.5):u==="high"&&(f=Math.min(m,2)),s.setPixelRatio(f)}a(o);let c=null;return typeof ResizeObserver<"u"&&(c=new ResizeObserver(()=>{const u=n.clientWidth,m=n.clientHeight;s.setSize(u,m),i&&(i.aspect=m>0?u/m:1,i.updateProjectionMatrix())}),c.observe(n)),{renderer:s,setQuality:a,dispose:()=>{c==null||c.disconnect(),s.dispose(),s.domElement.remove()}}}function Yr(n=1710618,t=25){const e=new v.Scene,i=n==="studio"?1447448:n;e.background=new v.Color(i);const r=new v.PerspectiveCamera(t,1,.01,1e3);r.position.set(0,0,3);const o=new v.DirectionalLight("#ffffff",1);o.position.set(5,8,5),e.add(o);const s=new v.DirectionalLight("#e0e8ff",.4);return s.position.set(-5,3,-5),e.add(s),{scene:e,camera:r,dispose:()=>{e.clear()}}}function ii(n,t,e){n.aspect=e>0?t/e:1,n.updateProjectionMatrix()}function jr(n,t,e={}){const i=new qi.OrbitControls(n,t);i.enableDamping=!0,i.dampingFactor=.05,i.screenSpacePanning=!1,i.autoRotate=e.autoRotate??!1,i.autoRotateSpeed=e.autoRotateSpeed??2;const r=n.position.clone(),o=i.target.clone();function s(){n.position.copy(r),i.target.copy(o),i.update()}return{controls:i,initialPosition:r,initialTarget:o,resetCamera:s,dispose:()=>{i.dispose()}}}function oi(n,t,e,i={}){const r="controls"in e?e.controls:e,s=new v.Box3().setFromObject(n).getBoundingSphere(new v.Sphere),a=s.radius>0?s.radius:1,c=v.MathUtils.degToRad(t.fov),u=a/Math.tan(c/2)*1.15;r.target.copy(s.center),t.position.set(s.center.x,s.center.y,s.center.z+u),t.near=a*.01,t.far=a*100,t.updateProjectionMatrix(),r.minDistance=i.minZoom??a*.5,r.maxDistance=i.maxZoom??a*6,r.update()}function Xr(n,t,e,i,r,o=()=>[],s){const a=new v.Raycaster,c=new v.Vector2;let u=null,m;const f=new v.Color;let l=0,d=!1,y={x:0,y:0};const w=(s==null?void 0:s.hoverHighlight)??!1;function b(){const S=[];return t.traverse(P=>{P.isMesh&&S.push(P)}),S}function M(S){const P=Array.isArray(S.material)?S.material[0]:S.material;return P instanceof v.MeshStandardMaterial?P:null}function h(S,P){var C,F;if(!(S===u&&P===m)){if(u&&w){const _=M(u);_&&(_.emissive.copy(f),_.emissiveIntensity=l)}if(u=S,m=P,S){if(w){const V=M(S);V&&(f.copy(V.emissive),l=V.emissiveIntensity,V.emissive.set(16777215),V.emissiveIntensity=.3)}(C=n.domElement)!=null&&C.style&&(n.domElement.style.cursor="pointer");const _=o().find(V=>V.meshId===S.uuid);if(_){const V=P!==void 0&&_.slots[P]!==void 0?P:0,k=_.slots[V];r.emit("partHover",{meshId:_.meshId,partId:_.partId,type:_.type,slotIndex:V,slotId:k==null?void 0:k.slotId,materialName:(k==null?void 0:k.materialName)??_.materialName})}else r.emit("partHover",null)}else(F=n.domElement)!=null&&F.style&&(n.domElement.style.cursor="default"),r.emit("partHover",null)}}function p(S){var _;if(d)return;const P=n.domElement.getBoundingClientRect();if(P.width===0||P.height===0)return;c.x=(S.clientX-P.left)/P.width*2-1,c.y=-((S.clientY-P.top)/P.height)*2+1,a.setFromCamera(c,e);const F=a.intersectObjects(b(),!1)[0];h(F?F.object:null,(_=F==null?void 0:F.face)==null?void 0:_.materialIndex)}function x(){h(null,void 0)}function g(S){y={x:S.clientX,y:S.clientY}}function A(S){var _;const P=S.clientX-y.x,C=S.clientY-y.y;if(Math.sqrt(P*P+C*C)<4){let V=u,k=m;if(!V){const H=n.domElement.getBoundingClientRect();if(H.width>0&&H.height>0){c.x=(S.clientX-H.left)/H.width*2-1,c.y=-((S.clientY-H.top)/H.height)*2+1,a.setFromCamera(c,e);const te=a.intersectObjects(b(),!1);te.length>0&&(V=te[0].object,k=(_=te[0].face)==null?void 0:_.materialIndex)}}if(V){const H=o().find(te=>te.meshId===V.uuid);if(H){const te=k!==void 0&&H.slots[k]!==void 0?k:0,oe=H.slots[te];r.emit("partSelected",{meshId:H.meshId,partId:H.partId,type:H.type,slotIndex:te,slotId:oe==null?void 0:oe.slotId,materialName:(oe==null?void 0:oe.materialName)??H.materialName})}}}}function T(){d=!0}function I(){d=!1}const E=n.domElement;return E.addEventListener("pointermove",p),E.addEventListener("pointerdown",g),E.addEventListener("pointerup",A),E.addEventListener("pointerleave",x),i.addEventListener("start",T),i.addEventListener("end",I),{dispose:()=>{E.removeEventListener("pointermove",p),E.removeEventListener("pointerdown",g),E.removeEventListener("pointerup",A),E.removeEventListener("pointerleave",x),i.removeEventListener("start",T),i.removeEventListener("end",I),h(null),E!=null&&E.style&&(E.style.cursor="default")}}}function Kr(n,t,e,i,r,o,s,a){const c={metalColor:n,stoneColor:t,parts:{...e},cameraState:{position:i.position.toArray(),target:r.target.toArray()}};return o&&Object.keys(o).length>0&&(c.materialColors={...o}),s&&Object.keys(s).length>0&&(c.partColors={...s}),c}function Jr(n,t,e,i,r,o,s){var m,f;const a=[],c=[],u=[];t(n.metalColor),e(n.stoneColor);for(const[l,d]of Object.entries(n.parts||{}))s!=null&&s.availablePartIds&&!s.availablePartIds.has(l)&&(a.push(l),u.push(`Part type override target '${l}' not found in model`),console.warn(`[3d-viewer] Part type override target '${l}' not found in loaded model`)),i(l,d);if(n.materialColors&&(s!=null&&s.setMaterialColor))for(const[l,d]of Object.entries(n.materialColors))!s.availableSlotIds&&!s.availableMaterialNames||((m=s.availableSlotIds)==null?void 0:m.has(l))||((f=s.availableMaterialNames)==null?void 0:f.has(l))||(c.push(l),u.push(`Material slot '${l}' not found in model`),console.warn(`[3d-viewer] Material slot '${l}' not found in loaded model`)),s.setMaterialColor(l,d);if(n.partColors&&(s!=null&&s.setPartColor))for(const[l,d]of Object.entries(n.partColors)){let y=l,w;const b=l.lastIndexOf(":");b>0&&!isNaN(Number(l.slice(b+1)))&&(y=l.slice(0,b),w=Number(l.slice(b+1))),s.availablePartIds&&!s.availablePartIds.has(y)&&(a.push(y),u.push(`Part '${y}' not found in model`),console.warn(`[3d-viewer] Part '${y}' not found in loaded model`)),s.setPartColor(y,d,w)}return n.cameraState&&(r.position.fromArray(n.cameraState.position),o.target.fromArray(n.cameraState.target),o.update()),{success:!0,unresolvedParts:a.length>0?a:void 0,unresolvedMaterials:c.length>0?c:void 0,warnings:u.length>0?u:void 0}}function Zr(n,t=1.2){let e;if(typeof document<"u"&&typeof document.createElement=="function"){const s=document.createElement("canvas");s.width=256,s.height=256;const a=s.getContext?s.getContext("2d"):null;if(a){const u=a.createRadialGradient(128,128,0,128,128,128);u.addColorStop(0,"rgba(0, 0, 0, 0.65)"),u.addColorStop(.3,"rgba(0, 0, 0, 0.4)"),u.addColorStop(.7,"rgba(0, 0, 0, 0.15)"),u.addColorStop(1,"rgba(0, 0, 0, 0)"),a.fillStyle=u,a.fillRect(0,0,256,256)}const c=new v.CanvasTexture(s);c.needsUpdate=!0,e=c}else e=new v.Texture,e.needsUpdate=!0;const i=new v.PlaneGeometry(t*2,t*2);i.rotateX(-Math.PI/2);const r=new v.MeshBasicMaterial({map:e,transparent:!0,opacity:.85,depthWrite:!1}),o=new v.Mesh(i,r);return o.position.y=-.5,o.renderOrder=-1,n.add(o),{mesh:o,setVisible:s=>{o.visible=s},setScale:s=>{o.scale.setScalar(s)},dispose:()=>{n.remove(o),i.dispose(),r.dispose(),e.dispose()}}}function Kt(n){n.traverse(t=>{var e;t instanceof v.Mesh&&((e=t.geometry)==null||e.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(r=>{var o,s,a,c,u;r instanceof v.MeshStandardMaterial&&((o=r.map)==null||o.dispose(),(s=r.normalMap)==null||s.dispose(),(a=r.roughnessMap)==null||a.dispose(),(c=r.metalnessMap)==null||c.dispose(),(u=r.envMap)==null||u.dispose()),r.dispose()}))})}function Qr(n,t={}){var Mn;const e=new Zi,i=Yr(t.background??16777215,t.fov??25),{scene:r,camera:o,dispose:s}=i,a=Wr(n,o,t),{renderer:c}=a,u=jr(o,c.domElement,t),m=u.controls,f=Zr(r);t.shadows===!1&&f.setVisible(!1),kr(r,c);let l;try{l=ln(c)}catch{}let d=null,y=null;function w(R){if(!(typeof navigator<"u"&&/Mobi/i.test(navigator.userAgent)&&(typeof window>"u"||window.devicePixelRatio<=2)))return R;const N="medium",z=["low","medium","high","ultra"];return z.indexOf(R)<=z.indexOf(N)?R:N}let b=w(t.diamondQuality??"medium"),M=null;async function h(R){try{const L=await un(R,c);d==null||d.dispose(),d=L,r.environment=L.texture,t.gemEnvUrl||(l=L.gemTexture??L.texture,A==null||A.traverse(N=>{N instanceof v.Mesh&&(N.material instanceof ye?N.material.setEnvMap(l):N.material instanceof Oe&&(N.material.uniforms.envMap.value=l))}))}catch(L){throw e.emit("error",L instanceof Error?L:new Error(String(L))),L}}async function p(R){try{const L=await un(R,c);y==null||y.dispose(),y=L,l=L.gemTexture??L.texture,A==null||A.traverse(N=>{N instanceof v.Mesh&&(N.material instanceof ye?N.material.setEnvMap(l):N.material instanceof Oe&&(N.material.uniforms.envMap.value=l))})}catch(L){throw e.emit("error",L instanceof Error?L:new Error(String(L))),L}}t.metalEnvUrl&&h(t.metalEnvUrl).catch(()=>{}),t.gemEnvUrl&&p(t.gemEnvUrl).catch(()=>{});const x=c.domElement,g=()=>{Qe.onContextRestored(c)};(Mn=x.addEventListener)==null||Mn.call(x,"webglcontextrestored",g);let A=null,T=[],I=[],E={},S={},P={},C=ge[0].hex,F=le[0].hex,_=null,V=null;typeof ResizeObserver<"u"&&(V=new ResizeObserver(()=>{ii(o,n.clientWidth,n.clientHeight)}),V.observe(n));let k=0,H=!1;function te(){m.update(),c.render(r,o),!H&&typeof requestAnimationFrame<"u"&&(k=requestAnimationFrame(te))}function oe(){const R=H;H=typeof document<"u"?document.hidden:!1,R&&!H&&typeof requestAnimationFrame<"u"&&(k=requestAnimationFrame(te))}typeof document<"u"&&document.addEventListener("visibilitychange",oe),typeof requestAnimationFrame<"u"&&(k=requestAnimationFrame(te));const qe=Xr(c,r,o,m,e,()=>T,{hoverHighlight:t.hoverHighlight??!1});function ie(){if(typeof(Be==null?void 0:Be.__getCurrentModel)=="function"){const R=Be.__getCurrentModel();if(R)return R}return A}function re(R,L,N){const z=`${R.partId}:${L}`;if(P[z])return{color:P[z],isOverridden:!0};const D=`${R.meshId}:${L}`;return P[D]?{color:P[D],isOverridden:!0}:P[R.partId]?{color:P[R.partId],isOverridden:!0}:P[R.meshId]?{color:P[R.meshId],isOverridden:!0}:N!=null&&N.slotId&&S[N.slotId]?{color:S[N.slotId],isOverridden:!0}:N!=null&&N.materialName&&S[N.materialName]?{color:S[N.materialName],isOverridden:!0}:R.materialName&&S[R.materialName]?{color:S[R.materialName],isOverridden:!0}:{color:R.type==="metal"?C:F,isOverridden:!1}}function nt(R,L){if(Array.isArray(R.material))R.material=R.material.map(N=>{let z=0;if(L.traverse(D=>{D instanceof v.Mesh&&(Array.isArray(D.material)?D.material.includes(N):D.material===N)&&z++}),z>1&&typeof N.clone=="function"){const D=N.clone();return D.name=N.name,D}return N});else if(R.material){let N=0;if(L.traverse(z=>{z instanceof v.Mesh&&(Array.isArray(z.material)?z.material.includes(R.material):z.material===R.material)&&N++}),N>1&&typeof R.material.clone=="function"){const z=R.material.clone();z.name=R.material.name,R.material=z}}}function be(R,L){const N=ie();if(N){let z=!1;if(Array.isArray(R.material))R.material.forEach((D,U)=>{const G=L.slots[U];re(L,U,G).isOverridden&&(z=!0)});else{const D=L.slots[0];re(L,0,D).isOverridden&&(z=!0)}z&&nt(R,N)}if(Array.isArray(R.material))R.material.forEach((z,D)=>{const U=L.slots[D],{color:G}=re(L,D,U);L.type==="metal"?Ue(R,G,D):ke(R,G,D)});else{const z=L.slots[0],{color:D}=re(L,0,z);L.type==="metal"?Ue(R,D):ke(R,D)}}async function xe(R,L={}){_==null||_.abort(),_=new AbortController;const N=_;L.signal&&(L.signal.aborted?N.abort():L.signal.addEventListener("abort",()=>N.abort(),{once:!0}));const z=N.signal;e.emit("loading",{progress:0});try{const D=L.dracoDecoderPath??t.dracoDecoderPath??dn,U=await ci(R,z,se=>{e.emit("loading",{progress:se*.8})},{dracoDecoderPath:D});if(z.aborted)return;e.emit("loading",{progress:.85});const G=new ri.GLTFLoader,W=new si.DRACOLoader;W.setDecoderPath(D),G.setDRACOLoader(W);let me;try{me=await new Promise((se,Ce)=>{G.parse(U.glb,"",se,Ce)})}finally{W.dispose()}if(z.aborted)return;e.emit("loading",{progress:.9}),A&&(r.remove(A),Kt(A),A=null),A=me.scene,Ft(A),r.add(A),T=En(A,E),I=Rn(T),A.traverse(se=>{if(!(se instanceof v.Mesh))return;const Ce=T.find(Vi=>Vi.meshId===se.uuid),An=(Ce==null?void 0:Ce.type)??"metal";ni(se,An,c,l,t.diamondMode??"reference"),Ce?be(se,Ce):An==="metal"?Ue(se,C):ke(se,F)}),b!=="medium"&&zt(b),oi(A,o,m,t),ii(o,n.clientWidth,n.clientHeight);const we=new v.Box3().setFromObject(A),ct=we.getBoundingSphere(new v.Sphere),lt=ct.radius>0?ct.radius:1;f.mesh.position.y=we.min.y,f.setScale(lt),e.emit("loading",{progress:1}),e.emit("loaded",{parts:T,materials:I})}catch(D){if(D.name==="AbortError"||z.aborted)return;e.emit("error",D instanceof Error?D:new Error(String(D)))}}function it(R){var N,z;C=((N=mn.find(D=>D.id===R))==null?void 0:N.hex)??((z=ge.find(D=>D.id===R))==null?void 0:z.hex)??R;const L=ie();L&&(L.traverse(D=>{if(!(D instanceof v.Mesh))return;const U=T.find(G=>G.meshId===D.uuid);if(((U==null?void 0:U.type)??"metal")==="metal")if(U)if(Array.isArray(D.material))D.material.forEach((G,W)=>{const me=U.slots[W],{isOverridden:we}=re(U,W,me);we||Ue(D,C,W)});else{const G=U.slots[0],{isOverridden:W}=re(U,0,G);W||Ue(D,C)}else Ue(D,C)}),e.emit("change",de()))}function ot(R){var N,z;F=((N=pn.find(D=>D.id===R))==null?void 0:N.hex)??((z=le.find(D=>D.id===R))==null?void 0:z.hex)??R;const L=ie();L&&(L.traverse(D=>{if(!(D instanceof v.Mesh))return;const U=T.find(G=>G.meshId===D.uuid);if((U==null?void 0:U.type)==="stone")if(U)if(Array.isArray(D.material))D.material.forEach((G,W)=>{const me=U.slots[W],{isOverridden:we}=re(U,W,me);we||ke(D,F,W)});else{const G=U.slots[0],{isOverridden:W}=re(U,0,G);W||ke(D,F)}else ke(D,F)}),e.emit("change",de()))}function rt(R,L){const N=T.find(U=>U.meshId===R||U.partId===R),z=N?N.partId:R;E[z]=L;const D=ie();D&&(T=En(D,E),I=Rn(T),D.traverse(U=>{if(!(U instanceof v.Mesh))return;const G=T.find(W=>W.meshId===U.uuid);!G||G.partId!==z&&G.meshId!==R||(ni(U,L,c,l,t.diamondMode??"reference"),be(U,G))}),L==="stone"&&b!=="medium"&&zt(b)),e.emit("change",de())}function st(R,L){const N=I.filter(D=>D.slotId===R||D.name===R);if(N.length>0)for(const D of N)S[D.slotId]=L;S[R]=L;const z=ie();z&&z.traverse(D=>{if(!(D instanceof v.Mesh))return;const U=T.find(G=>G.meshId===D.uuid);U&&be(D,U)}),e.emit("change",de())}function at(R,L,N){const z=N!==void 0?`${R}:${N}`:R;P[z]=L;const D=ie();D&&D.traverse(U=>{if(!(U instanceof v.Mesh))return;const G=T.find(W=>W.meshId===U.uuid);G&&(G.partId===R||G.meshId===R)&&be(U,G)}),e.emit("change",de())}function Vt(R){delete S[R];for(const N of I)(N.slotId===R||N.name===R)&&(delete S[N.slotId],delete S[N.name]);const L=ie();L&&L.traverse(N=>{if(!(N instanceof v.Mesh))return;const z=T.find(D=>D.meshId===N.uuid);z&&be(N,z)}),e.emit("change",de())}function $e(R,L){if(L!==void 0)delete P[`${R}:${L}`];else{delete P[R];for(const z of Object.keys(P))z.startsWith(`${R}:`)&&delete P[z]}const N=ie();N&&N.traverse(z=>{if(!(z instanceof v.Mesh))return;const D=T.find(U=>U.meshId===z.uuid);D&&(D.partId===R||D.meshId===R)&&be(z,D)}),e.emit("change",de())}function Mi(){S={},P={};const R=ie();R&&R.traverse(L=>{if(!(L instanceof v.Mesh))return;const N=T.find(z=>z.meshId===L.uuid);N&&be(L,N)}),e.emit("change",de())}function Ai(){return[...I]}function Si(){return[...T]}function de(){return Kr(C,F,E,o,m,S,P)}function wn(R){E={},S={},P={};const L=new Set(T.map(U=>U.partId)),N=new Set(I.map(U=>U.slotId)),z=new Set(I.map(U=>U.name));return Jr(R,it,ot,rt,o,m,{setMaterialColor:st,setPartColor:at,availablePartIds:L,availableSlotIds:N,availableMaterialNames:z})}t.initialState&&(wn(t.initialState),u.initialPosition.copy(o.position),u.initialTarget.copy(m.target));function Ti(R,L){return e.on(R,L)}function Bi(){var R;M!==null&&(clearTimeout(M),M=null),_==null||_.abort(),typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(k),typeof document<"u"&&document.removeEventListener("visibilitychange",oe),(R=x.removeEventListener)==null||R.call(x,"webglcontextrestored",g),Qe.clearCache(),V==null||V.disconnect(),f.dispose(),qe.dispose(),u.dispose(),A&&(r.remove(A),Kt(A),A=null),d==null||d.dispose(),y==null||y.dispose(),s(),a.dispose(),e.clear()}function Ci(R){return R!==void 0&&(m.autoRotateSpeed=R),m.autoRotate=!m.autoRotate,m.autoRotate}function Ii(R){R!==void 0&&(m.autoRotateSpeed=R),m.autoRotate=!0}function Pi(){m.autoRotate=!1}function Ei(){return m.autoRotate}function Ri(){u.resetCamera()}function Fi(){A&&oi(A,o,m,t)}async function _i(R){const L=(R==null?void 0:R.format)??"image/png",N=(R==null?void 0:R.quality)??.95;return c.render(r,o),c.domElement.toDataURL(L,N)}function Di(R){a.setQuality(R)}function Ni(R){f.setVisible(R)}function Li(){_==null||_.abort(),A&&(r.remove(A),Kt(A),A=null),T=[],E={},I=[],S={},P={},f.mesh.position.y=0,f.setScale(1)}function zt(R){const L=w(R);M!==null&&clearTimeout(M),M=setTimeout(()=>{if(M=null,b=L,!A)return;const{rayBounces:N,cubeResolution:z}=xn(L);A.traverse(D=>{var lt;if(!(D instanceof v.Mesh))return;const U=T.find(se=>se.meshId===D.uuid);if((U==null?void 0:U.type)!=="stone")return;const G=D.material;if(!(G instanceof ye))return;const W=G.bakeHandle,me=Qe.acquire(D.geometry,c,{resolution:z});if(!me)return;Qe.release(W);const we=((lt=G.uniforms.envMap)==null?void 0:lt.value)??l,ct=xi(me,we,G.preset,{rayBounces:N,quality:L,orientEnvMap:G.defines.DIA_ORIENT_ENVMAP===1});wi(G),D.material=ct})},300)}const Be={load:xe,unload:Li,setMetalColor:it,setStoneColor:ot,setPartType:rt,setMaterialColor:st,setPartColor:at,clearMaterialColor:Vt,clearPartColor:$e,clearOverrides:Mi,getMaterials:Ai,getParts:Si,getState:de,setState:wn,on:Ti,dispose:Bi,toggleRotation:Ci,startRotation:Ii,stopRotation:Pi,isRotating:Ei,resetCamera:Ri,fitToScene:Fi,captureSnapshot:_i,setQuality:Di,setShadowsEnabled:Ni,setMetalEnvironment:h,setGemEnvironment:p,setDiamondQuality:zt};return typeof window<"u"&&(Be.__scene=r,Be.__getCurrentModel=()=>A),Be}const es="1.0.0";exports.ALL_METAL_PRESETS=mn;exports.ALL_STONE_PRESETS=pn;exports.CANONICAL_METAL_PRESETS=go;exports.CANONICAL_STONE_PRESETS=vo;exports.CorruptFileError=He;exports.DEFAULT_DRACO_DECODER_PATH=dn;exports.DIAMOND_PRESETS=mo;exports.GEMSTONE_PRESETS=po;exports.METAL_PRESETS=ge;exports.NetworkError=tt;exports.PHYSICALLY_BASED_METAL_PRESETS=fo;exports.STONE_PRESETS=le;exports.UnsupportedFormatError=Rt;exports.VERSION=es;exports.convert=ci;exports.createViewer=Qr;exports.getMetalPreset=bo;exports.getStonePreset=xo;exports.inferFormatFromUrl=ai;exports.loadDmatMaterial=Hr;exports.loadDmatPreset=bi;exports.loadHdrEnvironment=un;exports.loadPmat=Or;exports.normalizeModelSource=ro;exports.resolveQualityTier=xn;
847
+ `;function Tn(n){switch(n){case"low":return{rayBounces:3,cubeResolution:128};case"medium":return{rayBounces:5,cubeResolution:256};case"high":return{rayBounces:6,cubeResolution:256};case"ultra":return{rayBounces:8,cubeResolution:512}}}const li=new v.Matrix4;class Me extends v.ShaderMaterial{constructor(e,i,o,r={}){const a=r.quality?Tn(r.quality).rayBounces:r.rayBounces??5,c=i.isCubeTexture===!0,u=o.boostFactors??[1,1,1],[f,d,l]=u;super({vertexShader:is,fragmentShader:os,glslVersion:v.GLSL3,defines:{RAY_BOUNCES:a,ENV_MAP_TYPE:c?0:1,DIA_ORIENT_ENVMAP:r.orientEnvMap?1:0,HAS_GEM_INCLUSIONS:0,GEM_NORMALS_UNORM:e.encoding==="unorm"?1:0},uniforms:{modelOffsetMatrix:{value:new v.Matrix4},modelOffsetMatrixInv:{value:new v.Matrix4},viewMatrixUniform:{value:new v.Matrix4},cameraPosition:{value:new v.Vector3},tCubeMapNormals:{value:e.texture},radius:{value:e.radius??1},centerOffset:{value:e.centroid?e.centroid.clone():new v.Vector3},envMap:{value:i},envMapRotation:{value:0},envMapIntensity:{value:o.envMapIntensity??1},refractiveIndex:{value:o.ior??2.6},rIndexDelta:{value:o.dispersion??.012},absorptionFactor:{value:o.absorptionFactor??1},squashFactor:{value:o.squashFactor??.98},geometryFactor:{value:o.geometryFactor??.5},gammaFactor:{value:o.gammaFactor??1},ambientFloor:{value:o.ambientFloor??.05},reflectivity:{value:.5},boostFactors:{value:new v.Vector3(f,d,l)},color:{value:new v.Color(o.hex)},colorCorrection:{value:new v.Vector3(1,1,1)},transmission:{value:0},clampHDR:{value:!1},useInclusion:{value:!1}},side:v.FrontSide,transparent:!1,depthTest:!0,depthWrite:!0,toneMapped:!0});re(this,"bakeHandle");re(this,"preset");re(this,"onBeforeRender");this.bakeHandle=e,this.preset={...o},this.onBeforeRender=(m,p,w,y,M)=>{w.getWorldPosition(this.uniforms.cameraPosition.value),this.uniforms.modelOffsetMatrix.value.copy(M.matrixWorld),li.copy(M.matrixWorld).invert(),this.uniforms.modelOffsetMatrixInv.value.copy(li),this.uniforms.viewMatrixUniform.value.copy(w.matrixWorldInverse)}}updatePreset(e){if(this.preset={...this.preset,...e},this.uniforms.refractiveIndex.value=e.ior??2.6,this.uniforms.rIndexDelta.value=e.dispersion??.012,this.uniforms.absorptionFactor.value=e.absorptionFactor??1,this.uniforms.color.value.set(e.hex),e.squashFactor!==void 0&&(this.uniforms.squashFactor.value=e.squashFactor),e.geometryFactor!==void 0&&(this.uniforms.geometryFactor.value=e.geometryFactor),e.gammaFactor!==void 0&&(this.uniforms.gammaFactor.value=e.gammaFactor),e.envMapIntensity!==void 0&&(this.uniforms.envMapIntensity.value=e.envMapIntensity),e.ambientFloor!==void 0&&(this.uniforms.ambientFloor.value=e.ambientFloor),e.boostFactors){const[i,o,r]=e.boostFactors;this.uniforms.boostFactors.value.set(i,o,r)}this.uniformsNeedUpdate=!0}setEnvMap(e){this.uniforms.envMap.value=e;const o=e.isCubeTexture===!0?0:1;this.defines.ENV_MAP_TYPE!==o&&(this.defines.ENV_MAP_TYPE=o,this.needsUpdate=!0)}clone(){var i;const e=new Me(this.bakeHandle,this.uniforms.envMap.value,this.preset,{orientEnvMap:this.defines.DIA_ORIENT_ENVMAP===1,rayBounces:this.defines.RAY_BOUNCES});return e.name=this.name,(i=this.uniforms.color)!=null&&i.value&&e.uniforms.color.value.copy(this.uniforms.color.value),e}}const Et=new Map;function Ci(n,t,e,i={}){const o=i.quality??`b${i.rayBounces??5}`,r=i.orientEnvMap?"_o1":"_o0",s=`ref_${n.key}_${e.id}_${e.hex}_${o}${r}`,a=Et.get(s);if(a)return a.refCount++,a.material;const c=new Me(n,t,e,i);return Et.set(s,{material:c,refCount:1}),c}function Bi(n){for(const[t,e]of Et.entries())if(e.material===n){e.refCount--,e.refCount<=0&&(n.dispose(),Et.delete(t));return}}function $e(n,t,e){const i=vn.find(r=>r.id===t)??Se.find(r=>r.id===t),o=Array.isArray(n.material)?e!==void 0?n.material[e]?[n.material[e]]:[]:n.material:e===void 0||e===0?n.material?[n.material]:[]:[];for(const r of o)r&&r instanceof v.MeshStandardMaterial&&(r.color.set(i?i.hex:t),r.metalness=(i==null?void 0:i.metalness)??r.metalness??1,r.roughness=(i==null?void 0:i.roughness)??r.roughness,r.envMapIntensity=1.2,r instanceof v.MeshPhysicalMaterial&&(r.clearcoat>0&&(r.clearcoat=0,r.needsUpdate=!0),i!=null&&i.specularColor&&(r.specularColor?r.specularColor.set(i.specularColor):r.specularColor=new v.Color(i.specularColor)),(i==null?void 0:i.ior)!==void 0&&(r.ior=i.ior)))}function We(n,t,e){const i=bn.find(r=>r.id===t)??de.find(r=>r.id===t),o=Array.isArray(n.material)?e!==void 0?n.material[e]?[n.material[e]]:[]:n.material:e===void 0||e===0?n.material?[n.material]:[]:[];for(const r of o)if(r){if(r instanceof Me)i?r.updatePreset(i):(r.uniforms.color.value.set(t),r.uniformsNeedUpdate=!0);else if(r instanceof Xe)if(i){const s=r.bakeHandle,a=Sn(s,r.uniforms.envMap.value,i);if(a!==r)if(Ai(r),Array.isArray(n.material)){const c=n.material.indexOf(r);c!==-1&&(n.material[c]=a)}else n.material=a;else r.updatePreset(i)}else r.uniforms.color.value.set(t),r.uniformsNeedUpdate=!0;else if(r instanceof v.MeshPhysicalMaterial){r.color.set(i?i.hex:t),i&&(r.ior=i.ior,r.roughness=i.roughness,i.specularColor&&(r.specularColor?r.specularColor.set(i.specularColor):r.specularColor=new v.Color(i.specularColor)),i.attenuationColor&&(r.attenuationColor?r.attenuationColor.set(i.attenuationColor):r.attenuationColor=new v.Color(i.attenuationColor),r.attenuationDistance=i.attenuationDistance??.5));const s=r.transmission>0,a=r.transparent!==!1;r.transmission=0,r.transparent=!1,r.envMapIntensity=3,(s||a)&&(r.needsUpdate=!0)}}}function ui(n,t,e,i,o="reference"){var f,d,l;const r=Array.isArray(n.material)?n.material[0]:n.material,s=r instanceof v.MeshPhysicalMaterial,a=r instanceof Xe,c=s&&r.metalness>.5;if(t==="metal"){if(!s||!c){const m=r,p=new v.MeshPhysicalMaterial({color:m instanceof v.MeshStandardMaterial?m.color.clone():new v.Color("#C0C0C0"),metalness:1,roughness:0,clearcoat:0,envMapIntensity:1,side:v.DoubleSide});r instanceof Xe?Ai(r):r instanceof Me?Bi(r):m==null||m.dispose(),m!=null&&m.name&&(p.name=m.name),m!=null&&m.userData&&(p.userData={...m.userData,...p.userData}),n.material=p}return}const u=r instanceof Me;if(a||u){i&&(u?r.setEnvMap(i):r.uniforms.envMap.value=i);return}if(e){let m=nt.acquire(n.geometry,e);if(!m&&(n.geometry.index?n.geometry.index.count:((f=n.geometry.attributes.position)==null?void 0:f.count)??0)/3<5e3){n.geometry.boundingSphere||n.geometry.computeBoundingSphere();const w=es(n.geometry),y=i??pn(e);m={key:`bvh_${n.geometry.id}`,texture:y instanceof v.CubeTexture?y:new v.WebGLCubeRenderTarget(1).texture,centroid:(d=n.geometry.boundingSphere)!=null&&d.center?n.geometry.boundingSphere.center.clone():new v.Vector3,radius:((l=n.geometry.boundingSphere)==null?void 0:l.radius)??1,encoding:"signed",bvh:w}}if(m){const p=i??pn(e);let w;o==="reference"&&!m.key.startsWith("bvh_")?w=Ci(m,p,de[0]):w=Sn(m,p,de[0]);const y=r;y==null||y.dispose(),y!=null&&y.name&&(w.name=y.name),y!=null&&y.userData&&(w.userData={...y.userData,...w.userData}),n.material=w;return}}if(!s||c){const m=r,p=new v.MeshPhysicalMaterial({color:m instanceof v.MeshStandardMaterial?m.color.clone():new v.Color("#FFFFFF"),metalness:0,transmission:0,ior:2.417,roughness:0,thickness:.5,envMapIntensity:3,transparent:!1});m==null||m.dispose(),m!=null&&m.name&&(p.name=m.name),m!=null&&m.userData&&(p.userData={...m.userData,...p.userData}),n.material=p}}function rs(n,t,e=!0){let i,o=!0,r="high",s;t instanceof v.PerspectiveCamera?(i=t,typeof e=="boolean"?o=e:e&&typeof e=="object"&&(o=e.antialias??!0,e.quality&&(r=e.quality),s=e.onResize)):typeof t=="boolean"?o=t:t&&typeof t=="object"&&(o=t.antialias??!0,t.quality&&(r=t.quality),s=t.onResize);const a=new v.WebGLRenderer({antialias:o,alpha:!1,powerPreference:"default"});a.outputColorSpace=v.SRGBColorSpace,a.toneMapping=v.ACESFilmicToneMapping,a.toneMappingExposure=1,a.setSize(n.clientWidth,n.clientHeight),a.shadowMap.enabled=!1,n.appendChild(a.domElement);let c=!1;function u(d){var w,y;const l=typeof window<"u"&&!!((y=(w=window.matchMedia)==null?void 0:w.call(window,"(pointer: coarse)"))!=null&&y.matches||typeof navigator<"u"&&((navigator.maxTouchPoints??0)>0||(navigator.msMaxTouchPoints??0)>0)),m=typeof window<"u"?window.devicePixelRatio:1;let p=1;d==="low"?p=1:d==="medium"?p=Math.min(m,l?1.25:1.5):d==="high"&&(p=Math.min(m,l?1.5:2)),a.setPixelRatio(p),c&&(s==null||s())}u(r),c=!0;let f=null;return typeof ResizeObserver<"u"&&(f=new ResizeObserver(()=>{const d=n.clientWidth,l=n.clientHeight;a.setSize(d,l),i&&(i.aspect=l>0?d/l:1,i.updateProjectionMatrix()),s==null||s()}),f.observe(n)),{renderer:a,setQuality:u,dispose:()=>{f==null||f.disconnect(),a.dispose(),a.domElement.remove()}}}function ss(n=1710618,t=25){const e=new v.Scene,i=n==="studio"?1447448:n;e.background=new v.Color(i);const o=new v.PerspectiveCamera(t,1,.01,1e3);o.position.set(0,0,3);const r=new v.DirectionalLight("#ffffff",1);r.position.set(5,8,5),e.add(r);const s=new v.DirectionalLight("#e0e8ff",.4);return s.position.set(-5,3,-5),e.add(s),{scene:e,camera:o,dispose:()=>{e.clear()}}}function as(n,t,e){n.aspect=e>0?t/e:1,n.updateProjectionMatrix()}function cs(n,t,e={}){const i=new io.OrbitControls(n,t);i.enableDamping=!0,i.dampingFactor=.05,i.screenSpacePanning=!1,i.autoRotate=e.autoRotate??!1,i.autoRotateSpeed=e.autoRotateSpeed??2;const o=n.position.clone(),r=i.target.clone();function s(){n.position.copy(o),i.target.copy(r),i.update()}return{controls:i,initialPosition:o,initialTarget:r,resetCamera:s,dispose:()=>{i.dispose()}}}function fi(n,t,e,i={}){const o="controls"in e?e.controls:e,s=new v.Box3().setFromObject(n).getBoundingSphere(new v.Sphere),a=s.radius>0?s.radius:1,c=v.MathUtils.degToRad(t.fov),u=a/Math.tan(c/2)*1.15;o.target.copy(s.center),t.position.set(s.center.x,s.center.y,s.center.z+u),t.near=a*.01,t.far=a*100,t.updateProjectionMatrix(),o.minDistance=i.minZoom??a*.5,o.maxDistance=i.maxZoom??a*6,o.update()}function ls(n,t,e,i,o,r=()=>[],s){const a=new v.Raycaster,c=new v.Vector2;let u=null,f;const d=new v.Color;let l=0,m=!1,p={x:0,y:0},w=null,y=0;const M=(s==null?void 0:s.hoverHighlight)??!1;function h(){w=null}function g(){if(w!==null)return w;const _=[];return t.traverse(V=>{V.isMesh&&_.push(V)}),w=_,w}function x(_){const V=Array.isArray(_.material)?_.material[0]:_.material;return V instanceof v.MeshStandardMaterial?V:null}function b(_,V){var U,ne;if(!(_===u&&V===f)){if(u&&M){const q=x(u);q&&(q.emissive.copy(d),q.emissiveIntensity=l)}if(u=_,f=V,_){if(M){const $=x(_);$&&(d.copy($.emissive),l=$.emissiveIntensity,$.emissive.set(16777215),$.emissiveIntensity=.3)}(U=n.domElement)!=null&&U.style&&(n.domElement.style.cursor="pointer");const q=r().find($=>$.meshId===_.uuid);if(q){const $=V!==void 0&&q.slots[V]!==void 0?V:0,G=q.slots[$];o.emit("partHover",{meshId:q.meshId,partId:q.partId,type:q.type,slotIndex:$,slotId:G==null?void 0:G.slotId,materialName:(G==null?void 0:G.materialName)??q.materialName})}else o.emit("partHover",null)}else(ne=n.domElement)!=null&&ne.style&&(n.domElement.style.cursor="default"),o.emit("partHover",null)}}function A(){var U;if(y=0,m)return;a.setFromCamera(c,e);const V=a.intersectObjects(g(),!1)[0];b(V?V.object:null,(U=V==null?void 0:V.face)==null?void 0:U.materialIndex)}function S(_){if(m)return;const V=n.domElement.getBoundingClientRect();V.width===0||V.height===0||(c.x=(_.clientX-V.left)/V.width*2-1,c.y=-((_.clientY-V.top)/V.height)*2+1,typeof requestAnimationFrame<"u"?y===0&&(y=requestAnimationFrame(A)):A())}function P(){y!==0&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(y),y=0),b(null,void 0)}function E(_){p={x:_.clientX,y:_.clientY}}function T(_){var q;const V=_.clientX-p.x,U=_.clientY-p.y;if(Math.sqrt(V*V+U*U)<4){let $=u,G=f;if(!$){const X=n.domElement.getBoundingClientRect();if(X.width>0&&X.height>0){c.x=(_.clientX-X.left)/X.width*2-1,c.y=-((_.clientY-X.top)/X.height)*2+1,a.setFromCamera(c,e);const se=a.intersectObjects(g(),!1);se.length>0&&($=se[0].object,G=(q=se[0].face)==null?void 0:q.materialIndex)}}if($){const X=r().find(se=>se.meshId===$.uuid);if(X){const se=G!==void 0&&X.slots[G]!==void 0?G:0,ce=X.slots[se];o.emit("partSelected",{meshId:X.meshId,partId:X.partId,type:X.type,slotIndex:se,slotId:ce==null?void 0:ce.slotId,materialName:(ce==null?void 0:ce.materialName)??X.materialName})}}}}function R(){m=!0,y!==0&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(y),y=0)}function B(){m=!1}const F=n.domElement;return F.addEventListener("pointermove",S),F.addEventListener("pointerdown",E),F.addEventListener("pointerup",T),F.addEventListener("pointerleave",P),i.addEventListener("start",R),i.addEventListener("end",B),{dispose:()=>{y!==0&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(y),y=0),w=null,F.removeEventListener("pointermove",S),F.removeEventListener("pointerdown",E),F.removeEventListener("pointerup",T),F.removeEventListener("pointerleave",P),i.removeEventListener("start",R),i.removeEventListener("end",B),b(null),F!=null&&F.style&&(F.style.cursor="default")},invalidateMeshes:h}}function us(n,t,e,i,o,r,s,a){const c={metalColor:n,stoneColor:t,parts:{...e},cameraState:{position:i.position.toArray(),target:o.target.toArray()}};return r&&Object.keys(r).length>0&&(c.materialColors={...r}),s&&Object.keys(s).length>0&&(c.partColors={...s}),c}function fs(n,t,e,i,o,r,s){var f,d;const a=[],c=[],u=[];(!(s!=null&&s.currentColor)||s.currentColor.metalColor!==n.metalColor)&&t(n.metalColor),(!(s!=null&&s.currentColor)||s.currentColor.stoneColor!==n.stoneColor)&&e(n.stoneColor);for(const[l,m]of Object.entries(n.parts||{}))s!=null&&s.availablePartIds&&!s.availablePartIds.has(l)&&(a.push(l),u.push(`Part type override target '${l}' not found in model`),console.warn(`[3d-viewer] Part type override target '${l}' not found in loaded model`)),i(l,m);if(n.materialColors&&(s!=null&&s.setMaterialColor))for(const[l,m]of Object.entries(n.materialColors))!s.availableSlotIds&&!s.availableMaterialNames||((f=s.availableSlotIds)==null?void 0:f.has(l))||((d=s.availableMaterialNames)==null?void 0:d.has(l))||(c.push(l),u.push(`Material slot '${l}' not found in model`),console.warn(`[3d-viewer] Material slot '${l}' not found in loaded model`)),s.setMaterialColor(l,m);if(n.partColors&&(s!=null&&s.setPartColor))for(const[l,m]of Object.entries(n.partColors)){let p=l,w;const y=l.lastIndexOf(":");y>0&&!isNaN(Number(l.slice(y+1)))&&(p=l.slice(0,y),w=Number(l.slice(y+1))),s.availablePartIds&&!s.availablePartIds.has(p)&&(a.push(p),u.push(`Part '${p}' not found in model`),console.warn(`[3d-viewer] Part '${p}' not found in loaded model`)),s.setPartColor(p,m,w)}return n.cameraState&&(o.position.fromArray(n.cameraState.position),r.target.fromArray(n.cameraState.target),r.update()),{success:!0,unresolvedParts:a.length>0?a:void 0,unresolvedMaterials:c.length>0?c:void 0,warnings:u.length>0?u:void 0}}let ge=null,Tt=0;function ds(n,t=1.2){let e;const i=typeof document<"u"&&typeof document.createElement=="function";if(i){if(!ge){const c=document.createElement("canvas");c.width=256,c.height=256;const u=c.getContext?c.getContext("2d"):null;if(u){const f=u.createRadialGradient(128,128,0,128,128,128);f.addColorStop(0,"rgba(0, 0, 0, 0.65)"),f.addColorStop(.3,"rgba(0, 0, 0, 0.4)"),f.addColorStop(.7,"rgba(0, 0, 0, 0.15)"),f.addColorStop(1,"rgba(0, 0, 0, 0)"),u.fillStyle=f,u.fillRect(0,0,256,256)}ge=new v.CanvasTexture(c),ge.colorSpace=v.SRGBColorSpace,ge.needsUpdate=!0}Tt++,e=ge}else e=new v.Texture,e.needsUpdate=!0;const o=new v.PlaneGeometry(t*2,t*2);o.rotateX(-Math.PI/2);const r=new v.MeshBasicMaterial({map:e,transparent:!0,opacity:.85,depthWrite:!1}),s=new v.Mesh(o,r);s.position.y=-.5,s.renderOrder=-1,n.add(s);let a=!1;return{mesh:s,setVisible:c=>{s.visible=c},setScale:c=>{s.scale.setScalar(c)},dispose:()=>{a||(a=!0,n.remove(s),o.dispose(),r.dispose(),i&&e===ge?(Tt--,Tt<=0&&(ge==null||ge.dispose(),ge=null,Tt=0)):e.dispose())}}}function tn(n){n.traverse(t=>{var e;t instanceof v.Mesh&&((e=t.geometry)==null||e.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(o=>{var r,s,a,c,u;o instanceof v.MeshStandardMaterial&&((r=o.map)==null||r.dispose(),(s=o.normalMap)==null||s.dispose(),(a=o.roughnessMap)==null||a.dispose(),(c=o.metalnessMap)==null||c.dispose(),(u=o.envMap)==null||u.dispose()),o.dispose()}))})}function ms(n,t={}){var Rn,En;const e=new fo,i=ss(t.background??16777215,t.fov??25),{scene:o,camera:r,dispose:s}=i,a=rs(n,r,{...t,onResize:()=>G()}),{renderer:c}=a,u=cs(r,c.domElement,t),f=u.controls,d=ds(o);t.shadows===!1&&d.setVisible(!1),Qr(o,c);let l;try{l=pn(c)}catch{}let m=null,p=null;function w(I){if(!(typeof navigator<"u"&&/Mobi/i.test(navigator.userAgent)&&(typeof window>"u"||window.devicePixelRatio<=2)))return I;const L="medium",z=["low","medium","high","ultra"];return z.indexOf(I)<=z.indexOf(L)?I:L}let y=w(t.diamondQuality??"medium"),M=null;async function h(I){try{const D=await hn(I,c);m==null||m.dispose(),m=D,o.environment=D.texture,t.gemEnvUrl||(l=D.gemTexture??D.texture,A==null||A.traverse(L=>{L instanceof v.Mesh&&(L.material instanceof Me?L.material.setEnvMap(l):L.material instanceof Xe&&(L.material.uniforms.envMap.value=l))})),G()}catch(D){throw e.emit("error",D instanceof Error?D:new Error(String(D))),D}}async function g(I){try{const D=await hn(I,c);p==null||p.dispose(),p=D,l=D.gemTexture??D.texture,A==null||A.traverse(L=>{L instanceof v.Mesh&&(L.material instanceof Me?L.material.setEnvMap(l):L.material instanceof Xe&&(L.material.uniforms.envMap.value=l))}),G()}catch(D){throw e.emit("error",D instanceof Error?D:new Error(String(D))),D}}t.metalEnvUrl&&h(t.metalEnvUrl).catch(()=>{}),t.gemEnvUrl&&g(t.gemEnvUrl).catch(()=>{});const x=c.domElement,b=()=>{nt.onContextRestored(c)};(Rn=x.addEventListener)==null||Rn.call(x,"webglcontextrestored",b);let A=null,S=[],P=[],E={},T={},R={},B=Se[0].hex,F=de[0].hex,_=null,V=null,U=null,ne=0,q=!1,$=!1;function G(){$=!0,ne===0&&!q&&typeof requestAnimationFrame<"u"&&(ne=requestAnimationFrame(X))}function X(){if(ne=0,q)return;const I=!!f.update(),D=f.autoRotate===!0;($||I||D)&&($=!1,c.render(o,r)),(I||D)&&ne===0&&!q&&typeof requestAnimationFrame<"u"&&(ne=requestAnimationFrame(X))}function se(){q=typeof document<"u"?document.hidden:!1,q||G()}typeof document<"u"&&document.addEventListener("visibilitychange",se);const ce=()=>{G()};(En=f.addEventListener)==null||En.call(f,"change",ce),G();const Cn=ls(c,o,r,f,e,()=>S,{hoverHighlight:t.hoverHighlight??!1});function oe(){if(typeof(Ee==null?void 0:Ee.__getCurrentModel)=="function"){const I=Ee.__getCurrentModel();if(I)return I}return A}function ye(I,D,L){const z=`${I.partId}:${D}`;if(R[z])return{color:R[z],isOverridden:!0};const N=`${I.meshId}:${D}`;return R[N]?{color:R[N],isOverridden:!0}:R[I.partId]?{color:R[I.partId],isOverridden:!0}:R[I.meshId]?{color:R[I.meshId],isOverridden:!0}:L!=null&&L.slotId&&T[L.slotId]?{color:T[L.slotId],isOverridden:!0}:L!=null&&L.materialName&&T[L.materialName]?{color:T[L.materialName],isOverridden:!0}:I.materialName&&T[I.materialName]?{color:T[I.materialName],isOverridden:!0}:{color:I.type==="metal"?B:F,isOverridden:!1}}function zt(I,D){if(Array.isArray(I.material))I.material=I.material.map(L=>{let z=0;if(D.traverse(N=>{N instanceof v.Mesh&&(Array.isArray(N.material)?N.material.includes(L):N.material===L)&&z++}),z>1&&typeof L.clone=="function"){const N=L.clone();return N.name=L.name,N}return L});else if(I.material){let L=0;if(D.traverse(z=>{z instanceof v.Mesh&&(Array.isArray(z.material)?z.material.includes(I.material):z.material===I.material)&&L++}),L>1&&typeof I.material.clone=="function"){const z=I.material.clone();z.name=I.material.name,I.material=z}}}function ve(I,D){const L=oe();if(L){let z=!1;if(Array.isArray(I.material))I.material.forEach((N,k)=>{const O=D.slots[k];ye(D,k,O).isOverridden&&(z=!0)});else{const N=D.slots[0];ye(D,0,N).isOverridden&&(z=!0)}z&&zt(I,L)}if(Array.isArray(I.material))I.material.forEach((z,N)=>{const k=D.slots[N],{color:O}=ye(D,N,k);D.type==="metal"?$e(I,O,N):We(I,O,N)});else{const z=D.slots[0],{color:N}=ye(D,0,z);D.type==="metal"?$e(I,N):We(I,N)}}async function kt(I,D={}){var N,k;U==null||U.abort(),U=new AbortController;const L=U;D.signal&&(D.signal.aborted?L.abort():D.signal.addEventListener("abort",()=>L.abort(),{once:!0}));const z=L.signal;(N=performance==null?void 0:performance.mark)==null||N.call(performance,"3d-viewer:load-start"),e.emit("loading",{progress:0});try{const O=D.dracoDecoderPath??t.dracoDecoderPath??gn,j=await pi(I,z,le=>{e.emit("loading",{progress:le*.8})},{dracoDecoderPath:O});if(z.aborted)return;e.emit("loading",{progress:.85});let me;if(j.scene)me=j.scene;else{const{loader:le,dispose:Fe}=di({dracoDecoderPath:O});try{me=(await new Promise((Ot,Wi)=>{le.parse(j.glb,"",Ot,Wi)})).scene,_t(me)}finally{Fe()}}if(z.aborted)return;e.emit("loading",{progress:.9}),A&&(o.remove(A),tn(A),A=null),A=me,o.add(A),S=zn(A,E),P=kn(S),A.traverse(le=>{if(!(le instanceof v.Mesh))return;const Fe=S.find(Ot=>Ot.meshId===le.uuid),Gt=(Fe==null?void 0:Fe.type)??"metal";ui(le,Gt,c,l,t.diamondMode??"reference"),Fe?ve(le,Fe):Gt==="metal"?$e(le,B):We(le,F)}),y!=="medium"&&Ut(y),fi(A,r,f,t),as(r,n.clientWidth,n.clientHeight);const Ce=new v.Box3().setFromObject(A),at=Ce.getBoundingSphere(new v.Sphere),ct=at.radius>0?at.radius:1;d.mesh.position.y=Ce.min.y,d.setScale(ct),e.emit("loading",{progress:1}),e.emit("loaded",{parts:S,materials:P}),_=null,V=null,(k=performance==null?void 0:performance.mark)==null||k.call(performance,"3d-viewer:load-end"),G()}catch(O){if(O.name==="AbortError"||z.aborted)return;e.emit("error",O instanceof Error?O:new Error(String(O)))}}function rt(I){var L,z;B=((L=vn.find(N=>N.id===I))==null?void 0:L.hex)??((z=Se.find(N=>N.id===I))==null?void 0:z.hex)??I,_=B;const D=oe();D&&(D.traverse(N=>{if(!(N instanceof v.Mesh))return;const k=S.find(O=>O.meshId===N.uuid);if(((k==null?void 0:k.type)??"metal")==="metal")if(k)if(Array.isArray(N.material))N.material.forEach((O,j)=>{const me=k.slots[j],{isOverridden:Ce}=ye(k,j,me);Ce||$e(N,B,j)});else{const O=k.slots[0],{isOverridden:j}=ye(k,0,O);j||$e(N,B)}else $e(N,B)}),e.emit("change",be()),G())}function st(I){var L,z;F=((L=bn.find(N=>N.id===I))==null?void 0:L.hex)??((z=de.find(N=>N.id===I))==null?void 0:z.hex)??I,V=F;const D=oe();D&&(D.traverse(N=>{if(!(N instanceof v.Mesh))return;const k=S.find(O=>O.meshId===N.uuid);if((k==null?void 0:k.type)==="stone")if(k)if(Array.isArray(N.material))N.material.forEach((O,j)=>{const me=k.slots[j],{isOverridden:Ce}=ye(k,j,me);Ce||We(N,F,j)});else{const O=k.slots[0],{isOverridden:j}=ye(k,0,O);j||We(N,F)}else We(N,F)}),e.emit("change",be()),G())}function Le(I,D){const L=S.find(k=>k.meshId===I||k.partId===I),z=L?L.partId:I;E[z]=D;const N=oe();N&&(S=zn(N,E),P=kn(S),N.traverse(k=>{if(!(k instanceof v.Mesh))return;const O=S.find(j=>j.meshId===k.uuid);!O||O.partId!==z&&O.meshId!==I||(ui(k,D,c,l,t.diamondMode??"reference"),ve(k,O))}),D==="stone"&&y!=="medium"&&Ut(y)),e.emit("change",be()),G()}function Bn(I,D){const L=P.filter(N=>N.slotId===I||N.name===I);if(L.length>0)for(const N of L)T[N.slotId]=D;T[I]=D;const z=oe();z&&z.traverse(N=>{if(!(N instanceof v.Mesh))return;const k=S.find(O=>O.meshId===N.uuid);k&&ve(N,k)}),e.emit("change",be()),G()}function Pn(I,D,L){const z=L!==void 0?`${I}:${L}`:I;R[z]=D;const N=oe();N&&N.traverse(k=>{if(!(k instanceof v.Mesh))return;const O=S.find(j=>j.meshId===k.uuid);O&&(O.partId===I||O.meshId===I)&&ve(k,O)}),e.emit("change",be()),G()}function Pi(I){delete T[I];for(const L of P)(L.slotId===I||L.name===I)&&(delete T[L.slotId],delete T[L.name]);const D=oe();D&&D.traverse(L=>{if(!(L instanceof v.Mesh))return;const z=S.find(N=>N.meshId===L.uuid);z&&ve(L,z)}),e.emit("change",be()),G()}function Ii(I,D){if(D!==void 0)delete R[`${I}:${D}`];else{delete R[I];for(const z of Object.keys(R))z.startsWith(`${I}:`)&&delete R[z]}const L=oe();L&&L.traverse(z=>{if(!(z instanceof v.Mesh))return;const N=S.find(k=>k.meshId===z.uuid);N&&(N.partId===I||N.meshId===I)&&ve(z,N)}),e.emit("change",be()),G()}function Ri(){T={},R={};const I=oe();I&&I.traverse(D=>{if(!(D instanceof v.Mesh))return;const L=S.find(z=>z.meshId===D.uuid);L&&ve(D,L)}),e.emit("change",be()),G()}function Ei(){return[...P]}function Fi(){return[...S]}function be(){return us(B,F,E,r,f,T,R)}function In(I){E={},T={},R={};const D=new Set(S.map(k=>k.partId)),L=new Set(P.map(k=>k.slotId)),z=new Set(P.map(k=>k.name)),N=fs(I,rt,st,Le,r,f,{setMaterialColor:Bn,setPartColor:Pn,availablePartIds:D,availableSlotIds:L,availableMaterialNames:z,currentColor:{metalColor:_??void 0,stoneColor:V??void 0}});return _=I.metalColor,V=I.stoneColor,G(),N}t.initialState&&(In(t.initialState),u.initialPosition.copy(r.position),u.initialTarget.copy(f.target));function _i(I,D){return e.on(I,D)}function Di(){var I,D;M!==null&&(clearTimeout(M),M=null),U==null||U.abort(),ne!==0&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(ne),ne=0),typeof document<"u"&&document.removeEventListener("visibilitychange",se),(I=f.removeEventListener)==null||I.call(f,"change",ce),(D=x.removeEventListener)==null||D.call(x,"webglcontextrestored",b),nt.clearCache(),d.dispose(),Cn.dispose(),u.dispose(),A&&(o.remove(A),tn(A),A=null),m==null||m.dispose(),p==null||p.dispose(),s(),a.dispose(),e.clear()}function Ni(I){return I!==void 0&&(f.autoRotateSpeed=I),f.autoRotate=!f.autoRotate,f.autoRotate&&G(),f.autoRotate}function Li(I){I!==void 0&&(f.autoRotateSpeed=I),f.autoRotate=!0,G()}function Vi(){f.autoRotate=!1}function zi(){return f.autoRotate}function ki(){u.resetCamera(),G()}function Ui(){A&&(fi(A,r,f,t),G())}function Gi(I,D){r.position.set(I[0],I[1],I[2]),f.target.set(D[0],D[1],D[2]),f.update(),G()}async function Oi(I){const D=(I==null?void 0:I.format)??"image/png",L=(I==null?void 0:I.quality)??.95;return c.render(o,r),c.domElement.toDataURL(D,L)}function Hi(I){a.setQuality(I)}function qi(I){d.setVisible(I),G()}function $i(){U==null||U.abort(),A&&(o.remove(A),tn(A),A=null),S=[],E={},P=[],T={},R={},_=null,V=null,d.mesh.position.y=0,d.setScale(1),G()}function Ut(I){const D=w(I);M!==null&&clearTimeout(M),M=setTimeout(()=>{if(M=null,y=D,!A)return;const{rayBounces:L,cubeResolution:z}=Tn(D);A.traverse(N=>{var ct;if(!(N instanceof v.Mesh))return;const k=S.find(le=>le.meshId===N.uuid);if((k==null?void 0:k.type)!=="stone")return;const O=N.material;if(!(O instanceof Me))return;const j=O.bakeHandle,me=nt.acquire(N.geometry,c,{resolution:z});if(!me)return;nt.release(j);const Ce=((ct=O.uniforms.envMap)==null?void 0:ct.value)??l,at=Ci(me,Ce,O.preset,{rayBounces:L,quality:D,orientEnvMap:O.defines.DIA_ORIENT_ENVMAP===1});Bi(O),N.material=at}),G()},300)}const Ee={load:kt,unload:$i,setMetalColor:rt,setStoneColor:st,setPartType:Le,setMaterialColor:Bn,setPartColor:Pn,clearMaterialColor:Pi,clearPartColor:Ii,clearOverrides:Ri,getMaterials:Ei,getParts:Fi,getState:be,setState:In,on:_i,dispose:Di,toggleRotation:Ni,startRotation:Li,stopRotation:Vi,isRotating:zi,resetCamera:ki,fitToScene:Ui,setCameraPosition:Gi,captureSnapshot:Oi,setQuality:Hi,setShadowsEnabled:qi,setMetalEnvironment:h,setGemEnvironment:g,setDiamondQuality:Ut,requestRender:G};return typeof window<"u"&&(Ee.__scene=o,Ee.__getCurrentModel=()=>A),Ee}const ps="1.0.0";exports.ALL_METAL_PRESETS=vn;exports.ALL_STONE_PRESETS=bn;exports.CANONICAL_METAL_PRESETS=Ro;exports.CANONICAL_STONE_PRESETS=Eo;exports.CorruptFileError=Ae;exports.DEFAULT_DRACO_DECODER_PATH=gn;exports.DIAMOND_PRESETS=Co;exports.GEMSTONE_PRESETS=Bo;exports.METAL_PRESETS=Se;exports.NetworkError=ot;exports.PHYSICALLY_BASED_METAL_PRESETS=To;exports.STONE_PRESETS=de;exports.UnsupportedFormatError=Ft;exports.VERSION=ps;exports.convert=pi;exports.createViewer=ms;exports.getMetalPreset=Fo;exports.getStonePreset=_o;exports.inferFormatFromUrl=mi;exports.loadDmatMaterial=ns;exports.loadDmatPreset=Ti;exports.loadHdrEnvironment=hn;exports.loadPmat=ts;exports.normalizeModelSource=bo;exports.resolveQualityTier=Tn;
848
848
  //# sourceMappingURL=index.cjs.map