filens-preview 0.3.1 → 0.3.2

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.
@@ -1 +1 @@
1
- var U=Object.defineProperty;var j=(e,t,n)=>t in e?U(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var d=(e,t,n)=>j(e,typeof t!="symbol"?t+"":t,n);import{c as G,b as R}from"./core-BLayEJn5.js";import{J as O}from"./vendor-CBCxJuSg.js";const _=[{extensions:["mm","opml","xmind","mmap"],family:"mindmap",driverId:"mindmap",targetFormat:"mindmap",contentTypes:["text/x-opml","application/x-freemind","application/x-xmind","application/vnd.xmind.workbook","application/x-mindmanager","application/vnd.mindjet.mindmanager"]}],D=new Set(["mm","opml","xmind","mmap"]),y="http://www.w3.org/2000/svg",b=34,J=110,I=260,W=90,H=20,E=36;class V{constructor(t,n={}){d(this,"listeners",{loading:new Set,rendered:new Set,error:new Set,statechange:new Set,warnings:new Set});d(this,"root");d(this,"scale");d(this,"fitMode");d(this,"canvasSize");d(this,"resizeObserver");d(this,"document",null);d(this,"loadGeneration",0);d(this,"loadController");d(this,"removeAbortListener");d(this,"selectedNodeId");d(this,"state");this.host=t,this.scale=n.initialScale??1,this.fitMode=n.fit??"contain",this.root=document.createElement("div"),this.root.className="mindmapv-preview",this.host.replaceChildren(this.root),this.state={loading:false,error:null,family:"mindmap",warnings:[],capabilities:{zoom:true,fit:true,pan:true,outline:true,search:true,fullscreen:true,metadata:true,download:true},scale:this.scale},typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{if(this.fitMode==="none")return;const r=this.scale;this.applyScale(),this.scale!==r&&this.emit("statechange",this.state)}))}async load(t,n){var a,c,f;const r=++this.loadGeneration;(a=this.loadController)==null||a.abort(),(c=this.removeAbortListener)==null||c.call(this),this.releaseDocument();const i=new AbortController;this.loadController=i;const o=n.signal,s=()=>{i.abort(),r===this.loadGeneration&&(this.releaseDocument(),this.state.loading=false,this.emit("statechange",this.state))};o==null||o.addEventListener("abort",s,{once:true}),this.removeAbortListener=()=>o==null?void 0:o.removeEventListener("abort",s),this.state={...this.state,loading:true,error:null,title:n.descriptor.name,warnings:[],selectedNodeId:void 0},this.emit("loading",this.state),this.emit("statechange",this.state);try{o!=null&&o.aborted&&i.abort(),l(i.signal);const p=$(((f=n.route)==null?void 0:f.sourceFormat)??n.descriptor.extension);if(!D.has(p))throw new Error(`Mind-map preview currently supports FreeMind MM, OPML, XMind, and MindManager MMAP files, got ${p||"unknown"}.`);const w={...n,signal:i.signal};let N;if(p==="xmind"||p==="mmap"){const x=await ft(t,w);l(i.signal),N=await(p==="xmind"?Y(x,w):Z(x,w))}else{const x=await ut(t,w);l(i.signal),N=q(x,p)}if(r!==this.loadGeneration)return;l(i.signal),this.document=N,this.selectedNodeId=this.document.root.id,this.state={...this.state,loading:false,error:null,title:this.document.title??n.descriptor.name,selectedNodeId:this.selectedNodeId,scale:this.scale},this.render(),R(this.root,{getScale:()=>this.state.scale,setScale:x=>this.setScale(x),signal:i.signal}),this.emit("rendered",this.state),this.emit("statechange",this.state)}catch(p){if(r!==this.loadGeneration)return;this.releaseDocument(),this.state.loading=false,l(i.signal);const w=p instanceof Error?p:new Error(String(p));throw this.state.error=w.message,this.emit("error",w),this.emit("statechange",this.state),w}}destroy(){var t,n;this.loadGeneration++,(t=this.loadController)==null||t.abort(),(n=this.removeAbortListener)==null||n.call(this),this.releaseDocument(),this.state.loading=false,this.root.parentElement===this.host&&this.host.replaceChildren();for(const r of Object.values(this.listeners))r.clear()}getState(){return{...this.state,warnings:[...this.state.warnings],selectedNodeId:this.selectedNodeId}}on(t,n){return this.listeners[t].add(n),()=>{this.listeners[t].delete(n)}}setScale(t){Number.isFinite(t)&&(this.scale=Math.max(.25,Math.min(t,3)),this.fitMode="none",this.state.scale=this.scale,this.applyScale(),this.emit("statechange",this.state))}fit(t="contain"){this.fitMode=t,t==="none"&&(this.scale=1),this.applyScale(),this.state.scale=this.scale,this.root.scrollLeft=0,this.root.scrollTop=0,this.emit("statechange",this.state)}pan(t,n){this.root.scrollLeft+=t,this.root.scrollTop+=n}async fullscreen(){var t,n;await((n=(t=this.root).requestFullscreen)==null?void 0:n.call(t))}render(){var s,a,c;if(!this.document){this.root.replaceChildren();return}const t=at(this.document.root),n=ct(t);this.canvasSize=n;const r=document.createElement("div");r.className="mindmapv-canvas-wrap",r.style.width=`${n.width}px`,r.style.height=`${n.height}px`;const i=document.createElementNS(y,"svg");i.classList.add("mindmapv-canvas"),i.setAttribute("viewBox",`0 0 ${n.width} ${n.height}`),i.setAttribute("role","img"),i.setAttribute("aria-label",this.document.title??"Mind map preview"),i.appendChild(lt(t)),i.appendChild(dt(t,this.selectedNodeId,f=>this.selectNode(f))),r.appendChild(i);const o=document.createElement("div");o.className="mindmapv-summary",o.textContent=`${this.document.nodeCount} node${this.document.nodeCount===1?"":"s"}`,(s=this.resizeObserver)==null||s.disconnect(),this.root.replaceChildren(o,r),this.applyScale(),(a=this.resizeObserver)==null||a.observe(this.root),(c=this.resizeObserver)==null||c.observe(o)}selectNode(t){if(!t){this.selectedNodeId=void 0,this.state.selectedNodeId=void 0,this.root.querySelectorAll(".mindmapv-node").forEach(n=>{n.classList.remove("is-selected")}),this.emit("statechange",this.state);return}this.selectedNodeId=t,this.state.selectedNodeId=t,this.root.querySelectorAll(".mindmapv-node").forEach(n=>{n.classList.toggle("is-selected",n.getAttribute("data-node-id")===t)}),this.emit("statechange",this.state)}applyScale(){const t=this.root.querySelector(".mindmapv-canvas-wrap");if(!(!t||!this.canvasSize)){if(this.fitMode!=="none"){const n=this.root.clientWidth,r=this.root.clientHeight-this.root.firstElementChild.offsetHeight;if(n>0&&r>0){const i=n/this.canvasSize.width,o=r/this.canvasSize.height;this.scale=this.fitMode==="width"?i:this.fitMode==="height"?o:Math.min(i,o)}}this.state.scale=this.scale,t.style.width=`${this.canvasSize.width*this.scale}px`,t.style.height=`${this.canvasSize.height*this.scale}px`}}releaseDocument(){var t;(t=this.resizeObserver)==null||t.disconnect(),this.canvasSize=void 0,this.document=null,this.selectedNodeId=void 0,this.state.selectedNodeId=void 0,this.root.replaceChildren()}emit(t,n){for(const r of this.listeners[t])r(n)}}function At(){return{id:"mindmap",family:"mindmap",supports:e=>D.has($(e)),createSession:(e,t)=>new V(e,t)}}function vt(e=G()){return[..._,...e.filter(t=>!t.extensions.some(n=>D.has(n)))]}function q(e,t){const n=new DOMParser().parseFromString(e,"application/xml");if(n.getElementsByTagName("parsererror")[0])throw new Error("Mind-map XML is invalid.");const i=$(t)==="opml"||m(n.documentElement)==="opml"?it(n):nt(n);return{title:i.text,root:i,nodeCount:A(i)}}async function Y(e,t={}){l(t.signal);const n=await O.loadAsync(e);l(t.signal);const r=n.file("content.json");if(r){const o=await r.async("text");return l(t.signal),rt(o)}const i=n.file("content.xml");if(i){const o=await i.async("text");return l(t.signal),st(o)}throw new Error("XMind package is missing content.json or content.xml.")}async function Z(e,t={}){l(t.signal);const n=await O.loadAsync(e);l(t.signal);const r=n.file("Document.xml")??n.file("document.xml")??n.file(/(^|\/)document\.xml$/i)[0];if(!r)throw new Error("MindManager package is missing Document.xml.");const i=await r.async("text");return l(t.signal),K(i)}function K(e){const t=new DOMParser().parseFromString(e,"application/xml");if(t.getElementsByTagName("parsererror")[0])throw new Error("MindManager Document.xml is invalid.");const n=Array.from(t.getElementsByTagName("*")).filter(o=>m(o)==="topic");if(!n.length)throw new Error("MindManager Document.xml does not contain topic nodes.");const r=n.find(o=>!Q(o))??n[0],i=B(r,"mmap-root");return{title:i.text,root:i,nodeCount:A(i)}}function Q(e){let t=e.parentElement;for(;t;){if(m(t)==="topic")return true;t=t.parentElement}return false}function B(e,t){var o;const n=L(e,"id")||t,r=v(L(e,"text")||((o=u(e,"text")[0])==null?void 0:o.textContent)||e.textContent||"Untitled"),i=tt(e).map((s,a)=>B(s,`${n}-${a+1}`));return{id:n,text:r,children:i}}function tt(e){const t=[],n=r=>{for(const i of Array.from(r.children)){if(m(i)==="topic"){t.push(i);continue}et(i)&&n(i)}};return n(e),t}function et(e){return Array.from(e.getElementsByTagName("*")).some(t=>m(t)==="topic")}function L(e,t){const n=t.toLowerCase();for(const r of Array.from(e.attributes))if(r.name.toLowerCase()===n)return r.value}function nt(e){const t=Array.from(e.getElementsByTagName("*")).find(n=>m(n)==="node");if(!t)throw new Error("FreeMind MM file does not contain a root node.");return z(t,"mm",t.parentElement?mt(t):"")}function z(e,t,n){const r=e.getAttribute("ID")||`${t}-${n||"1"}`,i=v(e.getAttribute("TEXT")||e.getAttribute("text")||"Untitled"),o=u(e,"node").map((s,a)=>z(s,`${r}-${a+1}`,n?`${n}-${a+1}`:String(a+1)));return{id:r,text:i,children:o}}function it(e){var i,o;const t=Array.from(e.getElementsByTagName("*")).find(s=>m(s)==="body"),n=(o=(i=Array.from(e.getElementsByTagName("*")).find(s=>m(s)==="title"))==null?void 0:i.textContent)==null?void 0:o.trim(),r=t?u(t,"outline"):[];if(!r.length)throw new Error("OPML file does not contain outline nodes.");if(r.length===1){const s=C(r[0],"opml-1");return n&&s.text==="Untitled"?{...s,text:n}:s}return{id:"opml-root",text:n||"OPML",children:r.map((s,a)=>C(s,`opml-${a+1}`))}}function C(e,t){const n=v(e.getAttribute("text")||e.getAttribute("title")||"Untitled");return{id:t,text:n,children:u(e,"outline").map((r,i)=>C(r,`${t}-${i+1}`))}}function rt(e){let t;try{t=JSON.parse(e)}catch{throw new Error("XMind content.json is invalid.")}const r=(Array.isArray(t)?t:[t]).find(s=>s&&typeof s=="object");if(!r)throw new Error("XMind content.json does not contain a sheet.");const i=h(r.rootTopic)??h(r.centralTopic)??h(r.topic);if(!i)throw new Error("XMind content.json does not contain a root topic.");const o=F(i,"xmind-json-1");return{title:g(r.title)||o.text,root:o,nodeCount:A(o)}}function F(e,t){const n=g(e.id)||g(e.uuid)||t,r=v(g(e.title)||g(e.text)||wt(e)||"Untitled"),i=ot(e).map((o,s)=>F(o,`${n}-${s+1}`));return{id:n,text:r,children:i}}function ot(e){var s;const t=[],n=e.children;Array.isArray(n)&&t.push(...n.map(h).filter(M));const r=h(n);if(r)for(const a of["attached","detached","floating","summary"]){const c=r[a],f=Array.isArray(c)?c:(s=h(c))==null?void 0:s.topics;Array.isArray(f)&&t.push(...f.map(h).filter(M))}const i=e.subTopics??e.subtopics;Array.isArray(i)&&t.push(...i.map(h).filter(M));const o=h(i);if(o)for(const a of Object.values(o))Array.isArray(a)&&t.push(...a.map(h).filter(M));return t}function st(e){var s,a;const t=new DOMParser().parseFromString(e,"application/xml");if(t.getElementsByTagName("parsererror")[0])throw new Error("XMind content.xml is invalid.");const n=Array.from(t.getElementsByTagName("*")).find(c=>m(c)==="sheet")??t.documentElement,r=u(n,"topic")[0]??Array.from(t.getElementsByTagName("*")).find(c=>m(c)==="topic");if(!r)throw new Error("XMind content.xml does not contain a root topic.");const i=X(r,"xmind-xml-1");return{title:((a=(s=u(n,"title")[0])==null?void 0:s.textContent)==null?void 0:a.trim())||i.text,root:i,nodeCount:A(i)}}function X(e,t){var o;const n=e.getAttribute("id")||t,r=((o=u(e,"title")[0])==null?void 0:o.textContent)??e.getAttribute("title")??e.getAttribute("text")??"Untitled",i=u(e,"children").flatMap(s=>u(s,"topics")).flatMap(s=>u(s,"topic")).map((s,a)=>X(s,`${n}-${a+1}`));return{id:n,text:v(r),children:i}}function at(e){const t=P(e,0);let n=E;const r=i=>{if(i.x=E+i.depth*(I+W),i.width=k(i.text),i.height=b,!i.children.length){i.y=n,n+=b+H;return}for(const o of i.children)r(o);i.y=(i.children[0].y+i.children[i.children.length-1].y)/2};return r(t),t}function P(e,t){return{...e,x:0,y:0,width:k(e.text),height:b,depth:t,children:e.children.map(n=>P(n,t+1))}}function ct(e){let t=0,n=0;return S(e,r=>{t=Math.max(t,r.x+r.width+E),n=Math.max(n,r.y+r.height+E)}),{width:Math.max(360,t),height:Math.max(260,n)}}function lt(e){const t=document.createElementNS(y,"g");return t.classList.add("mindmapv-links"),S(e,n=>{for(const r of n.children){const i=document.createElementNS(y,"path"),o=n.x+n.width,s=n.y+b/2,a=r.x,c=r.y+b/2,f=o+(a-o)*.5;i.setAttribute("d",`M ${o} ${s} C ${f} ${s}, ${f} ${c}, ${a} ${c}`),t.appendChild(i)}}),t}function dt(e,t,n){const r=document.createElementNS(y,"g");return r.classList.add("mindmapv-nodes"),S(e,i=>{const o=document.createElementNS(y,"g");o.classList.add("mindmapv-node"),i.id===t&&o.classList.add("is-selected"),o.setAttribute("data-node-id",i.id),o.setAttribute("tabindex","0"),o.setAttribute("role","button"),o.setAttribute("aria-label",i.text),o.addEventListener("click",()=>n(i.id)),o.addEventListener("keydown",c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),n(i.id))});const s=document.createElementNS(y,"rect");s.setAttribute("x",String(i.x)),s.setAttribute("y",String(i.y)),s.setAttribute("width",String(i.width)),s.setAttribute("height",String(b)),s.setAttribute("rx","6");const a=document.createElementNS(y,"text");a.setAttribute("x",String(i.x+14)),a.setAttribute("y",String(i.y+22)),a.textContent=ht(i.text),o.append(s,a),r.appendChild(o)}),r}function S(e,t){t(e);for(const n of e.children)S(n,t)}function k(e){return Math.max(J,Math.min(I,e.length*8+34))}function ht(e){return e.length>34?`${e.slice(0,31)}...`:e}function A(e){return 1+e.children.reduce((t,n)=>t+A(n),0)}function u(e,t){return Array.from(e.children).filter(n=>m(n)===t)}function m(e){return e.localName.toLowerCase()}function v(e){return e.replace(/\s+/g," ").trim()||"Untitled"}function mt(e){const t=[];let n=e;for(;n!=null&&n.parentElement;){const r=u(n.parentElement,m(n));t.unshift(r.indexOf(n)+1),n=n.parentElement}return t.join("-")||"1"}async function ut(e,t){if(l(t.signal),typeof e=="string"){if(e.trimStart().toLowerCase().startsWith("data:"))return pt(e);const n=await fetch(e,{signal:t.signal});if(l(t.signal),!n.ok)throw new Error(`Failed to load mind-map source: ${n.status} ${n.statusText}`.trim());return n.text()}return e instanceof Blob?e.text():ArrayBuffer.isView(e)?new TextDecoder().decode(e):e instanceof ArrayBuffer?new TextDecoder().decode(e):String(e)}async function ft(e,t){if(l(t.signal),typeof e=="string"){if(e.trimStart().toLowerCase().startsWith("data:"))return T(gt(e));const n=await fetch(e,{signal:t.signal});if(l(t.signal),!n.ok)throw new Error(`Failed to load mind-map source: ${n.status} ${n.statusText}`.trim());return n.arrayBuffer()}if(e instanceof Blob)return e.arrayBuffer();if(ArrayBuffer.isView(e)){const n=new Uint8Array(e.byteLength);return n.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),T(n)}return e instanceof ArrayBuffer?e:T(new TextEncoder().encode(String(e)))}function l(e){if(e!=null&&e.aborted)throw new DOMException("Mind-map preview aborted.","AbortError")}function pt(e){const t=e.indexOf(",");if(t<0)return e;const n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);return n.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(r),i=>i.charCodeAt(0))):decodeURIComponent(r)}function gt(e){const t=e.indexOf(",");if(t<0)return new TextEncoder().encode(e);const n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);return n.endsWith(";base64")?Uint8Array.from(atob(r),i=>i.charCodeAt(0)):new TextEncoder().encode(decodeURIComponent(r))}function T(e){const t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function $(e){return String(e??"").trim().replace(/^\./,"").toLowerCase()}function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function M(e){return e!==void 0}function g(e){return typeof e=="string"?e.trim():""}function wt(e){const t=h(e.title),n=h(e.text);return g(t==null?void 0:t.plain)||g(t==null?void 0:t.content)||g(n==null?void 0:n.plain)||g(n==null?void 0:n.content)}export{vt as a,At as c};
1
+ var U=Object.defineProperty;var j=(e,t,n)=>t in e?U(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var d=(e,t,n)=>j(e,typeof t!="symbol"?t+"":t,n);import{c as G,b as R}from"./core-EjELrtsP.js";import{J as O}from"./vendor-C1aIdQ-w.js";const _=[{extensions:["mm","opml","xmind","mmap"],family:"mindmap",driverId:"mindmap",targetFormat:"mindmap",contentTypes:["text/x-opml","application/x-freemind","application/x-xmind","application/vnd.xmind.workbook","application/x-mindmanager","application/vnd.mindjet.mindmanager"]}],D=new Set(["mm","opml","xmind","mmap"]),y="http://www.w3.org/2000/svg",b=34,J=110,I=260,W=90,H=20,E=36;class V{constructor(t,n={}){d(this,"listeners",{loading:new Set,rendered:new Set,error:new Set,statechange:new Set,warnings:new Set});d(this,"root");d(this,"scale");d(this,"fitMode");d(this,"canvasSize");d(this,"resizeObserver");d(this,"document",null);d(this,"loadGeneration",0);d(this,"loadController");d(this,"removeAbortListener");d(this,"selectedNodeId");d(this,"state");this.host=t,this.scale=n.initialScale??1,this.fitMode=n.fit??"contain",this.root=document.createElement("div"),this.root.className="mindmapv-preview",this.host.replaceChildren(this.root),this.state={loading:false,error:null,family:"mindmap",warnings:[],capabilities:{zoom:true,fit:true,pan:true,outline:true,search:true,fullscreen:true,metadata:true,download:true},scale:this.scale},typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{if(this.fitMode==="none")return;const r=this.scale;this.applyScale(),this.scale!==r&&this.emit("statechange",this.state)}))}async load(t,n){var a,c,f;const r=++this.loadGeneration;(a=this.loadController)==null||a.abort(),(c=this.removeAbortListener)==null||c.call(this),this.releaseDocument();const i=new AbortController;this.loadController=i;const o=n.signal,s=()=>{i.abort(),r===this.loadGeneration&&(this.releaseDocument(),this.state.loading=false,this.emit("statechange",this.state))};o==null||o.addEventListener("abort",s,{once:true}),this.removeAbortListener=()=>o==null?void 0:o.removeEventListener("abort",s),this.state={...this.state,loading:true,error:null,title:n.descriptor.name,warnings:[],selectedNodeId:void 0},this.emit("loading",this.state),this.emit("statechange",this.state);try{o!=null&&o.aborted&&i.abort(),l(i.signal);const p=$(((f=n.route)==null?void 0:f.sourceFormat)??n.descriptor.extension);if(!D.has(p))throw new Error(`Mind-map preview currently supports FreeMind MM, OPML, XMind, and MindManager MMAP files, got ${p||"unknown"}.`);const w={...n,signal:i.signal};let N;if(p==="xmind"||p==="mmap"){const x=await ft(t,w);l(i.signal),N=await(p==="xmind"?Y(x,w):Z(x,w))}else{const x=await ut(t,w);l(i.signal),N=q(x,p)}if(r!==this.loadGeneration)return;l(i.signal),this.document=N,this.selectedNodeId=this.document.root.id,this.state={...this.state,loading:false,error:null,title:this.document.title??n.descriptor.name,selectedNodeId:this.selectedNodeId,scale:this.scale},this.render(),R(this.root,{getScale:()=>this.state.scale,setScale:x=>this.setScale(x),signal:i.signal}),this.emit("rendered",this.state),this.emit("statechange",this.state)}catch(p){if(r!==this.loadGeneration)return;this.releaseDocument(),this.state.loading=false,l(i.signal);const w=p instanceof Error?p:new Error(String(p));throw this.state.error=w.message,this.emit("error",w),this.emit("statechange",this.state),w}}destroy(){var t,n;this.loadGeneration++,(t=this.loadController)==null||t.abort(),(n=this.removeAbortListener)==null||n.call(this),this.releaseDocument(),this.state.loading=false,this.root.parentElement===this.host&&this.host.replaceChildren();for(const r of Object.values(this.listeners))r.clear()}getState(){return{...this.state,warnings:[...this.state.warnings],selectedNodeId:this.selectedNodeId}}on(t,n){return this.listeners[t].add(n),()=>{this.listeners[t].delete(n)}}setScale(t){Number.isFinite(t)&&(this.scale=Math.max(.25,Math.min(t,3)),this.fitMode="none",this.state.scale=this.scale,this.applyScale(),this.emit("statechange",this.state))}fit(t="contain"){this.fitMode=t,t==="none"&&(this.scale=1),this.applyScale(),this.state.scale=this.scale,this.root.scrollLeft=0,this.root.scrollTop=0,this.emit("statechange",this.state)}pan(t,n){this.root.scrollLeft+=t,this.root.scrollTop+=n}async fullscreen(){var t,n;await((n=(t=this.root).requestFullscreen)==null?void 0:n.call(t))}render(){var s,a,c;if(!this.document){this.root.replaceChildren();return}const t=at(this.document.root),n=ct(t);this.canvasSize=n;const r=document.createElement("div");r.className="mindmapv-canvas-wrap",r.style.width=`${n.width}px`,r.style.height=`${n.height}px`;const i=document.createElementNS(y,"svg");i.classList.add("mindmapv-canvas"),i.setAttribute("viewBox",`0 0 ${n.width} ${n.height}`),i.setAttribute("role","img"),i.setAttribute("aria-label",this.document.title??"Mind map preview"),i.appendChild(lt(t)),i.appendChild(dt(t,this.selectedNodeId,f=>this.selectNode(f))),r.appendChild(i);const o=document.createElement("div");o.className="mindmapv-summary",o.textContent=`${this.document.nodeCount} node${this.document.nodeCount===1?"":"s"}`,(s=this.resizeObserver)==null||s.disconnect(),this.root.replaceChildren(o,r),this.applyScale(),(a=this.resizeObserver)==null||a.observe(this.root),(c=this.resizeObserver)==null||c.observe(o)}selectNode(t){if(!t){this.selectedNodeId=void 0,this.state.selectedNodeId=void 0,this.root.querySelectorAll(".mindmapv-node").forEach(n=>{n.classList.remove("is-selected")}),this.emit("statechange",this.state);return}this.selectedNodeId=t,this.state.selectedNodeId=t,this.root.querySelectorAll(".mindmapv-node").forEach(n=>{n.classList.toggle("is-selected",n.getAttribute("data-node-id")===t)}),this.emit("statechange",this.state)}applyScale(){const t=this.root.querySelector(".mindmapv-canvas-wrap");if(!(!t||!this.canvasSize)){if(this.fitMode!=="none"){const n=this.root.clientWidth,r=this.root.clientHeight-this.root.firstElementChild.offsetHeight;if(n>0&&r>0){const i=n/this.canvasSize.width,o=r/this.canvasSize.height;this.scale=this.fitMode==="width"?i:this.fitMode==="height"?o:Math.min(i,o)}}this.state.scale=this.scale,t.style.width=`${this.canvasSize.width*this.scale}px`,t.style.height=`${this.canvasSize.height*this.scale}px`}}releaseDocument(){var t;(t=this.resizeObserver)==null||t.disconnect(),this.canvasSize=void 0,this.document=null,this.selectedNodeId=void 0,this.state.selectedNodeId=void 0,this.root.replaceChildren()}emit(t,n){for(const r of this.listeners[t])r(n)}}function At(){return{id:"mindmap",family:"mindmap",supports:e=>D.has($(e)),createSession:(e,t)=>new V(e,t)}}function vt(e=G()){return[..._,...e.filter(t=>!t.extensions.some(n=>D.has(n)))]}function q(e,t){const n=new DOMParser().parseFromString(e,"application/xml");if(n.getElementsByTagName("parsererror")[0])throw new Error("Mind-map XML is invalid.");const i=$(t)==="opml"||m(n.documentElement)==="opml"?it(n):nt(n);return{title:i.text,root:i,nodeCount:A(i)}}async function Y(e,t={}){l(t.signal);const n=await O.loadAsync(e);l(t.signal);const r=n.file("content.json");if(r){const o=await r.async("text");return l(t.signal),rt(o)}const i=n.file("content.xml");if(i){const o=await i.async("text");return l(t.signal),st(o)}throw new Error("XMind package is missing content.json or content.xml.")}async function Z(e,t={}){l(t.signal);const n=await O.loadAsync(e);l(t.signal);const r=n.file("Document.xml")??n.file("document.xml")??n.file(/(^|\/)document\.xml$/i)[0];if(!r)throw new Error("MindManager package is missing Document.xml.");const i=await r.async("text");return l(t.signal),K(i)}function K(e){const t=new DOMParser().parseFromString(e,"application/xml");if(t.getElementsByTagName("parsererror")[0])throw new Error("MindManager Document.xml is invalid.");const n=Array.from(t.getElementsByTagName("*")).filter(o=>m(o)==="topic");if(!n.length)throw new Error("MindManager Document.xml does not contain topic nodes.");const r=n.find(o=>!Q(o))??n[0],i=B(r,"mmap-root");return{title:i.text,root:i,nodeCount:A(i)}}function Q(e){let t=e.parentElement;for(;t;){if(m(t)==="topic")return true;t=t.parentElement}return false}function B(e,t){var o;const n=L(e,"id")||t,r=v(L(e,"text")||((o=u(e,"text")[0])==null?void 0:o.textContent)||e.textContent||"Untitled"),i=tt(e).map((s,a)=>B(s,`${n}-${a+1}`));return{id:n,text:r,children:i}}function tt(e){const t=[],n=r=>{for(const i of Array.from(r.children)){if(m(i)==="topic"){t.push(i);continue}et(i)&&n(i)}};return n(e),t}function et(e){return Array.from(e.getElementsByTagName("*")).some(t=>m(t)==="topic")}function L(e,t){const n=t.toLowerCase();for(const r of Array.from(e.attributes))if(r.name.toLowerCase()===n)return r.value}function nt(e){const t=Array.from(e.getElementsByTagName("*")).find(n=>m(n)==="node");if(!t)throw new Error("FreeMind MM file does not contain a root node.");return z(t,"mm",t.parentElement?mt(t):"")}function z(e,t,n){const r=e.getAttribute("ID")||`${t}-${n||"1"}`,i=v(e.getAttribute("TEXT")||e.getAttribute("text")||"Untitled"),o=u(e,"node").map((s,a)=>z(s,`${r}-${a+1}`,n?`${n}-${a+1}`:String(a+1)));return{id:r,text:i,children:o}}function it(e){var i,o;const t=Array.from(e.getElementsByTagName("*")).find(s=>m(s)==="body"),n=(o=(i=Array.from(e.getElementsByTagName("*")).find(s=>m(s)==="title"))==null?void 0:i.textContent)==null?void 0:o.trim(),r=t?u(t,"outline"):[];if(!r.length)throw new Error("OPML file does not contain outline nodes.");if(r.length===1){const s=C(r[0],"opml-1");return n&&s.text==="Untitled"?{...s,text:n}:s}return{id:"opml-root",text:n||"OPML",children:r.map((s,a)=>C(s,`opml-${a+1}`))}}function C(e,t){const n=v(e.getAttribute("text")||e.getAttribute("title")||"Untitled");return{id:t,text:n,children:u(e,"outline").map((r,i)=>C(r,`${t}-${i+1}`))}}function rt(e){let t;try{t=JSON.parse(e)}catch{throw new Error("XMind content.json is invalid.")}const r=(Array.isArray(t)?t:[t]).find(s=>s&&typeof s=="object");if(!r)throw new Error("XMind content.json does not contain a sheet.");const i=h(r.rootTopic)??h(r.centralTopic)??h(r.topic);if(!i)throw new Error("XMind content.json does not contain a root topic.");const o=F(i,"xmind-json-1");return{title:g(r.title)||o.text,root:o,nodeCount:A(o)}}function F(e,t){const n=g(e.id)||g(e.uuid)||t,r=v(g(e.title)||g(e.text)||wt(e)||"Untitled"),i=ot(e).map((o,s)=>F(o,`${n}-${s+1}`));return{id:n,text:r,children:i}}function ot(e){var s;const t=[],n=e.children;Array.isArray(n)&&t.push(...n.map(h).filter(M));const r=h(n);if(r)for(const a of["attached","detached","floating","summary"]){const c=r[a],f=Array.isArray(c)?c:(s=h(c))==null?void 0:s.topics;Array.isArray(f)&&t.push(...f.map(h).filter(M))}const i=e.subTopics??e.subtopics;Array.isArray(i)&&t.push(...i.map(h).filter(M));const o=h(i);if(o)for(const a of Object.values(o))Array.isArray(a)&&t.push(...a.map(h).filter(M));return t}function st(e){var s,a;const t=new DOMParser().parseFromString(e,"application/xml");if(t.getElementsByTagName("parsererror")[0])throw new Error("XMind content.xml is invalid.");const n=Array.from(t.getElementsByTagName("*")).find(c=>m(c)==="sheet")??t.documentElement,r=u(n,"topic")[0]??Array.from(t.getElementsByTagName("*")).find(c=>m(c)==="topic");if(!r)throw new Error("XMind content.xml does not contain a root topic.");const i=X(r,"xmind-xml-1");return{title:((a=(s=u(n,"title")[0])==null?void 0:s.textContent)==null?void 0:a.trim())||i.text,root:i,nodeCount:A(i)}}function X(e,t){var o;const n=e.getAttribute("id")||t,r=((o=u(e,"title")[0])==null?void 0:o.textContent)??e.getAttribute("title")??e.getAttribute("text")??"Untitled",i=u(e,"children").flatMap(s=>u(s,"topics")).flatMap(s=>u(s,"topic")).map((s,a)=>X(s,`${n}-${a+1}`));return{id:n,text:v(r),children:i}}function at(e){const t=P(e,0);let n=E;const r=i=>{if(i.x=E+i.depth*(I+W),i.width=k(i.text),i.height=b,!i.children.length){i.y=n,n+=b+H;return}for(const o of i.children)r(o);i.y=(i.children[0].y+i.children[i.children.length-1].y)/2};return r(t),t}function P(e,t){return{...e,x:0,y:0,width:k(e.text),height:b,depth:t,children:e.children.map(n=>P(n,t+1))}}function ct(e){let t=0,n=0;return S(e,r=>{t=Math.max(t,r.x+r.width+E),n=Math.max(n,r.y+r.height+E)}),{width:Math.max(360,t),height:Math.max(260,n)}}function lt(e){const t=document.createElementNS(y,"g");return t.classList.add("mindmapv-links"),S(e,n=>{for(const r of n.children){const i=document.createElementNS(y,"path"),o=n.x+n.width,s=n.y+b/2,a=r.x,c=r.y+b/2,f=o+(a-o)*.5;i.setAttribute("d",`M ${o} ${s} C ${f} ${s}, ${f} ${c}, ${a} ${c}`),t.appendChild(i)}}),t}function dt(e,t,n){const r=document.createElementNS(y,"g");return r.classList.add("mindmapv-nodes"),S(e,i=>{const o=document.createElementNS(y,"g");o.classList.add("mindmapv-node"),i.id===t&&o.classList.add("is-selected"),o.setAttribute("data-node-id",i.id),o.setAttribute("tabindex","0"),o.setAttribute("role","button"),o.setAttribute("aria-label",i.text),o.addEventListener("click",()=>n(i.id)),o.addEventListener("keydown",c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),n(i.id))});const s=document.createElementNS(y,"rect");s.setAttribute("x",String(i.x)),s.setAttribute("y",String(i.y)),s.setAttribute("width",String(i.width)),s.setAttribute("height",String(b)),s.setAttribute("rx","6");const a=document.createElementNS(y,"text");a.setAttribute("x",String(i.x+14)),a.setAttribute("y",String(i.y+22)),a.textContent=ht(i.text),o.append(s,a),r.appendChild(o)}),r}function S(e,t){t(e);for(const n of e.children)S(n,t)}function k(e){return Math.max(J,Math.min(I,e.length*8+34))}function ht(e){return e.length>34?`${e.slice(0,31)}...`:e}function A(e){return 1+e.children.reduce((t,n)=>t+A(n),0)}function u(e,t){return Array.from(e.children).filter(n=>m(n)===t)}function m(e){return e.localName.toLowerCase()}function v(e){return e.replace(/\s+/g," ").trim()||"Untitled"}function mt(e){const t=[];let n=e;for(;n!=null&&n.parentElement;){const r=u(n.parentElement,m(n));t.unshift(r.indexOf(n)+1),n=n.parentElement}return t.join("-")||"1"}async function ut(e,t){if(l(t.signal),typeof e=="string"){if(e.trimStart().toLowerCase().startsWith("data:"))return pt(e);const n=await fetch(e,{signal:t.signal});if(l(t.signal),!n.ok)throw new Error(`Failed to load mind-map source: ${n.status} ${n.statusText}`.trim());return n.text()}return e instanceof Blob?e.text():ArrayBuffer.isView(e)?new TextDecoder().decode(e):e instanceof ArrayBuffer?new TextDecoder().decode(e):String(e)}async function ft(e,t){if(l(t.signal),typeof e=="string"){if(e.trimStart().toLowerCase().startsWith("data:"))return T(gt(e));const n=await fetch(e,{signal:t.signal});if(l(t.signal),!n.ok)throw new Error(`Failed to load mind-map source: ${n.status} ${n.statusText}`.trim());return n.arrayBuffer()}if(e instanceof Blob)return e.arrayBuffer();if(ArrayBuffer.isView(e)){const n=new Uint8Array(e.byteLength);return n.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),T(n)}return e instanceof ArrayBuffer?e:T(new TextEncoder().encode(String(e)))}function l(e){if(e!=null&&e.aborted)throw new DOMException("Mind-map preview aborted.","AbortError")}function pt(e){const t=e.indexOf(",");if(t<0)return e;const n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);return n.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(r),i=>i.charCodeAt(0))):decodeURIComponent(r)}function gt(e){const t=e.indexOf(",");if(t<0)return new TextEncoder().encode(e);const n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);return n.endsWith(";base64")?Uint8Array.from(atob(r),i=>i.charCodeAt(0)):new TextEncoder().encode(decodeURIComponent(r))}function T(e){const t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function $(e){return String(e??"").trim().replace(/^\./,"").toLowerCase()}function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function M(e){return e!==void 0}function g(e){return typeof e=="string"?e.trim():""}function wt(e){const t=h(e.title),n=h(e.text);return g(t==null?void 0:t.plain)||g(t==null?void 0:t.content)||g(n==null?void 0:n.plain)||g(n==null?void 0:n.content)}export{vt as a,At as c};
@@ -0,0 +1,55 @@
1
+ var Gn=Object.defineProperty;var Un=(n,e,t)=>e in n?Gn(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var M=(n,e,t)=>Un(n,typeof e!="symbol"?e+"":e,t);import{c as _n,o as Vn}from"./core-EjELrtsP.js";import{L as Ne,M as V,b as ne,F as nt,S as $n,C as de,V as E,d as ee,e as en,R as tn,B as Y,g as ie,h as Q,j as $,k as Wn,l as lt,P as we,m as xt,E as Mt,A as St,D as Oe,n as te,o as Ve,O as Kn,p as Z,q as _e,r as Pe,t as me,v as Yn,w as $e,x as Te,y as Ee,z as Ct,H as fe,I as Xn,K as Zn,N as nn,Q as qn,T as Jn,W as Qn,X as es,Y as ts,Z as ns,_ as ss,$ as rs,a0 as is,a1 as as,a2 as os,a3 as ls,a4 as cs,a5 as us,a6 as ds,a7 as hs,a8 as ms,J as fs,a9 as ps,aa as gs,ab as ws}from"./vendor-C1aIdQ-w.js";import{c as bs}from"./panorama-ChsqnvWC.js";const Pt=0,Lt=1,Et=2,Ft=3,At=4,Dt=5,We=0,ys=1,vs=2,xs=3,Ms=4,Ss=5,Nt=6,ae="16",ve="24",ke=$n,He=new E,je=new E;class Cs extends Q{constructor(e,t){super(e,t),this.isConditionalLine=true}}function Ps(n){for(let e=0,t=n.length;e<t;e++){const s=n[e],r=s.vertices,i=r[0],a=r[1],o=r[2];He.subVectors(a,i),je.subVectors(o,a),s.faceNormal=new E().crossVectors(He,je).normalize()}}const Ot=new tn;function Ls(n,e,t=false){const s=100.00000001000001;function r(f){const m=~~(f.x*s),g=~~(f.y*s),w=~~(f.z*s);return`${m},${g},${w}`}function i(f,m){return`${r(f)}_${r(m)}`}function a(f,m,g){g.direction.subVectors(m,f).normalize();const w=f.dot(g.direction);return g.origin.copy(f).addScaledVector(g.direction,-w),g}function o(f){return i(f.origin,f.direction)}const u=new Set,l=new Map,c=new Map,d=[];for(let f=0,m=e.length;f<m;f++){const w=e[f].vertices,p=w[0],b=w[1];if(u.add(i(p,b)),u.add(i(b,p)),t){const y=a(p,b,new tn),C=o(y);if(!l.has(C)){a(b,p,y);const k=o(y),D={ray:y,distances:[]};l.set(C,D),l.set(k,D)}const P=l.get(C);let S=P.ray.direction.dot(p),L=P.ray.direction.dot(b);S>L&&([S,L]=[L,S]),P.distances.push(S,L)}}for(let f=0,m=n.length;f<m;f++){const g=n[f],w=g.vertices,p=w.length;for(let b=0;b<p;b++){const y=b,C=(b+1)%p,P=w[y],S=w[C],L=i(P,S);if(u.has(L))continue;if(t){a(P,S,Ot);const D=o(Ot);if(l.has(D)){const N=l.get(D),{ray:v,distances:O}=N;let A=v.direction.dot(P),x=v.direction.dot(S);A>x&&([A,x]=[x,A]);let z=false;for(let H=0,U=O.length;H<U;H+=2)if(A>=O[H]&&x<=O[H+1]){z=true;break}if(z)continue}}const k={index:y,tri:g};c.set(L,k)}}const h=c.values();for(;;){const f=h.next().value;if(f===void 0)break;const m=[f];for(;m.length>0;){const g=m.pop().tri,w=g.vertices,p=g.normals,b=g.faceNormal,y=w.length;for(let C=0;C<y;C++){const P=C,S=(C+1)%y,L=w[P],k=w[S],D=i(L,k);c.delete(D);const N=i(k,L),v=c.get(N);if(v){const O=v.tri,A=v.index,x=O.normals,z=x.length,H=O.faceNormal;if(Math.abs(O.faceNormal.dot(g.faceNormal))<.25)continue;c.has(N)&&(m.push(v),c.delete(N));const U=(A+1)%z;p[P]&&x[U]&&p[P]!==x[U]&&(x[U].norm.add(p[P].norm),p[P].norm=x[U].norm);let I=p[P]||x[U];I===null&&(I={norm:new E},d.push(I.norm)),p[P]===null&&(p[P]=I,I.norm.add(b)),x[U]===null&&(x[U]=I,I.norm.add(H)),p[S]&&x[A]&&p[S]!==x[A]&&(x[A].norm.add(p[S].norm),p[S].norm=x[A].norm);let B=p[S]||x[A];B===null&&(B={norm:new E},d.push(B.norm)),p[S]===null&&(p[S]=B,B.norm.add(b)),x[A]===null&&(x[A]=B,B.norm.add(H))}}}}for(let f=0,m=d.length;f<m;f++)d[f].normalize()}function kt(n){return n==="Part"||n==="Unofficial_Part"}function Es(n){return/primitive/i.test(n)||n==="Subpart"}class Se{constructor(e,t){this.line=e,this.lineLength=e.length,this.currentCharIndex=0,this.currentChar=" ",this.lineNumber=t}seekNonSpace(){for(;this.currentCharIndex<this.lineLength;){if(this.currentChar=this.line.charAt(this.currentCharIndex),this.currentChar!==" "&&this.currentChar!==" ")return;this.currentCharIndex++}}getToken(){const e=this.currentCharIndex++;for(;this.currentCharIndex<this.lineLength&&(this.currentChar=this.line.charAt(this.currentCharIndex),!(this.currentChar===" "||this.currentChar===" "));)this.currentCharIndex++;const t=this.currentCharIndex;return this.seekNonSpace(),this.line.substring(e,t)}getVector(){return new E(parseFloat(this.getToken()),parseFloat(this.getToken()),parseFloat(this.getToken()))}getRemainingString(){return this.line.substring(this.currentCharIndex,this.lineLength)}isAtTheEnd(){return this.currentCharIndex>=this.lineLength}setToEnd(){this.currentCharIndex=this.lineLength}getLineNumberString(){return this.lineNumber>=0?" at line "+this.lineNumber:""}}class Fs{constructor(e){this.loader=e,this._cache={}}cloneResult(e){const t={};return t.faces=e.faces.map(s=>({colorCode:s.colorCode,material:s.material,vertices:s.vertices.map(r=>r.clone()),normals:s.normals.map(()=>null),faceNormal:null})),t.conditionalSegments=e.conditionalSegments.map(s=>({colorCode:s.colorCode,material:s.material,vertices:s.vertices.map(r=>r.clone()),controlPoints:s.controlPoints.map(r=>r.clone())})),t.lineSegments=e.lineSegments.map(s=>({colorCode:s.colorCode,material:s.material,vertices:s.vertices.map(r=>r.clone())})),t.type=e.type,t.category=e.category,t.keywords=e.keywords,t.author=e.author,t.subobjects=e.subobjects,t.fileName=e.fileName,t.totalFaces=e.totalFaces,t.startingBuildingStep=e.startingBuildingStep,t.materials=e.materials,t.group=null,t}async fetchData(e){let t=false,s=We;for(;s!==Nt;){let r=e;switch(s){case xs:s=s+1;break;case We:r="parts/"+r,s=s+1;break;case ys:r="p/"+r,s=s+1;break;case vs:r="models/"+r,s=s+1;break;case Ms:r=e.substring(0,e.lastIndexOf("/")+1)+r,s=s+1;break;case Ss:t?s=Nt:(e=e.toLowerCase(),r=e,t=true,s=We);break}const i=this.loader,a=new nt(i.manager);a.setPath(i.partsLibraryPath),a.setRequestHeader(i.requestHeader),a.setWithCredentials(i.withCredentials);try{return await a.loadAsync(r)}catch{continue}}throw new Error('LDrawLoader: Subobject "'+e+'" could not be loaded.')}parse(e,t=null){const s=this.loader,r=[],i=[],a=[],o=[],u={},l=D=>u[D]||null;let c="Model",d=null,h=null,f=null,m=0;e.indexOf(`\r
2
+ `)!==-1&&(e=e.replace(/\r\n/g,`
3
+ `));const g=e.split(`
4
+ `),w=g.length;let p=false,b=null,y=null,C=false,P=true,S=false,L=true,k=false;for(let D=0;D<w;D++){const N=g[D];if(N.length===0)continue;if(p){N.startsWith("0 FILE ")?(this.setData(b,y),b=N.substring(7),y=""):y+=N+`
5
+ `;continue}const v=new Se(N,D+1);if(v.seekNonSpace(),v.isAtTheEnd())continue;const O=v.getToken();let A,x,z,H,U,I,B,re,De,wt,bt;switch(O){case"0":const yt=v.getToken();if(yt)switch(yt){case"!LDRAW_ORG":c=v.getToken();break;case"!COLOUR":A=s.parseColorMetaDirective(v),A?u[A.userData.code]=A:console.warn("LDrawLoader: Error parsing material"+v.getLineNumberString());break;case"!CATEGORY":d=v.getToken();break;case"!KEYWORDS":const vt=v.getRemainingString().split(",");vt.length>0&&(h||(h=[]),vt.forEach(function(ce){h.push(ce.trim())}));break;case"FILE":D>0&&(p=true,b=v.getRemainingString(),y="",C=false,P=true);break;case"BFC":for(;!v.isAtTheEnd();){const ce=v.getToken();switch(ce){case"CERTIFY":case"NOCERTIFY":C=ce==="CERTIFY",P=true;break;case"CW":case"CCW":P=ce==="CCW";break;case"INVERTNEXT":S=true;break;case"CLIP":case"NOCLIP":L=ce==="CLIP";break;default:console.warn('THREE.LDrawLoader: BFC directive "'+ce+'" is unknown.');break}}break;case"STEP":k=true;break;case"Author:":f=v.getToken();break}break;case"1":x=v.getToken(),A=l(x);const Fn=parseFloat(v.getToken()),An=parseFloat(v.getToken()),Dn=parseFloat(v.getToken()),Nn=parseFloat(v.getToken()),On=parseFloat(v.getToken()),kn=parseFloat(v.getToken()),Rn=parseFloat(v.getToken()),Tn=parseFloat(v.getToken()),In=parseFloat(v.getToken()),Bn=parseFloat(v.getToken()),zn=parseFloat(v.getToken()),Hn=parseFloat(v.getToken()),jn=new en().set(Nn,On,kn,Fn,Rn,Tn,In,An,Bn,zn,Hn,Dn,0,0,0,1);let J=v.getRemainingString().trim().replace(/\\/g,"/");s.fileMap[J]?J=s.fileMap[J]:J.startsWith("s/")?J="parts/"+J:J.startsWith("48/")&&(J="p/"+J),o.push({material:A,colorCode:x,matrix:jn,fileName:J,inverted:S,startingBuildingStep:k}),k=false,S=false;break;case"2":x=v.getToken(),A=l(x),I=v.getVector(),B=v.getVector(),z={material:A,colorCode:x,vertices:[I,B]},i.push(z);break;case"5":x=v.getToken(),A=l(x),I=v.getVector(),B=v.getVector(),wt=v.getVector(),bt=v.getVector(),z={material:A,colorCode:x,vertices:[I,B],controlPoints:[wt,bt]},a.push(z);break;case"3":x=v.getToken(),A=l(x),H=P,U=!C||!L,H===true?(I=v.getVector(),B=v.getVector(),re=v.getVector()):(re=v.getVector(),B=v.getVector(),I=v.getVector()),r.push({material:A,colorCode:x,faceNormal:null,vertices:[I,B,re],normals:[null,null,null]}),m++,U===true&&(r.push({material:A,colorCode:x,faceNormal:null,vertices:[re,B,I],normals:[null,null,null]}),m++);break;case"4":x=v.getToken(),A=l(x),H=P,U=!C||!L,H===true?(I=v.getVector(),B=v.getVector(),re=v.getVector(),De=v.getVector()):(De=v.getVector(),re=v.getVector(),B=v.getVector(),I=v.getVector()),r.push({material:A,colorCode:x,faceNormal:null,vertices:[I,B,re,De],normals:[null,null,null,null]}),m+=2,U===true&&(r.push({material:A,colorCode:x,faceNormal:null,vertices:[De,re,B,I],normals:[null,null,null,null]}),m+=2);break;default:throw new Error('LDrawLoader: Unknown line type "'+O+'"'+v.getLineNumberString()+".")}}return p&&this.setData(b,y),{faces:r,conditionalSegments:a,lineSegments:i,type:c,category:d,keywords:h,author:f,subobjects:o,totalFaces:m,startingBuildingStep:k,materials:u,fileName:t,group:null}}getData(e,t=true){const s=e.toLowerCase(),r=this._cache[s];return r===null||r instanceof Promise?null:t?this.cloneResult(r):r}async ensureDataLoaded(e){const t=e.toLowerCase();t in this._cache||(this._cache[t]=this.fetchData(e).then(s=>{const r=this.parse(s,e);return this._cache[t]=r,r})),await this._cache[t]}setData(e,t){const s=e.toLowerCase();this._cache[s]=this.parse(t,e)}}function Ke(n,e,t,s){return(!s&&n===ae||s&&n===ve)&&(n=e),t[n]||null}class As{constructor(e){this.loader=e,this.parseCache=new Fs(e),this._cache={}}async processIntoMesh(e){const t=this.loader,s=this.parseCache,r=new Set,i=async(o,u=null)=>{const l=o.subobjects,c=[];for(let f=0,m=l.length;f<m;f++){const g=l[f],w=s.ensureDataLoaded(g.fileName).then(()=>{const p=s.getData(g.fileName,false);return Es(p.type)?i(s.getData(g.fileName),g):this.loadModel(g.fileName).catch(b=>(console.warn(b),null))});c.push(w)}const d=new ee;d.userData.category=o.category,d.userData.keywords=o.keywords,d.userData.author=o.author,d.userData.type=o.type,d.userData.fileName=o.fileName,o.group=d;const h=await Promise.all(c);for(let f=0,m=h.length;f<m;f++){const g=o.subobjects[f],w=h[f];if(w===null)continue;if(w.isGroup){const O=w;g.matrix.decompose(O.position,O.quaternion,O.scale),O.userData.startingBuildingStep=g.startingBuildingStep,O.name=g.fileName,t.applyMaterialsToMesh(O,g.colorCode,o.materials),O.userData.colorCode=g.colorCode,d.add(O);continue}w.group.children.length&&d.add(w.group);const p=o.lineSegments,b=o.conditionalSegments,y=o.faces,C=w.lineSegments,P=w.conditionalSegments,S=w.faces,L=g.matrix,k=g.inverted,D=L.determinant()<0,N=g.colorCode,v=N===ae?ve:N;for(let O=0,A=C.length;O<A;O++){const x=C[O],z=x.vertices;z[0].applyMatrix4(L),z[1].applyMatrix4(L),x.colorCode=x.colorCode===ve?v:x.colorCode,x.material=x.material||Ke(x.colorCode,x.colorCode,o.materials,true),p.push(x)}for(let O=0,A=P.length;O<A;O++){const x=P[O],z=x.vertices,H=x.controlPoints;z[0].applyMatrix4(L),z[1].applyMatrix4(L),H[0].applyMatrix4(L),H[1].applyMatrix4(L),x.colorCode=x.colorCode===ve?v:x.colorCode,x.material=x.material||Ke(x.colorCode,x.colorCode,o.materials,true),b.push(x)}for(let O=0,A=S.length;O<A;O++){const x=S[O],z=x.vertices;for(let H=0,U=z.length;H<U;H++)z[H].applyMatrix4(L);x.colorCode=x.colorCode===ae?N:x.colorCode,x.material=x.material||Ke(x.colorCode,N,o.materials,false),r.add(x.colorCode),D!==k&&z.reverse(),y.push(x)}o.totalFaces+=w.totalFaces}return u&&(t.applyMaterialsToMesh(d,u.colorCode,o.materials),d.userData.colorCode=u.colorCode),o};for(let o=0,u=e.faces;o<u;o++)r.add(e.faces[o].colorCode);if(await i(e),t.smoothNormals){const o=r.size>1;Ps(e.faces),Ls(e.faces,e.lineSegments,o)}const a=e.group;return e.faces.length>0&&a.add(Ye(this.loader,e.faces,3,false,e.totalFaces)),e.lineSegments.length>0&&a.add(Ye(this.loader,e.lineSegments,2)),e.conditionalSegments.length>0&&a.add(Ye(this.loader,e.conditionalSegments,2,true)),a}hasCachedModel(e){return e!==null&&e.toLowerCase()in this._cache}async getCachedModel(e){if(e!==null&&this.hasCachedModel(e)){const t=e.toLowerCase();return(await this._cache[t]).clone()}else return null}async loadModel(e){const t=this.parseCache,s=e.toLowerCase();if(this.hasCachedModel(e))return this.getCachedModel(e);{await t.ensureDataLoaded(e);const r=t.getData(e),i=this.processIntoMesh(r);return this.hasCachedModel(e)?this.getCachedModel(e):(kt(r.type)&&(this._cache[s]=i),(await i).clone())}}async parseModel(e){const s=this.parseCache.parse(e);return kt(s.type)&&this.hasCachedModel(s.fileName)?this.getCachedModel(s.fileName):this.processIntoMesh(s)}}function Ds(n,e){return n.colorCode===e.colorCode?0:n.colorCode<e.colorCode?-1:1}function Ye(n,e,t,s=false,r=null){e.sort(Ds),r===null&&(r=e.length);const i=new Float32Array(t*r*3),a=t===3?new Float32Array(t*r*3):null,o=[],u=new Array(6),l=new Y;let c=null,d=0,h=0,f=0;for(let g=0,w=e.length;g<w;g++){const p=e[g];let b=p.vertices;b.length===4&&(u[0]=b[0],u[1]=b[1],u[2]=b[2],u[3]=b[0],u[4]=b[2],u[5]=b[3],b=u);for(let y=0,C=b.length;y<C;y++){const P=b[y],S=f+y*3;i[S+0]=P.x,i[S+1]=P.y,i[S+2]=P.z}if(t===3){if(!p.faceNormal){const C=b[0],P=b[1],S=b[2];He.subVectors(P,C),je.subVectors(S,P),p.faceNormal=new E().crossVectors(He,je).normalize()}let y=p.normals;y.length===4&&(u[0]=y[0],u[1]=y[1],u[2]=y[2],u[3]=y[0],u[4]=y[2],u[5]=y[3],y=u);for(let C=0,P=y.length;C<P;C++){let S=p.faceNormal;y[C]&&(S=y[C].norm);const L=f+C*3;a[L+0]=S.x,a[L+1]=S.y,a[L+2]=S.z}}if(c!==p.colorCode){c!==null&&l.addGroup(d,h,o.length-1);const y=p.material;if(y!==null){if(t===3)o.push(y);else if(t===2)if(s){const C=n.edgeMaterialCache.get(y);o.push(n.conditionalEdgeMaterialCache.get(C))}else o.push(n.edgeMaterialCache.get(y))}else o.push(p.colorCode);c=p.colorCode,d=f/3,h=b.length}else h+=b.length;f+=3*b.length}h>0&&l.addGroup(d,1/0,o.length-1),l.setAttribute("position",new ie(i,3)),a!==null&&l.setAttribute("normal",new ie(a,3));let m=null;if(t===2?s?m=new Cs(l,o.length===1?o[0]:o):m=new Q(l,o.length===1?o[0]:o):t===3&&(m=new $(l,o.length===1?o[0]:o)),s){m.isConditionalLine=true;const g=new Float32Array(e.length*3*2),w=new Float32Array(e.length*3*2),p=new Float32Array(e.length*3*2);for(let b=0,y=e.length;b<y;b++){const C=e[b],P=C.vertices,S=C.controlPoints,L=S[0],k=S[1],D=P[0],N=P[1],v=b*3*2;g[v+0]=L.x,g[v+1]=L.y,g[v+2]=L.z,g[v+3]=L.x,g[v+4]=L.y,g[v+5]=L.z,w[v+0]=k.x,w[v+1]=k.y,w[v+2]=k.z,w[v+3]=k.x,w[v+4]=k.y,w[v+5]=k.z,p[v+0]=N.x-D.x,p[v+1]=N.y-D.y,p[v+2]=N.z-D.z,p[v+3]=N.x-D.x,p[v+4]=N.y-D.y,p[v+5]=N.z-D.z}l.setAttribute("control0",new ie(g,3,false)),l.setAttribute("control1",new ie(w,3,false)),l.setAttribute("direction",new ie(p,3,false))}return m}class Ns extends Ne{constructor(e){super(e),this.materials=[],this.materialLibrary={},this.edgeMaterialCache=new WeakMap,this.conditionalEdgeMaterialCache=new WeakMap,this.partsCache=new As(this),this.fileMap={},this.smoothNormals=true,this.partsLibraryPath="",this.ConditionalLineMaterial=null,this.missingColorMaterial=new V({name:Ne.DEFAULT_MATERIAL_NAME,color:16711935,roughness:.3,metalness:0}),this.missingEdgeColorMaterial=new ne({name:Ne.DEFAULT_MATERIAL_NAME,color:16711935}),this.missingConditionalEdgeColorMaterial=null,this.edgeMaterialCache.set(this.missingColorMaterial,this.missingEdgeColorMaterial),this.conditionalEdgeMaterialCache.set(this.missingEdgeColorMaterial,this.missingConditionalEdgeColorMaterial)}setPartsLibraryPath(e){return this.partsLibraryPath=e,this}setConditionalLineMaterial(e){return this.ConditionalLineMaterial=e,this.missingConditionalEdgeColorMaterial=new this.ConditionalLineMaterial({name:Ne.DEFAULT_MATERIAL_NAME,fog:true,color:16711935}),this}async preloadMaterials(e){const t=new nt(this.manager);t.setPath(this.path),t.setRequestHeader(this.requestHeader),t.setWithCredentials(this.withCredentials);const s=await t.loadAsync(e),r=/^0 !COLOUR/,i=s.split(/[\n\r]/g),a=[];for(let o=0,u=i.length;o<u;o++){const l=i[o];if(r.test(l)){const c=l.replace(r,""),d=this.parseColorMetaDirective(new Se(c));a.push(d)}}this.setMaterials(a)}load(e,t,s,r){const i=new nt(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,a=>{this.setMaterials([]),this.partsCache.parseModel(a).then(o=>{this.applyMaterialsToMesh(o,ae,this.materialLibrary,true),this.computeBuildingSteps(o),o.userData.fileName=e,t(o)}).catch(r)},s,r)}parse(e,t,s){this.partsCache.parseModel(e).then(r=>{this.applyMaterialsToMesh(r,ae,this.materialLibrary,true),this.computeBuildingSteps(r),r.userData.fileName="",t(r)}).catch(s)}setMaterials(e){this.materialLibrary={},this.materials=[];for(let t=0,s=e.length;t<s;t++)this.addMaterial(e[t]);return this.addMaterial(this.parseColorMetaDirective(new Se("Main_Colour CODE 16 VALUE #FF8080 EDGE #333333"))),this.addMaterial(this.parseColorMetaDirective(new Se("Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333"))),this}setFileMap(e){return this.fileMap=e,this}addMaterial(e){const t=this.materialLibrary;return t[e.userData.code]||(this.materials.push(e),t[e.userData.code]=e),this}getMaterial(e){if(e.startsWith("0x2")){const t=e.substring(3);return this.parseColorMetaDirective(new Se("Direct_Color_"+t+" CODE -1 VALUE #"+t+" EDGE #"+t))}return this.materialLibrary[e]||null}applyMaterialsToMesh(e,t,s,r=false){const i=this,a=t===ae;e.traverse(u=>{if(u.isMesh||u.isLineSegments)if(Array.isArray(u.material))for(let l=0,c=u.material.length;l<c;l++)u.material[l].isMaterial||(u.material[l]=o(u,u.material[l]));else u.material.isMaterial||(u.material=o(u,u.material))});function o(u,l){if(a&&!(l in s)&&!r)return l;const c=u.isLineSegments||u.isConditionalLine;(!c&&l===ae||c&&l===ve)&&(l=t);let h=null;if(l in s)h=s[l];else if(r)h=i.getMaterial(l),h===null&&(console.warn(`LDrawLoader: Material properties for code ${l} not available.`),h=i.missingColorMaterial);else return l;return u.isLineSegments&&(h=i.edgeMaterialCache.get(h),u.isConditionalLine&&(h=i.conditionalEdgeMaterialCache.get(h))),h}}getMainMaterial(){return this.getMaterial(ae)}getMainEdgeMaterial(){const e=this.getMaterial(ve);return e?this.edgeMaterialCache.get(e):null}parseColorMetaDirective(e){let t=null,s="#FF00FF",r="#FF00FF",i=1,a=false,o=0,u=Pt,l=null;const c=e.getToken();if(!c)throw new Error('LDrawLoader: Material name was expected after "!COLOUR tag'+e.getLineNumberString()+".");let d=null;for(;d=e.getToken(),!!d;)if(!f(d))switch(d.toUpperCase()){case"CODE":t=e.getToken();break;case"VALUE":if(s=e.getToken(),s.startsWith("0x"))s="#"+s.substring(2);else if(!s.startsWith("#"))throw new Error("LDrawLoader: Invalid color while parsing material"+e.getLineNumberString()+".");break;case"EDGE":if(r=e.getToken(),r.startsWith("0x"))r="#"+r.substring(2);else if(!r.startsWith("#")){if(l=this.getMaterial(r),!l)throw new Error("LDrawLoader: Invalid edge color while parsing material"+e.getLineNumberString()+".");l=this.edgeMaterialCache.get(l)}break;case"ALPHA":if(i=parseInt(e.getToken()),isNaN(i))throw new Error("LDrawLoader: Invalid alpha value in material definition"+e.getLineNumberString()+".");i=Math.max(0,Math.min(1,i/255)),i<1&&(a=true);break;case"LUMINANCE":if(!f(e.getToken()))throw new Error("LDrawLoader: Invalid luminance value in material definition"+e.getLineNumberString()+".");break;case"CHROME":u=Lt;break;case"PEARLESCENT":u=Et;break;case"RUBBER":u=Ft;break;case"MATTE_METALLIC":u=At;break;case"METAL":u=Dt;break;case"MATERIAL":e.setToEnd();break;default:throw new Error('LDrawLoader: Unknown token "'+d+'" while parsing material'+e.getLineNumberString()+".")}let h=null;switch(u){case Pt:h=new V({roughness:.3,metalness:0});break;case Et:h=new V({roughness:.3,metalness:.25});break;case Lt:h=new V({roughness:0,metalness:1});break;case Ft:h=new V({roughness:.9,metalness:0});break;case At:h=new V({roughness:.8,metalness:.4});break;case Dt:h=new V({roughness:.2,metalness:.85});break}if(h.color.setStyle(s,ke),h.transparent=a,h.premultipliedAlpha=true,h.opacity=i,h.depthWrite=!a,h.polygonOffset=true,h.polygonOffsetFactor=1,o!==0&&h.emissive.setStyle(s,ke).multiplyScalar(o),!l){if(l=new ne({color:new de().setStyle(r,ke),transparent:a,opacity:i,depthWrite:!a}),l.color,l.userData.code=t,l.name=c+" - Edge",this.ConditionalLineMaterial===null)throw new Error("THREE.LDrawLoader: ConditionalLineMaterial type must be specified via .setConditionalLineMaterial().");const m=new this.ConditionalLineMaterial({fog:true,transparent:a,depthWrite:!a,color:new de().setStyle(r,ke),opacity:i});m.userData.code=t,m.name=c+" - Conditional Edge",this.conditionalEdgeMaterialCache.set(l,m)}return h.userData.code=t,h.name=c,this.edgeMaterialCache.set(h,l),this.addMaterial(h),h;function f(m){let g;return m.startsWith("LUMINANCE")?g=parseInt(m.substring(9)):g=parseInt(m),isNaN(g)?false:(o=Math.max(0,Math.min(1,g/255)),true)}}computeBuildingSteps(e){let t=0;e.traverse(s=>{s.isGroup&&(s.userData.startingBuildingStep&&t++,s.userData.buildingStep=t)}),e.userData.numBuildingSteps=t+1}}const ct=new Set(["step","stp","stl","obj","ply","gltf","glb","3mf","amf","dae","fbx","3ds","usdz","gcode","gco","nc","wrl","vrml","pcd","xyz","vtk","vox","ldr","mpd","kmz","md2","lwo","bvh","pdb","nrrd","nhdr"]),Rt=250,st=12e3,Os=24,Tt=33;let Me=null;const ks=[{extensions:["step","stp","stl","obj","ply","gltf","glb","3mf","amf","dae","fbx","3ds","usdz","gcode","gco","nc","wrl","vrml","pcd","xyz","vtk","vox","ldr","mpd","kmz","md2","lwo","bvh","pdb","nrrd","nhdr"],family:"model3d",driverId:"model3d",targetFormat:"model3d",contentTypes:["model/stl","model/step","application/step","application/x-step","model/x.stl-ascii","model/x.stl-binary","application/vnd.ms-pki.stl","model/obj","model/ply","application/ply","model/gltf+json","model/gltf-binary","model/3mf","model/amf","application/x-amf","model/vnd.collada+xml","application/vnd.collada+xml","model/fbx","model/3ds","model/vnd.usdz+zip","model/usd","text/x-gcode","model/vrml","x-world/x-vrml","application/vnd.pointcloud","model/vtk","application/vnd.vtk","model/vox","application/x-magica-voxel","model/vnd.ldraw","text/vnd.ldraw","application/x-ldraw","application/vnd.google-earth.kmz","application/vnd.google-earth.kmz+xml","model/md2","application/x-md2","model/lwo","application/x-lwo","application/x-lightwave-object","application/bvh","application/x-bvh","chemical/x-pdb","chemical/pdb","application/nrrd","application/x-nrrd","application/vnd.ms-package.3dmanufacturing-3dmodel+xml"]}];class Rs{constructor(e,t={}){M(this,"listeners",{loading:new Set,rendered:new Set,error:new Set,statechange:new Set,warnings:new Set});M(this,"root");M(this,"stage");M(this,"hint");M(this,"renderer",null);M(this,"scene",null);M(this,"camera",null);M(this,"modelGroup",null);M(this,"geometry",null);M(this,"edgeGeometry",null);M(this,"material",null);M(this,"edgeMaterial",null);M(this,"resizeObserver",null);M(this,"animationFrame",0);M(this,"yaw",-35);M(this,"pitch",24);M(this,"distance",140);M(this,"modelRadius",60);M(this,"baseDistance",140);M(this,"baseModelRadius",60);M(this,"baseModelGroupPosition",new E);M(this,"explodeTargets",[]);M(this,"maxExplodeOffset",0);M(this,"materialRuntimeState",new WeakMap);M(this,"sectionSourceGeometry",null);M(this,"raycaster",new Wn);M(this,"pointerNdc",new lt);M(this,"measurementLineGeometry",null);M(this,"measurementLineMaterial",null);M(this,"measurementLine",null);M(this,"measurementPointsGeometry",null);M(this,"measurementPointsMaterial",null);M(this,"measurementPoints",null);M(this,"sectionHelperGroup",null);M(this,"sectionPlaneHelper",null);M(this,"sectionPlaneHelperGeometry",null);M(this,"sectionPlaneHelperMaterial",null);M(this,"sectionPlaneOutlineGeometry",null);M(this,"sectionPlaneOutlineMaterial",null);M(this,"sectionPlaneOutline",null);M(this,"sectionPlaneFillGeometry",null);M(this,"sectionPlaneFillMaterial",null);M(this,"sectionPlaneFill",null);M(this,"sectionBoxFillGeometry",null);M(this,"sectionBoxFillMaterial",null);M(this,"sectionBoxFill",null);M(this,"sectionBoxHelperGeometry",null);M(this,"sectionBoxHelperMaterial",null);M(this,"sectionBoxHelper",null);M(this,"sectionPlanes",[new we(new E(1,0,0),0),new we(new E(-1,0,0),0),new we(new E(0,1,0),0),new we(new E(0,-1,0),0),new we(new E(0,0,1),0),new we(new E(0,0,-1),0)]);M(this,"sectionHelperCache",new Map);M(this,"appliedSectionClippingKey",null);M(this,"appliedSectionHelperKey",null);M(this,"lastSectionHelperUpdateAt",Number.NEGATIVE_INFINITY);M(this,"sectionBounds",Ge());M(this,"measurementHoverClientX",null);M(this,"measurementHoverClientY",null);M(this,"projectionMode","perspective");M(this,"viewPreset","isometric");M(this,"displayMode","solid-edge");M(this,"snapshotBackground","scene");M(this,"state");M(this,"loadController",null);M(this,"interactionController",null);M(this,"resize",()=>{if(!this.renderer||!this.camera)return;const e2=this.stage.getBoundingClientRect(),t2=Math.max(1,Math.floor(e2.width||this.stage.clientWidth||1)),s2=Math.max(1,Math.floor(e2.height||this.stage.clientHeight||1));if(this.camera instanceof Ve)this.camera.aspect=t2/s2,this.camera.updateProjectionMatrix();else{const r=t2/s2,i=this.modelRadius*1.08/(this.state.scale*Math.min(1,r)),a=i*r;this.camera.left=-a,this.camera.right=a,this.camera.top=i,this.camera.bottom=-i,this.camera.updateProjectionMatrix()}this.positionCamera(),this.renderer.setSize(t2,s2,false),this.state.camera=this.currentCameraState()});this.host=e,this.options=t;const s=this.options.initialScale??1;this.root=document.createElement("div"),this.root.className="model3dv-preview",this.stage=document.createElement("div"),this.stage.className="model3dv-stage",this.hint=document.createElement("div"),this.hint.className="model3dv-hint",this.hint.textContent="Drag to orbit \xB7 Scroll to zoom \xB7 Double-click to reset",this.root.replaceChildren(this.stage,this.hint),this.host.replaceChildren(this.root),this.state={loading:false,error:null,family:"model3d",warnings:[],capabilities:{zoom:true,fit:true,pan:true,orbit:true,fullscreen:true,download:true,modelTree:true,metadata:true,measure:false,section:false,explode:false,materialFilter:false},scale:Number.isFinite(s)?_(s,.2,4):1,explode:0,displayMode:this.displayMode,snapshotBackground:this.snapshotBackground,measurement:{active:false,status:"idle",snapMode:"surface",axisLock:"free"},section:ue(),camera:{position:[0,0,this.distance],target:[0,0,0],projection:this.projectionMode,viewPreset:this.viewPreset}}}async load(e,t){var a,o,u,l;this.stopLoad();const s=new AbortController;this.loadController=s;const r=s.signal,i=()=>s.abort();r.addEventListener("abort",()=>{var c;(c=t.signal)==null||c.removeEventListener("abort",i),this.loadController===s&&(this.loadController=null,this.disposeScene(),this.state.loading=false,this.emit("statechange",this.state))},{once:true}),(a=t.signal)==null||a.addEventListener("abort",i,{once:true}),this.state={...this.state,loading:true,error:null,title:t.descriptor.name,warnings:[],explode:0,modelTree:void 0,selectedNodeId:void 0,isolatedMaterialKey:void 0,displayMode:this.displayMode,snapshotBackground:this.snapshotBackground,measurement:{active:false,status:"idle",snapMode:"surface",axisLock:"free"},section:ue(),metadata:void 0},this.projectionMode="perspective",this.viewPreset="isometric",this.yaw=-35,this.pitch=24,this.emit("loading",this.state),this.emit("statechange",this.state);try{(o=t.signal)!=null&&o.aborted&&s.abort(),F(r);const c=Sn(((u=t.route)==null?void 0:u.sourceFormat)??t.descriptor.extension);if(!ct.has(c))throw new Error(`3D preview currently supports browser-WASM STEP/STP plus browser-native STL, OBJ, PLY, glTF, GLB, 3MF, AMF, DAE, FBX, 3DS, USDA-backed USDZ, G-code, VRML, PCD, XYZ, VTK, VOX, LDraw, KMZ, MD2, LWO, BVH, PDB, NRRD, and NHDR files, got ${c||"unknown"}.`);const d=await ht(e,r);if(F(r),c==="step"||c==="stp"){const m=await or(d,{signal:r});this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:m.userData.previewWarnings??[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="glb"||c==="gltf"){const m=c==="gltf"?await gr(d,{resourcePath:Cn(e),resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r}):{object:await Gs(d,{signal:r}),warnings:[]};this.createObjectScene(m.object,r),this.state={...this.state,loading:false,error:null,warnings:m.warnings,metadata:T(m.object,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="obj"){const m=new TextDecoder().decode(d);let g=[],w;if(this.options.resourceResolver&&sn(m).length){const p=await Bs(m,{resourceBasePath:t.descriptor.name,resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r});g=p.warnings,w=T(p.object,c),this.createObjectScene(p.object,r)}else{const p=Is(m);w=Gt(p,c),this.createScene(p,r)}this.state={...this.state,loading:false,error:null,warnings:g,metadata:w,camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="amf"){const m=Us(d);this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="dae"){const m=_s(new TextDecoder().decode(d),{resourceBasePath:t.descriptor.name,resourcePath:Vi(e),resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r});this.createObjectScene(m.object,r),this.state={...this.state,loading:false,error:null,warnings:m.warnings,metadata:T(m.object,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="fbx"){const m=rr(d,{resourceBasePath:t.descriptor.name,resourcePath:Ce(e),resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r});this.createObjectScene(m.object,r),this.state={...this.state,loading:false,error:null,warnings:m.warnings,metadata:T(m.object,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="3ds"){const m=ir(d,{resourceBasePath:t.descriptor.name,resourcePath:Ce(e),resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r});this.createObjectScene(m.object,r),this.state={...this.state,loading:false,error:null,warnings:m.warnings,metadata:T(m.object,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="usdz"){const m=await ar(d);this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="gcode"||c==="gco"||c==="nc"){const m=lr(new TextDecoder().decode(d));this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="wrl"||c==="vrml"){const m=cr(new TextDecoder().decode(d),{resourceBasePath:t.descriptor.name,resourcePath:Ce(e),resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r});this.createObjectScene(m.object,r),this.state={...this.state,loading:false,error:null,warnings:m.warnings,metadata:T(m.object,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="pcd"){const m=ur(d);this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="xyz"){const m=dr(new TextDecoder().decode(d));this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="vtk"){const m=hr(d);this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="vox"){const m=fr(d);this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="ldr"||c==="mpd"){const m=await pr(new TextDecoder().decode(d),{resourceBasePath:t.descriptor.name,resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r});this.createObjectScene(m.object,r),this.state={...this.state,loading:false,error:null,warnings:m.warnings,metadata:T(m.object,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="kmz"){const m=await Vs(d,{signal:r});this.createObjectScene(m.object,r),this.state={...this.state,loading:false,error:null,warnings:m.warnings,metadata:T(m.object,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="md2"){const m=Js(d);this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="lwo"){const m=Qs(d,{resourceBasePath:t.descriptor.name,resourcePath:Ce(e),modelName:$i(t.descriptor.name),resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r});this.createObjectScene(m.object,r),this.state={...this.state,loading:false,error:null,warnings:m.warnings,metadata:T(m.object,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="bvh"){const m=er(new TextDecoder().decode(d));this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="pdb"){const m=tr(new TextDecoder().decode(d));this.createObjectScene(m,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(m,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}if(c==="nrrd"||c==="nhdr"){const m=c==="nhdr"?await sr(new TextDecoder().decode(d),{resourceBasePath:t.descriptor.name,resourceResolver:this.options.resourceResolver,sourceFormat:c,signal:r}):d;F(r);const g=nr(m);this.createObjectScene(g,r),this.state={...this.state,loading:false,error:null,warnings:[],metadata:T(g,c),camera:this.currentCameraState()},this.emit("rendered",this.state),this.emit("statechange",this.state);return}const h=c==="3mf"?await js(d,{signal:r}):{geometry:c==="ply"?Hs(d):Ts(d),warnings:[]},f=h.geometry;this.createScene(f,r),this.state={...this.state,loading:false,error:null,warnings:h.warnings,metadata:Gt(h.geometry,c),camera:this.currentCameraState()},this.state.warnings.length&&this.emit("warnings",this.state.warnings),this.emit("rendered",this.state),this.emit("statechange",this.state)}catch(c){if(r.aborted){(l=t.signal)!=null&&l.aborted&&F(r);return}this.stopLoad();const d=c instanceof Error?c:new Error(String(c));throw this.state.loading=false,this.state.error=d.message,this.emit("error",d),this.emit("statechange",this.state),d}}destroy(){this.stopLoad(),this.state.loading=false,this.stage.replaceChildren(),this.root.replaceChildren(),this.root.parentElement===this.host&&this.host.replaceChildren();for(const e of Object.values(this.listeners))e.clear()}stopLoad(){const e=this.loadController;this.loadController=null,e==null||e.abort(),this.disposeScene()}getState(){return{...this.state,warnings:[...this.state.warnings],modelTree:this.state.modelTree?fn(this.state.modelTree):void 0,layers:[...this.state.layers??[]],activeLayerIds:[...this.state.activeLayerIds??[]],metadata:this.state.metadata?{...this.state.metadata,materialNames:[...this.state.metadata.materialNames??[]],materialDetails:yn(this.state.metadata.materialDetails),bounds:this.state.metadata.bounds?{...this.state.metadata.bounds,min:[...this.state.metadata.bounds.min],max:[...this.state.metadata.bounds.max],size:[...this.state.metadata.bounds.size]}:void 0}:void 0,isolatedMaterialKey:this.state.isolatedMaterialKey,displayMode:this.state.displayMode,snapshotBackground:this.state.snapshotBackground,measurement:Vt(this.state.measurement),section:ii(this.state.section),camera:this.state.camera?{...this.state.camera}:void 0}}on(e,t){return this.listeners[e].add(t),()=>{this.listeners[e].delete(t)}}setScale(e){if(!Number.isFinite(e))return;const t=Math.max(.2,Math.min(e,4));this.state.scale!==t&&(this.state.scale=t,this.distance=Math.max(this.modelRadius*1.25,this.modelRadius*2.6/this.state.scale),this.updateCamera(),this.emit("statechange",this.state))}fit(){this.setScale(1)}pan(e,t){!Number.isFinite(e)||!Number.isFinite(t)||(this.yaw+=e*.35,this.pitch=_(this.pitch+t*.25,-80,80),this.viewPreset="free",this.updateCamera(),this.emit("statechange",this.state))}selectNode(e){this.state.selectedNodeId!==e&&(this.state.selectedNodeId=e,this.applyAppearanceState(),this.focusNode(e),this.emit("statechange",this.state))}setNodeVisibility(e,t){this.toggleNodeVisibility(e,t)}toggleNodeVisibility(e,t){var i;if(!this.modelGroup||!((i=this.state.modelTree)!=null&&i.length))return;const s=this.findNodeObject(e);if(!s)return;const r=typeof t=="boolean"?t:!(s.userData.previewOriginalVisible??s.visible);if(!!(s.userData.previewOriginalVisible??s.visible)!==r){if(this.applyNodeVisibility(s,r),this.state.modelTree=pn(this.state.modelTree,e,r),this.state.selectedNodeId){const a=wn(this.state.modelTree,this.state.selectedNodeId);a!=null&&a.visible?this.applyAppearanceState():(this.state.selectedNodeId=void 0,this.applyAppearanceState(),this.focusNode(void 0))}else this.applyAppearanceState();this.clearSectionHelperCache(),this.emit("statechange",this.state)}}setExplode(e){if(!Number.isFinite(e))return;if(!this.explodeTargets.length){this.state.explode=0;return}const t=_(e,0,1);(this.state.explode??0)!==t&&(this.state.explode=t,this.applyExplode(this.state.explode),this.focusNode(this.state.selectedNodeId),this.emit("statechange",this.state))}setActiveMaterial(e){const t=e||void 0;this.state.isolatedMaterialKey!==t&&(this.state.isolatedMaterialKey=t,this.applyAppearanceState(),this.clearSectionHelperCache(),this.focusNode(this.state.selectedNodeId),this.emit("statechange",this.state))}setMeasurementActive(e){const t=Vt(this.state.measurement)??{active:false,status:"idle",snapMode:"surface",axisLock:"free"},s={...t,active:e,status:e?t.start?t.end?"complete":"pick-end":"pick-start":t.start&&t.end?"complete":t.start?"pick-end":"idle"};e||(s.previewPoint=void 0,s.previewDelta=void 0,s.previewDistance=void 0),!$t(this.state.measurement,s)&&(this.state.measurement=s,this.updateMeasurementHelpers(),this.emit("statechange",this.state))}clearMeasurement(){var t,s;const e={active:false,status:"idle",snapMode:((t=this.state.measurement)==null?void 0:t.snapMode)??"surface",axisLock:((s=this.state.measurement)==null?void 0:s.axisLock)??"free",previewPoint:void 0,previewDelta:void 0,previewDistance:void 0};$t(this.state.measurement,e)||(this.state.measurement=e,this.updateMeasurementHelpers(),this.emit("statechange",this.state))}ensureSectionState(){const e=this.state.section;return e?Qe(e,this.sectionBounds):ue(this.sectionBounds)}setMeasurementSnapMode(e){const t=this.state.measurement??{active:false,status:"idle",snapMode:"surface",axisLock:"free"};(t.snapMode??"surface")!==e&&(t.snapMode=e,this.state.measurement=t,this.refreshMeasurementHover(),this.updateMeasurementHelpers(),this.emit("statechange",this.state))}setMeasurementAxisLock(e){const t=this.state.measurement??{active:false,status:"idle",snapMode:"surface",axisLock:"free"};(t.axisLock??"free")!==e&&(t.axisLock=e,this.state.measurement=t,this.refreshMeasurementHover(),this.updateMeasurementHelpers(),this.emit("statechange",this.state))}setSectionActive(e){const t=this.ensureSectionState();t.active!==e&&(t.active=e,this.state.section=t,this.updateSectionPlanes(),this.emit("statechange",this.state))}setSectionMode(e){const t=this.ensureSectionState();(t.mode??"single")!==e&&(t.mode=e,this.state.section=Qe(t,this.sectionBounds),this.updateSectionPlanes(),this.emit("statechange",this.state))}setSectionAxis(e){const t=this.ensureSectionState();if(t.axis===e)return;const[s,r]=this.sectionBounds[e];t.axis=e,t.min=R(s),t.max=R(r),t.offset=_(t.offset,t.min,t.max),this.state.section=t,this.updateSectionPlanes(),this.emit("statechange",this.state)}setSectionOffset(e){if(!Number.isFinite(e))return;const t=this.ensureSectionState(),s=R(_(e,t.min,t.max));t.offset!==s&&(t.offset=s,this.state.section=t,this.updateSectionPlanes(),this.emit("statechange",this.state))}setSectionRange(e,t,s){var c;if(!Number.isFinite(t)||!Number.isFinite(s))return;const r=this.ensureSectionState(),i=this.sectionBounds[e],a=_(Math.min(t,s),i[0],i[1]),o=_(Math.max(t,s),i[0],i[1]),u=[R(a),R(o)],l=(c=r.range)==null?void 0:c[e];l&&l[0]===u[0]&&l[1]===u[1]||(r.range={...r.range??xe(this.sectionBounds),[e]:u},this.state.section=Qe(r,this.sectionBounds),this.updateSectionPlanes(),this.emit("statechange",this.state))}clearSection(){const e=ue(this.sectionBounds);ai(this.state.section,e)||(this.state.section=e,this.updateSectionPlanes(),this.emit("statechange",this.state))}setCameraProjection(e){this.projectionMode!==e&&(this.projectionMode=e,this.replaceCamera(),this.updateCamera(),this.emit("statechange",this.state))}setCameraViewPreset(e){if(this.viewPreset===e)return;this.viewPreset=e;const t=Jr(e);t&&(this.yaw=t.yaw,this.pitch=t.pitch),this.updateCamera(),this.emit("statechange",this.state)}setDisplayMode(e){this.displayMode!==e&&(this.displayMode=e,this.state.displayMode=e,this.applyAppearanceState(),this.emit("statechange",this.state))}setSnapshotBackground(e){this.snapshotBackground!==e&&(this.snapshotBackground=e,this.state.snapshotBackground=e,this.emit("statechange",this.state))}downloadSnapshot(e,t){if(typeof document>"u")return;const s=this.renderer,r=s==null?void 0:s.domElement,i=this.scene,a=this.camera;if(!r||!s||!i||!a)return;const o=this.applySceneBackground(t??this.snapshotBackground);s.render(i,a);const u=r.toDataURL("image/png");o(),s.render(i,a);const l=document.createElement("a");l.href=u,l.download=Qr(e??this.state.title),l.rel="noopener",l.click()}async fullscreen(){var e,t;await((t=(e=this.root).requestFullscreen)==null?void 0:t.call(e))}createScene(e,t){F(t);const s=Qt({antialias:true,alpha:false,preserveDrawingBuffer:true});this.renderer=s,s.setPixelRatio(Math.min(window.devicePixelRatio||1,2)),s.setClearColor(1120295,1),s.localClippingEnabled=true,s.clippingPlanes=[],s.domElement.className="model3dv-canvas",this.stage.replaceChildren(s.domElement);const r=new xt;r.background=new de(1120295);const i=this.createCamera(),a=new ee;this.modelGroup=a,this.scene=r,this.camera=i;const o=new Y;this.geometry=o,o.setAttribute("position",new ie(e.positions,3)),o.setAttribute("normal",new ie(e.normals,3)),e.colors&&o.setAttribute("color",new ie(e.colors,3)),o.computeBoundingSphere();const u=zi(e.bounds),l=Hi(e.bounds);this.modelRadius=Math.max(l.length()/2,.5),this.baseModelRadius=this.modelRadius,this.distance=Math.max(this.modelRadius*1.25,this.modelRadius*2.6/this.state.scale),this.baseDistance=this.distance,a.position.set(-u.x,-u.y,-u.z),this.baseModelGroupPosition.copy(a.position);const c=new V({color:e.colors?16777215:8246268,roughness:.55,metalness:.08,vertexColors:!!e.colors});this.material=c;const d=new $(o,c);a.add(d);const h=new Mt(o,35),f=new ne({color:14412542,transparent:true,opacity:.22});this.edgeGeometry=h,this.edgeMaterial=f;const m=new Q(h,f),g=m;g.userData.previewEdgeHelper=true,g.userData.previewEdgeSourceId=d.id,g.userData.previewOriginalVisible=true,a.add(m),r.add(new St(16777215,.48));const w=new Oe(16777215,1.4);w.position.set(1,1.6,1.3),r.add(w);const p=new Oe(9684477,.8);p.position.set(-1.5,.8,-1),r.add(p),r.add(a),this.renderer=s,this.scene=r,this.camera=i,this.modelGroup=a,this.geometry=o,this.edgeGeometry=h,this.material=c,this.edgeMaterial=f,this.clearSectionHelperCache(),this.sectionSourceGeometry={positions:ki(e.positions,st)},this.explodeTargets=[],this.maxExplodeOffset=0,this.sectionBounds=ji(e.bounds,u),this.state.modelTree=void 0,this.state.selectedNodeId=void 0,this.state.isolatedMaterialKey=void 0,this.state.explode=0,this.state.displayMode=this.displayMode,this.state.snapshotBackground=this.snapshotBackground,this.state.measurement={active:false,status:"idle",snapMode:"surface",axisLock:"free"},this.state.section=ue(this.sectionBounds),this.state.capabilities.measure=true,this.state.capabilities.section=true,this.state.capabilities.explode=false,this.state.capabilities.materialFilter=false,this.state.capabilities.displayMode=true,this.captureMaterialRuntimeState(a),this.applyAppearanceState(),this.setupMeasurementHelpers(a),this.bindInteractions(s.domElement),this.observeResize(),this.resize(),this.updateSectionPlanes(),this.updateCamera(),this.startAnimation()}createObjectScene(e,t){t.aborted&&(he(e),F(t));const s=Qt({antialias:true,alpha:false,preserveDrawingBuffer:true});this.renderer=s,s.setPixelRatio(Math.min(window.devicePixelRatio||1,2)),s.setClearColor(1120295,1),s.localClippingEnabled=true,s.clippingPlanes=[],s.domElement.className="model3dv-canvas",this.stage.replaceChildren(s.domElement);const r=new xt;r.background=new de(1120295);const i=this.createCamera(),a=new ee;this.modelGroup=a,this.scene=r,this.camera=i,a.add(e),r.add(new St(16777215,.62));const o=new Oe(16777215,1.45);o.position.set(1,1.6,1.3),r.add(o);const u=new Oe(9684477,.7);u.position.set(-1.5,.8,-1),r.add(u),r.add(a);const l=new te().setFromObject(e),c=l.getCenter(new E),d=l.getSize(new E);this.modelRadius=Math.max(d.length()/2,.5),this.baseModelRadius=this.modelRadius,this.distance=Math.max(this.modelRadius*1.25,this.modelRadius*2.6/this.state.scale),this.baseDistance=this.distance,e.position.sub(c),this.sectionBounds=Gi(e),this.baseModelGroupPosition.copy(a.position),this.explodeTargets=ei(e,this.baseModelRadius),this.maxExplodeOffset=this.explodeTargets.reduce((h,f)=>Math.max(h,f.distance),0),this.state.modelTree=Kr(e),this.state.selectedNodeId=void 0,this.state.isolatedMaterialKey=void 0,this.state.explode=0,this.state.displayMode=this.displayMode,this.state.snapshotBackground=this.snapshotBackground,this.state.measurement={active:false,status:"idle",snapMode:"surface",axisLock:"free"},this.state.section=ue(this.sectionBounds),this.state.capabilities.measure=true,this.state.capabilities.section=true,this.state.capabilities.explode=this.explodeTargets.length>1,this.state.capabilities.materialFilter=Yr(e),this.state.capabilities.displayMode=true,this.attachEdgeHelpers(e),this.captureMaterialRuntimeState(e),this.applyExplode(0),this.applyAppearanceState(),this.setupMeasurementHelpers(a),this.renderer=s,this.scene=r,this.camera=i,this.modelGroup=a,this.clearSectionHelperCache(),this.sectionSourceGeometry={positions:new Float32Array,objects:Di(e,st)},this.bindInteractions(s.domElement),this.observeResize(),this.resize(),this.updateSectionPlanes(),this.updateCamera(),this.startAnimation()}bindInteractions(e){var u;(u=this.interactionController)==null||u.abort(),this.interactionController=new AbortController;const t=this.interactionController.signal,s=new Map;let r=null;const i=()=>{const[l,c]=s.values();return l&&c?Math.hypot(c.x-l.x,c.y-l.y):0},a=l=>{e.hasPointerCapture(l)&&e.releasePointerCapture(l)};e.style.touchAction="none",t.addEventListener("abort",()=>{for(const l of s.keys())a(l);s.clear(),r=null},{once:true}),e.addEventListener("pointerdown",l=>{const c={x:l.clientX,y:l.clientY};s.set(l.pointerId,c),r=s.size===1?{...c}:null,e.setPointerCapture(l.pointerId)},{signal:t}),e.addEventListener("pointermove",l=>{var m;const c=s.get(l.pointerId);if(!c){(((m=this.state.measurement)==null?void 0:m.active)??false)&&s.size===0&&(this.measurementHoverClientX=l.clientX,this.measurementHoverClientY=l.clientY,this.updateMeasurementHover(l.clientX,l.clientY));return}r&&Math.hypot(l.clientX-r.x,l.clientY-r.y)>4&&(r=null);const d=i(),h=l.clientX-c.x,f=l.clientY-c.y;if(c.x=l.clientX,c.y=l.clientY,s.size===1)(h!==0||f!==0)&&this.pan(h,f);else{const g=i();d>0&&g>0&&this.setScale(this.state.scale*g/d)}},{signal:t}),e.addEventListener("pointerup",l=>{var d;if(!s.delete(l.pointerId))return;const c=r&&Math.hypot(l.clientX-r.x,l.clientY-r.y)<=4;r=null,a(l.pointerId),(((d=this.state.measurement)==null?void 0:d.active)??false)&&c&&this.pickMeasurementPoint(l.clientX,l.clientY)},{signal:t});const o=l=>{s.delete(l.pointerId)&&(r=null,a(l.pointerId))};e.addEventListener("pointercancel",o,{signal:t}),e.addEventListener("lostpointercapture",o,{signal:t}),e.addEventListener("pointerleave",()=>{this.measurementHoverClientX=null,this.measurementHoverClientY=null,this.clearMeasurementHover()},{signal:t}),e.addEventListener("wheel",l=>{l.preventDefault(),this.setScale(this.state.scale+(l.deltaY>0?-.08:.08))},{passive:false,signal:t}),e.addEventListener("dblclick",l=>{var c;l.button!==0||l.ctrlKey||l.metaKey||l.altKey||l.shiftKey||(c=this.state.measurement)!=null&&c.active||(l.preventDefault(),this.setCameraViewPreset("isometric"),this.fit())},{signal:t})}observeResize(){var e;if((e=this.resizeObserver)==null||e.disconnect(),typeof ResizeObserver<"u"){this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(this.stage);return}window.addEventListener("resize",this.resize)}startAnimation(){const e=()=>{this.animationFrame=requestAnimationFrame(e),this.renderFrame()};e()}renderFrame(){!this.renderer||!this.scene||!this.camera||!this.modelGroup||(this.updateSectionPlanes(),this.renderer.render(this.scene,this.camera))}createCamera(){return this.projectionMode==="orthographic"?new Kn(-100,100,100,-100,.1,1e5):new Ve(45,1,.1,1e5)}replaceCamera(){var t;const e=((t=this.camera)==null?void 0:t.position.clone())??new E(0,0,this.distance);this.camera=this.createCamera(),this.camera.position.copy(e),this.resize()}updateCamera(){this.resize()}positionCamera(){if(!this.camera)return;let e=this.distance;if(this.camera instanceof Ve){const r=tt(this.camera.fov)/2,i=Math.atan(Math.tan(r)*this.camera.aspect);e*=1.08/(2.6*Math.sin(Math.min(r,i)))}const t=tt(this.yaw),s=tt(this.pitch);this.camera.position.set(e*Math.cos(s)*Math.sin(t),e*Math.sin(s),e*Math.cos(s)*Math.cos(t)),this.camera.lookAt(0,0,0)}currentCameraState(){var t;const e=((t=this.camera)==null?void 0:t.position)??new E(0,0,this.distance);return{position:[e.x,e.y,e.z],target:[0,0,0],projection:this.projectionMode,viewPreset:this.viewPreset}}applyExplode(e){this.explodeTargets.length&&this.clearSectionHelperCache();for(const t of this.explodeTargets)t.object.position.copy(t.basePosition).addScaledVector(t.direction,t.distance*e)}setupMeasurementHelpers(e){const t=new Y;t.setAttribute("position",new Z([0,0,0,0,0,0],3));const s=new ne({color:16096779,transparent:true,opacity:.95}),r=new _e(t,s);r.visible=false,r.userData.previewMeasurementHelper=true;const i=new Y;i.setAttribute("position",new Z([0,0,0,0,0,0],3));const a=new Pe({color:16498468,size:Math.max(this.baseModelRadius*.045,.8),sizeAttenuation:true}),o=new me(i,a);o.visible=false,o.userData.previewMeasurementHelper=true,e.add(r),e.add(o),this.measurementLineGeometry=t,this.measurementLineMaterial=s,this.measurementLine=r,this.measurementPointsGeometry=i,this.measurementPointsMaterial=a,this.measurementPoints=o,this.updateMeasurementHelpers()}pickMeasurementPoint(e,t){this.measurementHoverClientX=e,this.measurementHoverClientY=t;const s=this.resolveMeasurementPoint(e,t);s&&this.applyMeasurementPoint(s)}updateMeasurementHover(e,t){const s=this.state.measurement;if(!(s!=null&&s.active))return;const r=this.resolveMeasurementPoint(e,t);if(!r){this.clearMeasurementHover();return}this.applyMeasurementPreviewPoint(r)}applyMeasurementPreviewPoint(e){const t=this.state.measurement;if(t!=null&&t.active){if(t.start){const s=new E(...t.start),r=Ut(e,s,t.axisLock??"free"),i=r.clone().sub(s),a=ye(r),o=ye(i),u=R(i.length());if(oe(t.previewPoint,a)&&oe(t.previewDelta,o)&&t.previewDistance===u&&t.status==="pick-end")return;t.previewPoint=a,t.previewDelta=o,t.previewDistance=u,t.status="pick-end"}else{const s=ye(e);if(oe(t.previewPoint,s)&&t.previewDelta==null&&t.previewDistance==null&&t.status==="pick-start")return;t.previewPoint=s,t.previewDelta=void 0,t.previewDistance=void 0,t.status="pick-start"}this.updateMeasurementHelpers(),this.emit("statechange",this.state)}}refreshMeasurementHover(){this.measurementHoverClientX==null||this.measurementHoverClientY==null||this.updateMeasurementHover(this.measurementHoverClientX,this.measurementHoverClientY)}clearMeasurementHover(){const e=this.state.measurement;if(!e)return;const t=e.active?e.start?"pick-end":"pick-start":e.status;e.previewPoint==null&&e.previewDelta==null&&e.previewDistance==null&&e.status===t||(e.previewPoint=void 0,e.previewDelta=void 0,e.previewDistance=void 0,e.active&&(e.status=t),this.updateMeasurementHelpers(),this.emit("statechange",this.state))}resolveMeasurementPoint(e,t){var c;if(!this.renderer||!this.camera||!this.modelGroup)return;const s=this.renderer.domElement.getBoundingClientRect(),r=s.width||1,i=s.height||1;this.pointerNdc.set((e-s.left)/r*2-1,-((t-s.top)/i*2-1)),this.raycaster.setFromCamera(this.pointerNdc,this.camera);const o=this.raycaster.intersectObject(this.modelGroup,true).find(d=>{const h=d.object;return!h.userData.previewMeasurementHelper&&h.visible});if(!o)return;const l=(((c=this.state.measurement)==null?void 0:c.snapMode)??"surface")==="vertex"?Zr(o)??o.point:o.point;return this.modelGroup.worldToLocal(l.clone())}applyMeasurementPoint(e){const t=this.state.measurement??{active:false,status:"idle",snapMode:"surface",axisLock:"free"},s=t.start?new E(...t.start):void 0;if(!s||t.end)t.start=ye(e),t.end=void 0,t.delta=void 0,t.distance=void 0,t.previewPoint=void 0,t.previewDelta=void 0,t.previewDistance=void 0,t.status="pick-end";else{const r=Ut(e,s,t.axisLock??"free"),i=r.clone().sub(s);t.end=ye(r),t.delta=ye(i),t.distance=R(i.length()),t.previewPoint=void 0,t.previewDelta=void 0,t.previewDistance=void 0,t.status="complete",t.active=false}this.state.measurement=t,this.updateMeasurementHelpers(),this.emit("statechange",this.state)}updateMeasurementHelpers(){var s,r,i,a;const e=(s=this.state.measurement)!=null&&s.start?new E(...this.state.measurement.start):void 0,t=(r=this.state.measurement)!=null&&r.end?new E(...this.state.measurement.end):(i=this.state.measurement)!=null&&i.previewPoint?new E(...this.state.measurement.previewPoint):void 0;if(this.measurementLineGeometry&&this.measurementLine){const o=this.measurementLineGeometry.getAttribute("position");e&&t?(o.setXYZ(0,e.x,e.y,e.z),o.setXYZ(1,t.x,t.y,t.z),o.needsUpdate=true,this.measurementLineGeometry.computeBoundingSphere(),this.measurementLine.visible=true):this.measurementLine.visible=false}if(this.measurementPointsGeometry&&this.measurementPoints){const o=this.measurementPointsGeometry.getAttribute("position"),u=e??((a=this.state.measurement)!=null&&a.previewPoint?new E(...this.state.measurement.previewPoint):void 0);if(u){o.setXYZ(0,u.x,u.y,u.z);const l=t??u;o.setXYZ(1,l.x,l.y,l.z),o.needsUpdate=true,this.measurementPointsGeometry.computeBoundingSphere(),this.measurementPoints.visible=true}else this.measurementPoints.visible=false}}updateSectionPlanes(){var r,i;if(!this.renderer||!this.modelGroup)return;const e=this.state.section;if(!(e!=null&&e.active)){this.appliedSectionClippingKey!=="inactive"&&(this.renderer.clippingPlanes=[],this.appliedSectionClippingKey="inactive"),this.appliedSectionHelperKey!=="inactive"&&(this.updateSectionHelpers(void 0),this.appliedSectionHelperKey="inactive");return}this.modelGroup.updateMatrixWorld(true);const t=ui(e,this.modelGroup);if(t!==this.appliedSectionClippingKey){const a=e.mode==="box"?this.resolveBoxSectionPlanes(e):this.resolveSingleSectionPlanes(e);this.renderer.clippingPlanes=a,this.appliedSectionClippingKey=t}const s=ci(e);if(e.mode==="box"){s!==this.appliedSectionHelperKey&&this.appliedSectionHelperKey!==null&&this.appliedSectionHelperKey!=="inactive"&&this.appliedSectionHelperKey.startsWith("box:")&&((r=this.sectionBoxFill)==null?void 0:r.visible)&&((i=this.sectionBoxHelper)==null?void 0:i.visible)&&Re()-this.lastSectionHelperUpdateAt<Tt?this.markBoxSectionHelperPending():s!==this.appliedSectionHelperKey&&(this.updateSectionHelpers(e),this.appliedSectionHelperKey=s,this.lastSectionHelperUpdateAt=Re());return}this.prepareSingleSectionHelper(e),s!==this.appliedSectionHelperKey&&(this.shouldRefreshSingleSectionHelper(e)?(this.updateSectionPlaneDetail(e),this.appliedSectionHelperKey=s,this.lastSectionHelperUpdateAt=Re()):this.markSingleSectionHelperPending())}markBoxSectionHelperPending(){!this.sectionPlaneHelper||!this.sectionPlaneOutline||!this.sectionPlaneFill||!this.sectionBoxFill||!this.sectionBoxHelper||(this.sectionPlaneHelper.visible=false,this.sectionPlaneOutline.visible=false,this.sectionPlaneFill.visible=false,this.sectionBoxFill.visible=false,this.sectionBoxHelper.visible=false)}shouldRefreshSingleSectionHelper(e){return this.appliedSectionHelperKey===null||this.appliedSectionHelperKey==="inactive"||this.sectionHelperCache.has(Ue(e))?true:Re()-this.lastSectionHelperUpdateAt>=Tt}prepareSingleSectionHelper(e){this.ensureSectionHelpers(),!(!this.sectionPlaneHelper||!this.sectionPlaneOutline||!this.sectionPlaneFill||!this.sectionBoxFill||!this.sectionBoxHelper)&&(this.updateSectionPlaneMesh(e),this.sectionBoxFill.visible=false,this.sectionBoxHelper.visible=false,this.sectionPlaneHelper.visible=true,this.sectionPlaneOutline.visible=true)}markSingleSectionHelperPending(){!this.sectionPlaneOutline||!this.sectionPlaneFill||(this.sectionPlaneOutline.visible=false,this.sectionPlaneFill.visible=false)}resolveSingleSectionPlanes(e){const t=_t(e.axis),s=this.sectionPlanes[0];return s.set(t,-e.offset),s.applyMatrix4(this.modelGroup.matrixWorld),[s]}resolveBoxSectionPlanes(e){const t=e.range??xe(this.sectionBounds),s=[],r=[{axis:"x",positive:this.sectionPlanes[0],negative:this.sectionPlanes[1]},{axis:"y",positive:this.sectionPlanes[2],negative:this.sectionPlanes[3]},{axis:"z",positive:this.sectionPlanes[4],negative:this.sectionPlanes[5]}];for(const{axis:i,positive:a,negative:o}of r){const u=this.sectionBounds[i],[l,c]=t[i];l>u[0]+5e-4&&(a.set(_t(i),-l),a.applyMatrix4(this.modelGroup.matrixWorld),s.push(a)),c<u[1]-5e-4&&(o.set(qr(i),c),o.applyMatrix4(this.modelGroup.matrixWorld),s.push(o))}return s}ensureSectionHelpers(){if(!this.modelGroup||this.sectionHelperGroup)return;const e=new ee;e.userData.previewMeasurementHelper=true;const t=new Yn(1,1),s=new $e({color:3718648,transparent:true,opacity:.14,side:Te,depthWrite:false}),r=new $(t,s);r.visible=false,r.renderOrder=3,r.userData.previewMeasurementHelper=true,e.add(r);const i=new Y;i.setAttribute("position",new Z(new Array(24).fill(0),3));const a=new ne({color:8246268,transparent:true,opacity:.95,depthWrite:false}),o=new Q(i,a);o.visible=false,o.renderOrder=4,o.userData.previewMeasurementHelper=true,e.add(o);const u=new Y,l=new $e({color:3718648,transparent:true,opacity:.22,side:Te,depthWrite:false}),c=new $(u,l);c.visible=false,c.renderOrder=3.5,c.userData.previewMeasurementHelper=true,e.add(c);const d=new Y,h=new $e({color:3718648,transparent:true,opacity:.1,side:Te,depthWrite:false}),f=new $(d,h);f.visible=false,f.renderOrder=2.8,f.userData.previewMeasurementHelper=true,e.add(f);const m=new Y;m.setAttribute("position",new Z(new Array(72).fill(0),3));const g=new ne({color:3718648,transparent:true,opacity:.7,depthWrite:false}),w=new Q(m,g);w.visible=false,w.renderOrder=3,w.userData.previewMeasurementHelper=true,e.add(w),this.modelGroup.add(e),this.sectionHelperGroup=e,this.sectionPlaneHelperGeometry=t,this.sectionPlaneHelperMaterial=s,this.sectionPlaneHelper=r,this.sectionPlaneOutlineGeometry=i,this.sectionPlaneOutlineMaterial=a,this.sectionPlaneOutline=o,this.sectionPlaneFillGeometry=u,this.sectionPlaneFillMaterial=l,this.sectionPlaneFill=c,this.sectionBoxFillGeometry=d,this.sectionBoxFillMaterial=h,this.sectionBoxFill=f,this.sectionBoxHelperGeometry=m,this.sectionBoxHelperMaterial=g,this.sectionBoxHelper=w}updateSectionHelpers(e){if(this.ensureSectionHelpers(),!(!this.sectionPlaneHelper||!this.sectionPlaneOutline||!this.sectionPlaneFill||!this.sectionBoxFill||!this.sectionBoxHelper||!this.modelGroup)){if(!(e!=null&&e.active)){this.sectionPlaneHelper.visible=false,this.sectionPlaneOutline.visible=false,this.sectionPlaneFill.visible=false,this.sectionBoxFill.visible=false,this.sectionBoxHelper.visible=false;return}if(e.mode==="box"){this.sectionPlaneHelper.visible=false,this.sectionPlaneOutline.visible=false,this.sectionPlaneFill.visible=false,this.updateSectionBoxHelper(e),this.updateSectionBoxFill(e),this.sectionBoxHelper.visible=true;return}}}updateSectionPlaneMesh(e){if(!this.sectionPlaneHelper)return;const t=di(e,this.sectionBounds),s=Math.max(t.width,.001)*1.02,r=Math.max(t.height,.001)*1.02;switch(this.sectionPlaneHelper.position.set(0,0,0),this.sectionPlaneHelper.rotation.set(0,0,0),e.axis){case"x":this.sectionPlaneHelper.position.x=e.offset,this.sectionPlaneHelper.rotation.y=Math.PI/2;break;case"y":this.sectionPlaneHelper.position.y=e.offset,this.sectionPlaneHelper.rotation.x=Math.PI/2;break;case"z":default:this.sectionPlaneHelper.position.z=e.offset;break}this.sectionPlaneHelper.scale.set(s,r,1)}updateSectionPlaneDetail(e){if(!this.sectionPlaneOutlineGeometry||!this.sectionPlaneOutline||!this.sectionPlaneFill||!this.modelGroup)return;const t=this.resolveSectionHelperCacheEntry(e),s=t!=null&&t.outlinePoints.length?t.outlinePoints:hi(e,this.sectionBounds),r=this.sectionPlaneOutlineGeometry.getAttribute("position"),i=s.length/3;if(r.count!==i)this.sectionPlaneOutlineGeometry.setAttribute("position",new Z(s,3)),this.sectionPlaneOutlineGeometry.computeBoundingSphere();else{for(let o=0;o<s.length;o+=3)r.setXYZ(o/3,s[o],s[o+1],s[o+2]);r.needsUpdate=true,this.sectionPlaneOutlineGeometry.computeBoundingSphere()}this.sectionPlaneOutline.visible=true;const a=t!=null&&t.fillData?yi(t.fillData):void 0;if(!a){this.sectionPlaneFill.visible=false;return}this.replaceSectionPlaneFillGeometry(a),this.sectionPlaneFill.visible=true}resolveSectionHelperCacheEntry(e){const t=Ue(e),s=this.sectionHelperCache.get(t);if(s)return this.sectionHelperCache.delete(t),this.sectionHelperCache.set(t,s),s;const r=Ai(e,this.sectionSourceGeometry,this.modelGroup);if(!r.length)return;const i=fi(e.axis,r),a={outlinePoints:i.loops.length||i.chains.length?[...i.loops.flatMap(o=>Be(o)),...i.chains.flatMap(o=>mi(o))]:r,fillData:i.loops.length?bi(e.axis,i.loops):void 0};for(this.sectionHelperCache.set(t,a);this.sectionHelperCache.size>Os;){const o=this.sectionHelperCache.keys().next().value;if(typeof o!="string")break;this.sectionHelperCache.delete(o)}return a}clearSectionHelperCache(){this.sectionHelperCache.clear(),this.appliedSectionHelperKey=null,this.appliedSectionClippingKey=null,this.lastSectionHelperUpdateAt=Number.NEGATIVE_INFINITY}replaceSectionPlaneFillGeometry(e){if(!this.sectionPlaneFill){e.dispose();return}const t=this.sectionPlaneFillGeometry;this.sectionPlaneFill.geometry=e,this.sectionPlaneFillGeometry=e,t==null||t.dispose()}replaceSectionBoxFillGeometry(e){if(!this.sectionBoxFill){e.dispose();return}const t=this.sectionBoxFillGeometry;this.sectionBoxFill.geometry=e,this.sectionBoxFillGeometry=e,t==null||t.dispose()}updateSectionBoxFill(e){if(!this.sectionBoxFill)return;const t=vi(e,this.sectionBounds);if(!t){this.sectionBoxFill.visible=false;return}this.replaceSectionBoxFillGeometry(t),this.sectionBoxFill.visible=true}updateSectionBoxHelper(e){if(!this.sectionBoxHelperGeometry)return;const t=e.range??xe(this.sectionBounds),[s,r]=t.x,[i,a]=t.y,[o,u]=t.z,l=[[s,i,o],[r,i,o],[r,a,o],[s,a,o],[s,i,u],[r,i,u],[r,a,u],[s,a,u]],c=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],d=[];for(const[f,m]of c)d.push(...l[f],...l[m]);const h=this.sectionBoxHelperGeometry.getAttribute("position");for(let f=0;f<d.length;f+=3)h.setXYZ(f/3,d[f],d[f+1],d[f+2]);h.needsUpdate=true,this.sectionBoxHelperGeometry.computeBoundingSphere()}findNodeObject(e){var s;let t;return(s=this.modelGroup)==null||s.traverse(r=>{const i=r;i.userData.previewNodeId===e&&(t=i)}),t}applyNodeVisibility(e,t){e.traverse(s=>{const r=s;r.userData.previewOriginalVisible=t,s.visible=t})}focusNode(e){if(!this.modelGroup)return;if(!e){if(this.state.isolatedMaterialKey){const o=Xr(this.modelGroup);if(!o.isEmpty()){const u=o.getCenter(new E),l=o.getSize(new E);this.modelRadius=Math.max(l.length()/2,.5),this.distance=Math.max(this.modelRadius*2.6,this.baseDistance*.24),this.modelGroup.position.copy(this.baseModelGroupPosition).sub(u),this.updateCamera();return}}const a=this.state.explode??0;this.modelRadius=this.baseModelRadius+this.maxExplodeOffset*a,this.distance=Math.max(this.modelRadius*1.25,this.modelRadius*2.6/this.state.scale),this.modelGroup.position.copy(this.baseModelGroupPosition),this.updateCamera();return}let t;if(this.modelGroup.traverse(a=>{a.userData.previewNodeId===e&&(t=a)}),!t)return;const s=new te().setFromObject(t);if(s.isEmpty())return;const r=s.getCenter(new E),i=s.getSize(new E);this.modelRadius=Math.max(i.length()/2,.5),this.distance=Math.max(this.modelRadius*2.6,this.baseDistance*.24),this.modelGroup.position.copy(this.baseModelGroupPosition).sub(r),this.updateCamera()}applyAppearanceState(){var e;(e=this.modelGroup)==null||e.traverse(t=>{const s=t;if(typeof s.userData.previewOriginalVisible!="boolean"&&(s.userData.previewOriginalVisible=t.visible),s.userData.previewMeasurementHelper)return;if(s.userData.previewEdgeHelper){const a=this.findObjectById(s.userData.previewEdgeSourceId),o=a?!!a.userData.previewOriginalVisible&&this.matchesActiveMaterialFilter(a):true;t.visible=s.userData.previewOriginalVisible&&o&&this.displayMode!=="shaded",this.applySelectionMaterialState(t,{emphasized:false,dimmed:!!(this.state.selectedNodeId&&a&&a.userData.previewNodeId!==this.state.selectedNodeId)});return}const r=!!(this.state.selectedNodeId&&s.userData.previewNodeId===this.state.selectedNodeId),i=!!(this.state.selectedNodeId&&s.userData.previewNodeId&&s.userData.previewNodeId!==this.state.selectedNodeId);t.visible=s.userData.previewOriginalVisible&&this.matchesActiveMaterialFilter(t),this.applySelectionMaterialState(t,{emphasized:r&&t.visible,dimmed:i&&t.visible})})}matchesActiveMaterialFilter(e){const t=this.state.isolatedMaterialKey;if(!t)return true;const s=ft(e);return s.length?s.includes(t):true}captureMaterialRuntimeState(e){e.traverse(t=>{const s=t,r=Array.isArray(s.material)?s.material:s.material?[s.material]:[];for(const i of r)this.materialRuntimeState.has(i)||this.materialRuntimeState.set(i,{opacity:i.opacity,transparent:i.transparent,wireframe:"wireframe"in i?!!i.wireframe:void 0,depthWrite:i.depthWrite,...i instanceof V?{emissiveHex:i.emissive.getHex(),emissiveIntensity:i.emissiveIntensity}:{}})})}applySelectionMaterialState(e,t){const s=e,r=Array.isArray(s.material)?s.material:s.material?[s.material]:[];for(const i of r){const a=this.materialRuntimeState.get(i)??{opacity:i.opacity,transparent:i.transparent,wireframe:"wireframe"in i?!!i.wireframe:void 0,depthWrite:i.depthWrite},o=this.displayMode==="xray"?Math.min(a.opacity,.26):a.opacity,u=a.transparent||o<1,l=this.displayMode==="xray"?false:a.depthWrite??true;if(i instanceof V){i.wireframe=this.displayMode==="wireframe",i.emissive.setHex(t.emphasized?1920728:a.emissiveHex??0),i.emissiveIntensity=t.emphasized?Math.max(a.emissiveIntensity??0,.42):a.emissiveIntensity??0,i.opacity=t.dimmed?Math.min(o,.28):o,i.transparent=u||i.opacity<1,i.depthWrite=l,i.needsUpdate=true;continue}(i instanceof ne||i instanceof Pe)&&(i.opacity=t.dimmed?Math.min(o,.24):o,i.transparent=u||i.opacity<1,i.depthWrite=l,i.needsUpdate=true)}}attachEdgeHelpers(e){e.traverse(t=>{if(!(t instanceof $||t instanceof Ee))return;const s=t.geometry;if(!s||!s.getAttribute("position"))return;const r=new Mt(s,35),i=new ne({color:14412542,transparent:true,opacity:.22,depthWrite:false}),a=new Q(r,i);a.renderOrder=2,a.userData.previewEdgeHelper=true,a.userData.previewEdgeSourceId=t.id,a.userData.previewOriginalVisible=t.visible,t.add(a)})}findObjectById(e){if(!this.modelGroup||typeof e!="number")return;let t;return this.modelGroup.traverse(s=>{!t&&s.id===e&&(t=s)}),t}applySceneBackground(e){const t=this.renderer,s=this.scene;if(!t||!s)return()=>{};const r=s.background;switch(e){case"white":s.background=new de(16777215),t.setClearColor(16777215,1);break;case"transparent":s.background=null,t.setClearColor(0,0);break;default:s.background=new de(1120295),t.setClearColor(1120295,1);break}return()=>{s.background=r,t.setClearColor(1120295,1)}}disposeScene(){var e,t,s,r,i;this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=0),(e=this.resizeObserver)==null||e.disconnect(),this.resizeObserver=null,window.removeEventListener("resize",this.resize),(t=this.interactionController)==null||t.abort(),this.interactionController=null,he(this.modelGroup,[this.geometry,this.edgeGeometry,this.measurementLineGeometry,this.measurementPointsGeometry,this.sectionPlaneHelperGeometry,this.sectionPlaneOutlineGeometry,this.sectionPlaneFillGeometry,this.sectionBoxFillGeometry,this.sectionBoxHelperGeometry],[this.material,this.edgeMaterial,this.measurementLineMaterial,this.measurementPointsMaterial,this.sectionPlaneHelperMaterial,this.sectionPlaneOutlineMaterial,this.sectionPlaneFillMaterial,this.sectionBoxFillMaterial,this.sectionBoxHelperMaterial]),this.renderer&&(this.renderer.clippingPlanes=[],this.renderer.localClippingEnabled=false),(s=this.renderer)==null||s.dispose(),this.stage.replaceChildren(),this.renderer=null,this.scene=null,this.camera=null,this.modelGroup=null,this.geometry=null,this.edgeGeometry=null,this.material=null,this.edgeMaterial=null,this.measurementLineGeometry=null,this.measurementLineMaterial=null,this.measurementLine=null,this.measurementPointsGeometry=null,this.measurementPointsMaterial=null,this.measurementPoints=null,this.sectionHelperGroup=null,this.sectionPlaneHelper=null,this.sectionPlaneHelperGeometry=null,this.sectionPlaneHelperMaterial=null,this.sectionPlaneOutlineGeometry=null,this.sectionPlaneOutlineMaterial=null,this.sectionPlaneOutline=null,this.sectionPlaneFillGeometry=null,this.sectionPlaneFillMaterial=null,this.sectionPlaneFill=null,this.sectionBoxFillGeometry=null,this.sectionBoxFillMaterial=null,this.sectionBoxFill=null,this.sectionBoxHelperGeometry=null,this.sectionBoxHelperMaterial=null,this.sectionBoxHelper=null,this.measurementHoverClientX=null,this.measurementHoverClientY=null,this.clearSectionHelperCache(),this.sectionBounds=Ge(),this.explodeTargets=[],this.maxExplodeOffset=0,this.materialRuntimeState=new WeakMap,this.state.modelTree=void 0,this.state.selectedNodeId=void 0,this.state.isolatedMaterialKey=void 0,this.state.measurement={active:false,status:"idle",snapMode:((r=this.state.measurement)==null?void 0:r.snapMode)??"surface",axisLock:((i=this.state.measurement)==null?void 0:i.axisLock)??"free"},this.state.section=ue(),this.state.capabilities.measure=false,this.state.capabilities.section=false,this.state.capabilities.explode=false,this.state.capabilities.materialFilter=false}emit(e,t){for(const s of this.listeners[e])s(t)}}function F(n){if(n!=null&&n.aborted)throw new DOMException("3D preview aborted.","AbortError")}function j(n,e,t){return e?new Promise((s,r)=>{let i=false;const a=()=>{i||(i=true,e.removeEventListener("abort",a),r(new DOMException("3D preview aborted.","AbortError")))};e.addEventListener("abort",a,{once:true}),e.aborted&&a(),n.then(o=>{if(i){t==null||t(o);return}i=true,e.removeEventListener("abort",a),s(o)},o=>{i||(i=true,e.removeEventListener("abort",a),r(o))}).catch(()=>{})}):n}function he(n,e=[],t=[]){const s=new Set(e.filter(l=>!!l)),r=new Set(t.filter(l=>!!l)),i=new Set,a=new Set,o=new Set;for(const l of Array.isArray(n)?n:n?[n]:[])l.traverse(c=>{const d=c;d.geometry&&s.add(d.geometry);for(const h of Array.isArray(d.material)?d.material:d.material?[d.material]:[])r.add(h);if(d.skeleton&&a.add(d.skeleton),Array.isArray(c.userData.previewObjectUrls)){for(const h of c.userData.previewObjectUrls)typeof h=="string"&&h.startsWith("blob:")&&o.add(h);delete c.userData.previewObjectUrls}});const u=l=>{l&&typeof l=="object"&&l.isTexture?i.add(l):Array.isArray(l)&&l.forEach(u)};for(const l of r){Object.values(l).forEach(u);const c=l.uniforms;if(c)for(const d of Object.values(c))u(d.value)}for(const l of a)l.boneTexture&&i.delete(l.boneTexture),l.dispose();for(const l of s)l.dispose();for(const l of r)l.dispose();for(const l of i)l.dispose();for(const l of o)URL.revokeObjectURL(l)}function ta(){return{id:"model3d",family:"model3d",supports:n=>ct.has(Sn(n)),createSession:(n,e)=>new Rs(n,e)}}function na(n=_n()){return[...ks,...n.filter(e=>!e.extensions.some(t=>ct.has(t)))]}function Ts(n){const e=new Uint8Array(n);return Bi(e)?Tr(e):Rr(new TextDecoder().decode(e))}function Is(n){const e=[],t=[],s=[],r=[],i=[],a=[];for(const o of n.split(/\r?\n/)){const u=o.trim();if(!u||u.startsWith("#"))continue;const l=u.split(/\s+/);if(l[0]==="v"){e.push([G(l[1]),G(l[2]),G(l[3])]),t.push(jr(l));continue}if(l[0]==="vn"){s.push(ln([G(l[1]),G(l[2]),G(l[3])]));continue}if(l[0]!=="f"||l.length<4)continue;const c=l.slice(1).map(d=>zr(d,e.length,s.length)).filter(Boolean);if(!(c.length<3))for(let d=1;d<c.length-1;d+=1)Hr(c[0],c[d],c[d+1],e,t,s,r,i,a)}if(!r.length)throw new Error("No OBJ triangles found.");return Fe(r,i,a.length===r.length?a:void 0)}async function Bs(n,e={}){F(e.signal);const t=sn(n);if(!t.length||!e.resourceResolver)return{object:new Ct().parse(n),warnings:[]};const s=[],r=[],i=[];let a=null,o;try{for(const l of t){const c=Ae(await dt(e.resourceResolver,{source:K(X(e.resourceBasePath??""),l),fallbackSource:l,relation:"material",sourceFormat:e.sourceFormat??"obj"},e.signal));if(F(e.signal),r.push(...c.warnings),!c.source){r.push(`OBJ material library "${l}" could not be resolved; materials were skipped.`);continue}const d=await Pn(c.source,e.signal);F(e.signal);const h=await yr(d,l,e,i);r.push(...h.warnings),s.push(h.text)}F(e.signal);const u=new Ct;if(s.length){const l=new fe,c=new Promise(d=>{l.onLoad=d});l.onError=()=>{r.push("An OBJ texture failed to load; the preview may be incomplete.")},l.itemStart("filens:obj-parse");try{o=new Xn(l).parse(s.join(`
6
+ `),""),u.setMaterials(o),a=u.parse(n)}finally{l.itemEnd("filens:obj-parse")}await j(c,e.signal),F(e.signal),zs(a,Object.values(o.materials))}else a=u.parse(n);return{object:a,warnings:r}}catch(u){throw he(a,[],Object.values((o==null?void 0:o.materials)??{})),u}finally{for(const u of i)URL.revokeObjectURL(u)}}function zs(n,e){const t=new Set,s=new Set;n.traverse(r=>{const i=r.material;for(const a of Array.isArray(i)?i:i?[i]:[])t.add(a)});for(const r of t)for(const i of Object.values(r))i!=null&&i.isTexture&&s.add(i);for(const r of e)if(!t.has(r)){for(const i of Object.values(r))i!=null&&i.isTexture&&!s.has(i)&&(s.add(i),i.dispose());r.dispose()}}function sn(n){const e=[];for(const t of n.split(/\r?\n/)){const s=t.trim();if(!s||s.startsWith("#"))continue;const r=/^mtllib\s+(.+)$/i.exec(s);if(r!=null&&r[1])for(const i of r[1].trim().split(/\s+/))i&&e.push(i)}return[...new Set(e)]}function Hs(n){const e=new Uint8Array(n),t=Gr(e);if(t.format==="ascii")return Ur(new TextDecoder().decode(e.slice(t.dataOffset)),t);if(t.format==="binary_little_endian")return _r(e,t);throw new Error(`Unsupported PLY format "${t.format}".`)}async function js(n,e={}){F(e.signal);const t=await j(fs.loadAsync(n),e.signal);F(e.signal);const s=t.file("3D/3dmodel.model")??t.file(/(^|\/)3dmodel\.model$/i)[0];if(!s)throw new Error("3MF package is missing 3D/3dmodel.model.");const r=[s,...Object.values(t.files).filter(p=>!p.dir&&/\.model$/i.test(p.name)&&p.name!==s.name)],i=[];for(const p of r){const b=await j(p.async("text"),e.signal);F(e.signal);const y=new DOMParser().parseFromString(b,"application/xml");if(y.getElementsByTagName("parsererror")[0]){if(p===s)throw new Error("3MF model XML is invalid.");continue}i.push(y)}const a=new Map,o=new Set;for(const p of i){for(const[b,y]of Ir(p))a.has(b)||a.set(b,y);for(const b of Br(p))o.add(b)}const u=new Set,l=new Map,c=new Map;for(const p of i)for(const b of W(p,"object")){const y=b.getAttribute("id");if(!y)continue;const C=W(b,"mesh")[0],P=c.has(y);if(C){const S=W(C,"vertex").map(N=>[G(N.getAttribute("x")??void 0),G(N.getAttribute("y")??void 0),G(N.getAttribute("z")??void 0)]),L=[],k=[],D=zt(b.getAttribute("pid"),b.getAttribute("pindex"),a);Bt(b.getAttribute("pid"),a,u);for(const N of W(C,"triangle")){const v=["v1","v2","v3"].map(x=>Number(N.getAttribute(x))).filter(x=>Number.isInteger(x)&&x>=0&&x<S.length);if(v.length!==3)continue;const O=N.getAttribute("pid")??b.getAttribute("pid");Bt(O,a,u);const A=["p1","p2","p3"].map(x=>zt(O,N.getAttribute(x)??N.getAttribute("pindex")??b.getAttribute("pindex"),a)??D??[.49,.83,.99]);L.push(S[v[0]],S[v[1]],S[v[2]]),k.push(...A)}L.length&&!P&&c.set(y,{positions:L,colors:k})}(!l.has(y)||!P&&c.has(y))&&l.set(y,b)}for(const p of l.keys())an(p,l,c,new Set);const d=i[0],h=[],f=[],m=[],g=W(d,"item"),w=g.length?g:[...c.keys()].map(p=>({objectId:p}));for(const p of w){const b=p instanceof Element?p.getAttribute("objectid"):p.objectId,y=b?c.get(b):void 0;if(!(y!=null&&y.positions.length))continue;const C=p instanceof Element?on(p.getAttribute("transform")):it;for(let P=0;P<y.positions.length;P+=3){const S=Ie(y.positions[P],C),L=Ie(y.positions[P+1],C),k=Ie(y.positions[P+2],C),D=mt(S,L,k),N=[y.colors[P]??[.49,.83,.99],y.colors[P+1]??[.49,.83,.99],y.colors[P+2]??[.49,.83,.99]];for(const v of[S,L,k])h.push(...v),f.push(...D);for(const v of N)m.push(...v)}}if(!h.length)throw new Error("No 3MF mesh triangles found.");for(const p of Array.from(u).map(b=>`3MF material resource "${b}" is not a supported color palette; fallback vertex colors were used.`))o.add(p);return{geometry:Fe(h,f,m),warnings:[...o]}}async function Gs(n,e={}){return rn(n,"",e.signal)}async function rn(n,e,t){F(t);const s=new ws,r=a=>{var o;return he((o=a.scenes)!=null&&o.length?a.scenes:[a.scene])},i=await j(s.parseAsync(n,e),t,r);return t!=null&&t.aborted&&(r(i),F(t)),i.scene}function Us(n){return new Zn().parse(n)}function _s(n,e={}){const t=[],s=[],r=new fe;e.resourceResolver&&r.setURLModifier(a=>Fr(a,e,s,t));const i=new nn(r).parse(n,e.resourcePath??"").scene;return t.length&&(i.userData.previewObjectUrls=t),{object:i,warnings:s}}async function Vs(n,e={}){var h,f;F(e.signal);const t=await j(Vn(new Uint8Array(n)),e.signal);F(e.signal);const s=Ks([...t.values()].filter(m=>!m.directory).map(m=>m.name)),r=Ys(s),i=r?await j(t.get(r).text(),e.signal):void 0;F(e.signal);const a=[],o=Xs(s,r,i,a),u=await j(t.get(o).text(),e.signal);F(e.signal);const l=new DOMParser().parseFromString(u,"application/xml");if(l.getElementsByTagName("parsererror").length)throw new Error("KMZ Collada XML is invalid.");const c=new Map;for(const m of Array.from(l.getElementsByTagName("*"))){if(m.localName!=="image")continue;const g=(f=(h=Array.from(m.children).find(p=>p.localName==="init_from"))==null?void 0:h.textContent)==null?void 0:f.trim();if(!g)continue;const w=ut(s,g,o);w&&!c.has(w)&&(c.set(w,await j(t.get(w).bytes(),e.signal)),F(e.signal))}const d=$s(u,o,s,m=>c.get(m),a,e.signal);try{return await j(d.ready,e.signal),F(e.signal),{object:d.object,warnings:a}}catch(m){throw d.release(),he(d.object),m}finally{d.release()}}function $s(n,e,t,s,r,i){F(i);const a=new fe,o=[],u=new Map;let l;const c=()=>{for(const h of o.splice(0))URL.revokeObjectURL(h);(l==null?void 0:l.userData.previewObjectUrls)===o&&delete l.userData.previewObjectUrls},d=new Promise(h=>{a.onLoad=()=>{c(),h()}});a.onError=()=>{r.push("A KMZ texture failed to load; the preview may be incomplete.")},a.setURLModifier(h=>{F(i);const f=ut(t,h,e),m=u.get(f??h);if(m)return m;const g=f?s(f):void 0;if(g){const w=new Uint8Array(g.byteLength);w.set(g);const p=URL.createObjectURL(new Blob([w.buffer],{type:qs(f)}));return u.set(f,p),o.push(p),p}return/^[a-z][a-z\d+.-]*:/i.test(h)&&!/^file:/i.test(h)?h:(r.push(`KMZ texture "${h}" could not be resolved; dependent appearance may be missing.`),'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"%3E%3Cpath fill="white" d="M0 0h1v1H0z"/%3E%3C/svg%3E')}),a.itemStart("filens:kmz-parse");try{l=new nn(a).parse(n,"").scene,o.length&&(l.userData.previewObjectUrls=o),Ws(l)||r.push("KMZ Collada model contains no renderable geometry.")}catch(h){throw c(),h}finally{a.itemEnd("filens:kmz-parse")}return{object:l,ready:d,release:c}}function Ws(n){let e=false;return n.traverse(t=>{var s,r;(r=(s=t.geometry)==null?void 0:s.getAttribute("position"))!=null&&r.count&&(e=true)}),e}function rt(n){const e=[];for(const t of n.replace(/\\/g,"/").split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return e.join("/")}function Ks(n){return new Map(n.map(e=>[rt(e),e]))}function ut(n,e,t=""){let s=e.trim().replace(/\\/g,"/").split(/[?#]/,1)[0]??"";if(/^[a-z][a-z\d+.-]*:/i.test(s))return;try{s=decodeURIComponent(s)}catch{}const r=t.slice(0,t.lastIndexOf("/")+1),i=[...new Set([...s.startsWith("/")?[]:[rt(r+s)],rt(s)])];for(const u of i){const l=n.get(u);if(l)return l}for(const u of i){const l=[...n].filter(([c])=>c.toLowerCase()===u.toLowerCase());if(l.length===1)return l[0][1]}const a=i[i.length-1].toLowerCase(),o=[...n].filter(([u])=>u.toLowerCase().endsWith("/"+a));return o.length===1?o[0][1]:void 0}function Ys(n){return n.get("doc.kml")??[...n.values()].find(e=>/^doc\.kml$/i.test(e))??[...n.values()].find(e=>/(^|\/)doc\.kml$/i.test(e))??[...n.values()].find(e=>/\.kml$/i.test(e))}function Xs(n,e,t,s){const r=t?Zs(t):void 0,i=r?ut(n,r,e):void 0,a=[...n.values()].find(u=>/\.dae$/i.test(u));r&&!i&&a&&s.push(`KMZ model "${r}" could not be resolved; using "${a}".`);const o=i??a;if(!o)throw new Error("KMZ archive does not contain a Collada (.dae) model.");return o}function Zs(n){var t,s,r;const e=new DOMParser().parseFromString(n,"application/xml");if(!e.getElementsByTagName("parsererror").length)for(const i of Array.from(e.getElementsByTagName("*"))){if(((t=i.localName)==null?void 0:t.toLowerCase())!=="model")continue;const a=Array.from(i.children).find(u=>u.localName.toLowerCase()==="link"),o=a&&((r=(s=Array.from(a.children).find(u=>u.localName.toLowerCase()==="href"))==null?void 0:s.textContent)==null?void 0:r.trim());if(o&&/\.dae(?:[?#].*)?$/i.test(o))return o}}function qs(n){var t;switch((t=n.split(".").pop())==null?void 0:t.toLowerCase()){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"bmp":return"image/bmp";case"tga":return"image/x-tga";case"dds":return"image/vnd-ms.dds";default:return"application/octet-stream"}}function Js(n){const e=new ls().parse(n);if(!e)throw new Error("Invalid MD2 model data.");return e.hasAttribute("normal")||e.computeVertexNormals(),new $(e,new V({color:8246268,roughness:.58,metalness:.04}))}function Qs(n,e={}){const t=[],s=[],r=new fe;e.resourceResolver&&r.setURLModifier(u=>Lr(u,e,s,t));const a=new cs(r).parse(n,e.resourcePath??"",e.modelName??"model"),o=new ee;for(const u of a.meshes??[])o.add(u);if(!o.children.length){for(const u of t)URL.revokeObjectURL(u);throw new Error("No LWO meshes found.")}return t.length&&(o.userData.previewObjectUrls=t),{object:o,warnings:s}}function er(n){const t=new us().parse(n).skeleton.bones[0];if(!t)throw new Error("No BVH skeleton bones found.");const s=new ee;s.add(t);const r=new ds(t),i=r.material;for(const a of Array.isArray(i)?i:[i])a.color.set(8246268);return s.add(r),s}function tr(n){var s,r;const e=new hs().parse(n),t=new ee;if((s=e.geometryAtoms.getAttribute("position"))!=null&&s.count&&t.add(new me(e.geometryAtoms,new Pe({size:.6,color:16777215,vertexColors:true}))),(r=e.geometryBonds.getAttribute("position"))!=null&&r.count&&t.add(new Q(e.geometryBonds,new ne({color:14412542,transparent:true,opacity:.72}))),!t.children.length)throw new Error("No PDB atoms found.");return t}function nr(n){const e=Pr(n),t=new ms().parse(e.buffer),s=t.xLength*t.yLength*t.zLength;if(!Number.isSafeInteger(s)||s<1||t.data.length!==s)throw new Error("NRRD voxel data length does not match its dimensions.");if((e.encoding==="raw"||e.encoding==="gz"||e.encoding==="gzip")&&e.endian){const m=new Uint8Array(new Uint16Array([1]).buffer)[0]===1?"little":"big";if(e.endian!==m){const g=new Uint8Array(t.data.buffer,t.data.byteOffset,t.data.byteLength),w=t.data.BYTES_PER_ELEMENT;for(let p=0;p<g.length;p+=w)for(let b=p,y=p+w-1;b<y;b++,y--){const C=g[b];g[b]=g[y],g[y]=C}}}const[r,i]=t.computeMinMax(),a=i-r,o=r<=0&&i>0?0:a>0?r+a*.5:r,l=Math.max(1,Math.ceil(s/6e4)),c=t.spacing.length>=3?t.spacing:[1,1,1],d=[],h=[];for(let m=0;m<s;m+=l){const g=Number(t.data[m]);if(!Number.isFinite(g)||g<o)continue;const w=m%t.xLength,p=Math.floor(m/t.xLength),b=p%t.yLength,y=Math.floor(p/t.yLength);d.push(w*c[0],b*c[1],y*c[2]);const C=a>0?_((g-r)/a,0,1):1;h.push(.22+C*.64,.3+C*.55,.4+C*.52)}if(!d.length)throw new Error("No NRRD voxels passed the preview threshold.");const f=new Y;return f.setAttribute("position",new Z(d,3)),f.setAttribute("color",new Z(h,3)),new me(f,new Pe({size:Math.max(Math.min(...c.filter(m=>m>0)),1)*.75,vertexColors:true}))}async function sr(n,e={}){F(e.signal);const t=Sr(n);if(!t)return new TextEncoder().encode(n).buffer;const s=e.resourceResolver;if(!s)throw new Error(`NHDR references external data file "${t}" but no resourceResolver was provided.`);const r=X(e.resourceBasePath??""),i=Ae(await dt(s,{source:K(r,t),fallbackSource:t,relation:"volume",sourceFormat:e.sourceFormat??"nhdr"},e.signal));if(!i.source)throw new Error(`NHDR external data file "${t}" could not be resolved.`);const a=await ht(i.source,e.signal);return F(e.signal),Cr(n,a)}function rr(n,e={}){const t=[],s=[],r=new fe;e.resourceResolver&&r.setURLModifier(a=>Ar(a,e,s,t));const i=new qn(r).parse(n,e.resourcePath??"");return t.length&&(i.userData.previewObjectUrls=t),{object:i,warnings:s}}function ir(n,e={}){const t=[],s=[],r=new fe;e.resourceResolver&&r.setURLModifier(a=>Dr(a,e,s,t));const i=new Jn(r).parse(n,e.resourcePath??"");return t.length&&(i.userData.previewObjectUrls=t),{object:i,warnings:s}}async function ar(n){return new Qn().parse(n)}async function or(n,e={}){var a;if(F(e.signal),!Me){const o=Promise.resolve().then(()=>Zi).then(({createRustStepImporter:u})=>u());Me=o,o.catch(()=>{Me===o&&(Me=null)})}const t=await j(Me,e.signal);F(e.signal);const s=t.ReadStepFile(new Uint8Array(n),{linearUnit:"millimeter"},e.signal),r=await j(Promise.resolve(s),e.signal);if(F(e.signal),!r.success||!r.root||!((a=r.meshes)!=null&&a.length))throw new Error("Rust STEP could not read this STEP file.");const i=new ee;i.userData.stepEngine="rust",i.userData.previewWarnings=r.warnings??[];for(const o of r.root.meshes){const u=r.meshes[o];if(!u)continue;const l=new Y;l.setAttribute("position",new Z(u.attributes.position.array,3)),u.attributes.normal?l.setAttribute("normal",new Z(u.attributes.normal.array,3)):l.computeVertexNormals(),u.index&&l.setIndex(u.index.array),i.add(new $(l,new V({color:new de(.72,.76,.82),side:Te})))}return i}function lr(n){return new es().parse(n)}function cr(n,e={}){const t=[],s=[],r=new fe;e.resourceResolver&&r.setURLModifier(a=>Er(a,e,s,t));const i=new ts(r).parse(n,e.resourcePath??"");return t.length&&(i.userData.previewObjectUrls=t),{object:i,warnings:s}}function ur(n){return new ns().parse(n)}function dr(n){const e=new ss().parse(n),t=e.hasAttribute("color");return new me(e,new Pe({size:.08,color:t?16777215:8246268,vertexColors:t}))}function hr(n){const e=new rs().parse(mr(n),"");return e.hasAttribute("normal")||e.computeVertexNormals(),new $(e,new V({color:e.hasAttribute("color")?16777215:8246268,roughness:.58,metalness:.04,vertexColors:e.hasAttribute("color")}))}function mr(n){const e=typeof n=="string"?new TextEncoder().encode(n):new Uint8Array(n);if(e.byteLength>=Rt)return typeof n=="string"?e.buffer:n;const t=new Uint8Array(Rt);return t.fill(32),t.set(e),t[t.length-1]=10,t.buffer}function fr(n){const e=new is().parse(n),t=new ee;for(const s of e??[])s&&t.add(new as(s));return t}async function pr(n,e={}){var s;F(e.signal);const t=[];try{const r=await xr(n,e,t);F(e.signal);const i=new Ns;i.setConditionalLineMaterial(os),i.setMaterials([]);const a=new Promise((u,l)=>{i.parse(r,c=>u(c),c=>l(c))}),o=await j(a,e.signal,he);return(s=e.signal)!=null&&s.aborted&&(he(o),F(e.signal)),{object:o,warnings:t}}catch(r){throw t.length&&!(r&&typeof r=="object"&&"name"in r&&r.name==="AbortError")?new Error(`${r instanceof Error?r.message:String(r)} Warnings: ${t.join(" ")}`):r}}async function gr(n,e={}){F(e.signal);const t=[];try{const s=typeof n=="string"?n:new TextDecoder().decode(n),r=Ui(s),i=wr(r),a=i.length&&e.resourceResolver?await br(r,i,e,t):{json:r,warnings:[],unresolvedResources:i},o=a.unresolvedResources;if(o.length&&!e.resourcePath)throw new Error(`glTF references external resources that are not bundled with this preview: ${o.join(", ")}.`);return F(e.signal),{object:await rn(JSON.stringify(a.json),e.resourcePath??"",e.signal),warnings:a.warnings}}finally{for(const s of t)URL.revokeObjectURL(s)}}function wr(n){if(!n||typeof n!="object")return[];const e=n,t=[...(e.buffers??[]).map(s=>s.uri),...(e.images??[]).filter(s=>s.bufferView==null).map(s=>s.uri)];return[...new Set(t.filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.trim()).filter(s=>!_i(s)))]}async function br(n,e,t,s){var u;const r=Nr(n),i=[],a=new Map,o=[];for(const l of e){F(t.signal);const c=await j(Promise.resolve((u=t.resourceResolver)==null?void 0:u.call(t,{family:"model3d",sourceFormat:t.sourceFormat??"gltf",source:l,relation:kr(r,l),name:l.split(/[\\/]/).pop()??l})),t.signal);F(t.signal);const d=pe(c,Ln(l),s);i.push(...d.warnings),d.source?a.set(l,d.source):o.push(l)}return Or(r,a),{json:r,warnings:i,unresolvedResources:o}}async function yr(n,e,t,s){var o;const r=X(K(X(t.resourceBasePath??""),e)),i=[],a=[];for(const u of n.split(/\r?\n/)){const l=Mr(u);if(!l||!t.resourceResolver){i.push(u);continue}if((o=t.signal)!=null&&o.aborted)throw new DOMException("3D preview aborted.","AbortError");const c=await dt(t.resourceResolver,{source:K(r,l.path),fallbackSource:l.path,relation:"texture",sourceFormat:t.sourceFormat??"obj"},t.signal);F(t.signal);const d=pe(c,q(l.path),s);if(a.push(...d.warnings),!d.source){a.push(`OBJ texture "${l.path}" could not be resolved; the material map was left unchanged.`),i.push(u);continue}i.push(`${l.prefix}${d.source}`)}return{text:i.join(`
7
+ `),warnings:a}}async function dt(n,e,t){F(t);const s=await j(Promise.resolve(n({family:"model3d",sourceFormat:e.sourceFormat,source:e.source,relation:e.relation,name:e.source.split(/[\\/]/).pop()??e.source})),t);return F(t),Ae(s).source||e.fallbackSource===e.source?s:j(Promise.resolve(n({family:"model3d",sourceFormat:e.sourceFormat,source:e.fallbackSource,relation:e.relation,name:e.fallbackSource.split(/[\\/]/).pop()??e.fallbackSource})),t)}function vr(n,e){const t=[];let s=e,r=[],i=false,a=false;for(const o of n.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
8
+ `).split(`
9
+ `)){const u=/^\s*0\s+FILE\s+(.+?)\s*$/i.exec(o);u?(i&&(t.push({name:s,text:r.join(`
10
+ `)+`
11
+ `}),r=[]),s=u[1],i=true,a=false):/^\s*0\s+NOFILE\s*$/i.test(o)?a=true:a||r.push(o)}return t.push({name:s,text:r.join(`
12
+ `)+`
13
+ `}),t}async function xr(n,e,t){const s=X(e.resourceBasePath??""),r=new Map,i=new Map,a=new Map,o=f=>s&&f.startsWith(`${s}/`)?f.slice(s.length+1):f,u=(f,m,g,w)=>{const p=vr(f,g??"__filens_main__.ldr"),b=new Map;let y;for(let C=0;C<p.length;C++){const P=p[C],S=Xe(P.name),L=C===0&&w?o(w):Xe(g?o(K(m,S)):S),k=L.toLowerCase();let D=r.get(k);D||(D={name:L,text:P.text,directory:C===0&&g?m:X(K(m,S)),definitions:b},r.set(k,D)),b.set(S.toLowerCase(),D),C===0&&(y=D,g&&b.set(g.toLowerCase(),D))}return y},l=u(n,s),c=new Set,d=new Set,h=async f=>{if(F(e.signal),c.has(f))throw new Error(`Cyclic LDraw part reference: "${f.name}".`);if(d.has(f))return;c.add(f);const m=f.text.split(`
14
+ `);for(let g=0;g<m.length;g++){const w=/^(\s*1\s+(?:\S+\s+){13})(.+?)\s*$/.exec(m[g]);if(!w)continue;const p=Xe(w[2]),b=p.toLowerCase();let y=f.definitions.get(b)??l.definitions.get(b);if(!y&&e.resourceResolver){const C=/^(?:parts\/s|p\/48)\//i.test(p),P=[...new Set([K(C?s:f.directory,p),K(s,p),p])],S=P[0].toLowerCase();y=a.get(S);for(const L of P){if(y||(y=i.get(L.toLowerCase()),y))break;const k=Ae(await j(Promise.resolve(e.resourceResolver({family:"model3d",sourceFormat:e.sourceFormat??"ldr",source:L,relation:"part",name:L.split("/").pop()??L})),e.signal));if(F(e.signal),t.push(...k.warnings),!k.source)continue;const D=await Pn(k.source,e.signal);F(e.signal),y=u(D,X(L),p,L),i.set(L.toLowerCase(),y);break}y||(t.push(`LDraw part "${w[2]}" could not be resolved; dependent geometry may be missing.`),y=u(`0 !LDRAW_ORG Subpart
15
+ `,f.directory,p,P[0])),a.set(S,y)}y&&(m[g]=`${w[1]}${y.name}`,await h(y))}f.text=m.join(`
16
+ `),c.delete(f),d.add(f)};return await h(l),F(e.signal),[...new Set(r.values())].map(f=>`0 FILE ${f.name}
17
+ ${f.text}`).join(`
18
+ `)}function Mr(n){const e=/^(\s*(?:map_\S+|bump|norm|disp)\s+)(.+?)\s*$/i.exec(n);if(!(e!=null&&e[1])||!e[2])return;let t=e[1],s=e[2];const r={"-bm":1,"-mm":2,"-s":3,"-o":3};for(;;){const i=/^(\S+)\s+/.exec(s),a=i&&r[i[1]];if(!a)break;const o=new RegExp(`^\\S+(?:\\s+\\S+){${a}}\\s+`).exec(s);if(!o)break;t+=o[0],s=s.slice(o[0].length)}return s?{prefix:t,path:s}:void 0}function Sr(n){for(const e of n.split(/\r?\n/)){const t=e.trim();if(!t||t.startsWith("#"))continue;const s=/^data\s*file\s*:\s*(.+)$/i.exec(t)??/^datafile\s*:\s*(.+)$/i.exec(t);if(!(s!=null&&s[1]))continue;const r=s[1].trim();if(!r||/[\s%]/.test(r))throw new Error(`NHDR data file reference "${r}" is not supported for direct preview yet.`);return r}}function Cr(n,e){const t=n.split(/\r?\n/),s=[];let r=false,i=false;for(const c of t){if(!c.trim())break;if(/^\s*data\s*file\s*:/i.test(c)||/^\s*datafile\s*:/i.test(c)){r=true;continue}/^\s*encoding\s*:/i.test(c)&&(i=true),s.push(c)}if(!r)return new TextEncoder().encode(n).buffer;i||s.push("encoding: raw");const a=s.join(`
19
+ `).replace(/\s+$/,""),o=new TextEncoder().encode(`${a}
20
+ #
21
+
22
+ `),u=new Uint8Array(e),l=new Uint8Array(o.byteLength+u.byteLength);return l.set(o,0),l.set(u,o.byteLength),l.buffer}function Pr(n){const e=new Uint8Array(n);let t=0;for(let s=0;s<e.length;s++){if(e[s]!==10)continue;if((e[s-1]===13?s-1:s)!==t){t=s+1;continue}const i=new TextDecoder().decode(e.subarray(0,t)),a=new Map(i.split(/\r?\n/).flatMap(d=>{const h=/^([^:#]+):\s*(.*)$/.exec(d);return h?[[h[1].trim().toLowerCase(),h[2].trim().toLowerCase()]]:[]}));for(const d of["line skip","byte skip"])if(a.has(d)&&a.get(d)!=="0")throw new Error(`NRRD ${d} is not supported for preview.`);if(a.get("dimension")!=="3")throw new Error("NRRD preview requires three scalar dimensions.");const o=a.get("encoding");if(!["raw","gz","gzip","ascii","text","txt","hex"].includes(o??""))throw new Error(`NRRD encoding "${o??""}" is not supported for preview.`);const u=a.get("endian");if(u&&u!=="little"&&u!=="big")throw new Error(`Unsupported NRRD endian "${u}".`);if(!i.includes("\r")&&/\n#[^\n]*\n$/.test(i))return{buffer:n,encoding:o,endian:u};const l=new TextEncoder().encode(`${i.replace(/\r\n/g,`
23
+ `).trimEnd()}
24
+ #
25
+
26
+ `),c=new Uint8Array(l.length+e.length-s-1);return c.set(l),c.set(e.subarray(s+1),l.length),{buffer:c.buffer,encoding:o,endian:u}}return{buffer:n}}function Lr(n,e,t,s){var u;const r=e.resourceResolver;if(!r)return n;if((u=e.signal)!=null&&u.aborted)throw new DOMException("3D preview aborted.","AbortError");const i=X(e.resourceBasePath??""),a=n.replace(/\\/g,"/"),o=[K(i,a),a,a.split("/").pop()??a];for(const l of o){const c=r({family:"model3d",sourceFormat:e.sourceFormat??"lwo",source:l,relation:"texture",name:l.split(/[\\/]/).pop()??l});if(c&&!(c instanceof Promise)){const d=pe(c,q(l));if(t.push(...d.warnings),d.source){const h=ge(d.source,q(l));return h?(h.startsWith("blob:")&&s.push(h),h):(t.push(`LWO texture "${a}" resolved to an unsupported source type; default loader lookup was used.`),n)}}}return t.push(`LWO texture "${a}" could not be resolved; default loader lookup was used.`),n}function Er(n,e,t,s){var u;const r=e.resourceResolver;if(!r)return n;if((u=e.signal)!=null&&u.aborted)throw new DOMException("3D preview aborted.","AbortError");const i=X(e.resourceBasePath??""),a=n.replace(/\\/g,"/"),o=[K(i,a),a,a.split("/").pop()??a];for(const l of o){const c=r({family:"model3d",sourceFormat:e.sourceFormat??"vrml",source:l,relation:"texture",name:l.split(/[\\/]/).pop()??l});if(c&&!(c instanceof Promise)){const d=pe(c,q(l));if(t.push(...d.warnings),d.source){const h=ge(d.source,q(l));return h?(h.startsWith("blob:")&&s.push(h),h):(t.push(`VRML texture "${a}" resolved to an unsupported source type; default loader lookup was used.`),n)}}}return t.push(`VRML texture "${a}" could not be resolved; default loader lookup was used.`),n}function Fr(n,e,t,s){var u;const r=e.resourceResolver;if(!r)return n;if((u=e.signal)!=null&&u.aborted)throw new DOMException("3D preview aborted.","AbortError");const i=X(e.resourceBasePath??""),a=n.replace(/\\/g,"/"),o=[K(i,a),a,a.split("/").pop()??a];for(const l of o){const c=r({family:"model3d",sourceFormat:e.sourceFormat??"dae",source:l,relation:"texture",name:l.split(/[\\/]/).pop()??l});if(c&&!(c instanceof Promise)){const d=pe(c,q(l));if(t.push(...d.warnings),d.source){const h=ge(d.source,q(l));return h?(h.startsWith("blob:")&&s.push(h),h):(t.push(`Collada texture "${a}" resolved to an unsupported source type; default loader lookup was used.`),n)}}}return t.push(`Collada texture "${a}" could not be resolved; default loader lookup was used.`),n}function Ar(n,e,t,s){var u;const r=e.resourceResolver;if(!r)return n;if((u=e.signal)!=null&&u.aborted)throw new DOMException("3D preview aborted.","AbortError");const i=X(e.resourceBasePath??""),a=n.replace(/\\/g,"/"),o=[K(i,a),a,a.split("/").pop()??a];for(const l of o){const c=r({family:"model3d",sourceFormat:e.sourceFormat??"fbx",source:l,relation:"texture",name:l.split(/[\\/]/).pop()??l});if(c&&!(c instanceof Promise)){const d=pe(c,q(l));if(t.push(...d.warnings),d.source){const h=ge(d.source,q(l));return h?(h.startsWith("blob:")&&s.push(h),h):(t.push(`FBX texture "${a}" resolved to an unsupported source type; default loader lookup was used.`),n)}}}return t.push(`FBX texture "${a}" could not be resolved; default loader lookup was used.`),n}function Dr(n,e,t,s){var u;const r=e.resourceResolver;if(!r)return n;if((u=e.signal)!=null&&u.aborted)throw new DOMException("3D preview aborted.","AbortError");const i=X(e.resourceBasePath??""),a=n.replace(/\\/g,"/"),o=[K(i,a),a,a.split("/").pop()??a];for(const l of o){const c=r({family:"model3d",sourceFormat:e.sourceFormat??"3ds",source:l,relation:"texture",name:l.split(/[\\/]/).pop()??l});if(c&&!(c instanceof Promise)){const d=pe(c,q(l));if(t.push(...d.warnings),d.source){const h=ge(d.source,q(l));return h?(h.startsWith("blob:")&&s.push(h),h):(t.push(`3DS texture "${a}" resolved to an unsupported source type; default loader lookup was used.`),n)}}}return t.push(`3DS texture "${a}" could not be resolved; default loader lookup was used.`),n}function Xe(n){const e=n.replace(/\\/g,"/").replace(/^\.\//,"");return/^s\//i.test(e)?`parts/${e}`:/^48\//i.test(e)?`p/${e}`:e}function Nr(n){return JSON.parse(JSON.stringify(n))}function Or(n,e){if(!n||typeof n!="object")return;const t=n;for(const s of t.buffers??[]){const r=typeof s.uri=="string"?e.get(s.uri.trim()):void 0;r!==void 0&&(s.uri=r)}for(const s of t.images??[]){const r=typeof s.uri=="string"?e.get(s.uri.trim()):void 0;s.bufferView==null&&r!==void 0&&(s.uri=r)}}function kr(n,e){if(!n||typeof n!="object")return"resource";const t=n;return(t.buffers??[]).some(s=>s.uri===e)?"buffer":(t.images??[]).some(s=>s.bufferView==null&&s.uri===e)?"image":"resource"}async function ht(n,e){if(F(e),typeof n=="string"){const t=r=>{var i;(i=r.body)==null||i.cancel().catch(()=>{})},s=await j(fetch(n,{signal:e}),e,t);try{if(F(e),!s.ok)throw new Error(`Failed to load 3D source: ${s.status} ${s.statusText}`.trim());return await j(s.arrayBuffer(),e)}catch(r){throw t(s),r}}if(n instanceof Blob)return j(n.arrayBuffer(),e);if(ArrayBuffer.isView(n)){const t=new Uint8Array(n.byteLength);return t.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),t.buffer}if(n instanceof ArrayBuffer)return n.slice(0);throw new Error("Unsupported 3D source type.")}function Rr(n){const e=[],t=[];let s=[0,0,1];const r=[];for(const i of n.split(/\r?\n/)){const a=i.trim().split(/\s+/);if(a[0]==="facet"&&a[1]==="normal"){s=[G(a[2]),G(a[3]),G(a[4])];continue}if(a[0]==="vertex"&&(r.push([G(a[1]),G(a[2]),G(a[3])]),r.length===3))for(const o of r.splice(0,3))e.push(...o),t.push(...s)}if(!e.length)throw new Error("No STL triangles found.");return Fe(e,t)}function Tr(n){if(n.byteLength<84)throw new Error("Binary STL is too small.");const e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=e.getUint32(80,true);if(84+t*50>n.byteLength)throw new Error("Binary STL triangle data is truncated.");if(!t)throw new Error("No STL triangles found.");const r=new Float32Array(t*9),i=new Float32Array(t*9);let a=84;for(let o=0;o<t;o+=1){const u=e.getFloat32(a,true),l=e.getFloat32(a+4,true),c=e.getFloat32(a+8,true);a+=12;for(let d=0;d<3;d+=1){const h=o*9+d*3;r[h]=e.getFloat32(a,true),r[h+1]=e.getFloat32(a+4,true),r[h+2]=e.getFloat32(a+8,true),i[h]=u,i[h+1]=l,i[h+2]=c,a+=12}a+=2}return{positions:r,normals:i,triangleCount:t,bounds:hn(r)}}const it=[1,0,0,0,1,0,0,0,1,0,0,0];function W(n,e){return Array.from(n.querySelectorAll("*")).filter(t=>t.localName===e)}function It(n,e){return Array.from(n.children).filter(t=>t.localName===e)}function an(n,e,t,s){const r=t.get(n);if(r)return r;if(s.has(n))return;const i=e.get(n);if(!i)return;s.add(n);const a=It(i,"components")[0];if(!a){s.delete(n);return}const o=[],u=[];for(const c of It(a,"component")){const d=c.getAttribute("objectid"),h=d?an(d,e,t,s):void 0;if(!(h!=null&&h.positions.length))continue;const f=on(c.getAttribute("transform"));for(let m=0;m<h.positions.length;m+=1)o.push(Ie(h.positions[m],f)),u.push(h.colors[m]??[.49,.83,.99])}if(s.delete(n),!o.length)return;const l={positions:o,colors:u};return t.set(n,l),l}function Ir(n){const e=new Map;for(const t of W(n,"basematerials")){const s=t.getAttribute("id");s&&e.set(s,W(t,"base").map(r=>Ht(r.getAttribute("displaycolor"))))}for(const t of W(n,"colorgroup")){const s=t.getAttribute("id");s&&e.set(s,W(t,"color").map(r=>Ht(r.getAttribute("color"))))}return e}function Br(n){return[...W(n,"texture2d").map(t=>["texture2d",t.getAttribute("id")]),...W(n,"texture2dgroup").map(t=>["texture2dgroup",t.getAttribute("id")]),...W(n,"compositematerials").map(t=>["composite materials",t.getAttribute("id")]),...W(n,"multiproperties").map(t=>["multi properties",t.getAttribute("id")])].filter(([,t])=>!!t).map(([t,s])=>`3MF ${t} resource "${s}" is not rendered directly yet; base-material colors remain supported.`)}function Bt(n,e,t){n&&!e.has(n)&&t.add(n)}function zt(n,e,t){if(!n)return;const s=t.get(n);if(!(s!=null&&s.length))return;const r=Number(e??0);return Number.isInteger(r)&&r>=0&&r<s.length?s[r]:s[0]}function Ht(n){const e=String(n??"").trim(),t=/^#?([0-9a-f]{6})(?:[0-9a-f]{2})?$/i.exec(e);if(!(t!=null&&t[1]))return[.49,.83,.99];const s=t[1];return[Number.parseInt(s.slice(0,2),16)/255,Number.parseInt(s.slice(2,4),16)/255,Number.parseInt(s.slice(4,6),16)/255]}function on(n){if(!n)return it;const e=n.trim().split(/\s+/).map(Number);return e.length!==12||e.some(t=>!Number.isFinite(t))?it:e}function Ie(n,e){return[n[0]*e[0]+n[1]*e[1]+n[2]*e[2]+e[9],n[0]*e[3]+n[1]*e[4]+n[2]*e[5]+e[10],n[0]*e[6]+n[1]*e[7]+n[2]*e[8]+e[11]]}function zr(n,e,t){const[s,,r]=n.split("/"),i=jt(Number(s),e);if(i==null)return;const a=r?jt(Number(r),t):void 0;return{vertexIndex:i,normalIndex:a}}function Hr(n,e,t,s,r,i,a,o,u){const l=[n,e,t],c=mt(s[n.vertexIndex],s[e.vertexIndex],s[t.vertexIndex]);for(const d of l){a.push(...s[d.vertexIndex]),o.push(...d.normalIndex!=null?i[d.normalIndex]??c:c);const h=r[d.vertexIndex];h&&u.push(...h)}}function jr(n){if(n.length<7)return;const e=[Number(n[4]),Number(n[5]),Number(n[6])];if(!e.some(t=>!Number.isFinite(t)))return e.map(t=>_(t>1?t/255:t,0,1))}function jt(n,e){if(!Number.isInteger(n)||n===0||e<=0)return;const t=n>0?n-1:e+n;return t>=0&&t<e?t:void 0}function mt(n,e,t){const s=e[0]-n[0],r=e[1]-n[1],i=e[2]-n[2],a=t[0]-n[0],o=t[1]-n[1],u=t[2]-n[2];return ln([r*u-i*o,i*a-s*u,s*o-r*a])}function ln(n){const e=Math.hypot(n[0],n[1],n[2]);return e?[n[0]/e,n[1]/e,n[2]/e]:[0,0,1]}function Gr(n){const e=$r(n);if(!e)throw new Error("PLY header is missing end_header.");const s=new TextDecoder().decode(n.slice(0,e.headerEnd)).replace(/\r/g,"").split(`
27
+ `).map(c=>c.trim()).filter(Boolean);if(s[0]!=="ply")throw new Error("Invalid PLY header.");let r="",i=0,a=0,o;const u=[];let l;for(const c of s.slice(1)){const d=c.split(/\s+/);if(d[0]==="format"){r=d[1]??"";continue}if(d[0]==="element"){o=d[1]==="vertex"||d[1]==="face"?d[1]:void 0,d[1]==="vertex"&&(i=Number(d[2])||0),d[1]==="face"&&(a=Number(d[2])||0);continue}if(d[0]==="property"){if(o==="vertex"&&d.length>=3&&d[1]!=="list"){u.push({type:d[1],name:d[2]});continue}o==="face"&&d[1]==="list"&&d.length>=5&&!l&&(l={countType:d[2],itemType:d[3],name:d[4]})}}if(!r||!i||!a||!u.length||!l)throw new Error("PLY header does not define supported vertex and face data.");return{format:r,dataOffset:e.dataOffset,vertexCount:i,faceCount:a,vertexProperties:u,faceListProperty:l}}function Ur(n,e){const t=n.replace(/\r/g,"").split(`
28
+ `).map(f=>f.trim()).filter(Boolean),s=[],r=[];let i=0;const a=e.vertexProperties.findIndex(f=>f.name==="x"),o=e.vertexProperties.findIndex(f=>f.name==="y"),u=e.vertexProperties.findIndex(f=>f.name==="z"),l=un(e.vertexProperties);if(a<0||o<0||u<0)throw new Error("PLY vertex properties must include x, y, and z.");for(;i<e.vertexCount&&i<t.length;i+=1){const f=t[i].split(/\s+/);s.push([G(f[a]),G(f[o]),G(f[u])]),r.push(dn(f.map(Number),e.vertexProperties,l))}const c=[],d=[],h=[];for(let f=0;f<e.faceCount&&i<t.length;f+=1,i+=1){const m=t[i].split(/\s+/).map(Number),g=m[0]??0,w=m.slice(1,1+g).filter(p=>Number.isInteger(p));cn(w,s,r,c,d,h)}if(!c.length)throw new Error("No PLY triangles found.");return Fe(c,d,h.length===c.length?h:void 0)}function _r(n,e){const t=new DataView(n.buffer,n.byteOffset,n.byteLength),s=[],r=[];let i=e.dataOffset;const a=e.vertexProperties.findIndex(f=>f.name==="x"),o=e.vertexProperties.findIndex(f=>f.name==="y"),u=e.vertexProperties.findIndex(f=>f.name==="z"),l=un(e.vertexProperties);if(a<0||o<0||u<0)throw new Error("PLY vertex properties must include x, y, and z.");for(let f=0;f<e.vertexCount;f+=1){const m=[];for(const g of e.vertexProperties){const w=qe(t,i,g.type,true);m.push(w.value),i=w.nextOffset}s.push([m[a]??0,m[o]??0,m[u]??0]),r.push(dn(m,e.vertexProperties,l))}const c=[],d=[],h=[];for(let f=0;f<e.faceCount;f+=1){const m=qe(t,i,e.faceListProperty.countType,true);i=m.nextOffset;const g=[];for(let w=0;w<m.value;w+=1){const p=qe(t,i,e.faceListProperty.itemType,true);g.push(p.value),i=p.nextOffset}cn(g,s,r,c,d,h)}if(!c.length)throw new Error("No PLY triangles found.");return Fe(c,d,h.length===c.length?h:void 0)}function cn(n,e,t,s,r,i){const a=n.filter(o=>Number.isInteger(o)&&o>=0&&o<e.length);if(!(a.length<3))for(let o=1;o<a.length-1;o+=1){const u=e[a[0]],l=e[a[o]],c=e[a[o+1]],d=mt(u,l,c),h=[a[0],a[o],a[o+1]];for(const f of[u,l,c])s.push(...f),r.push(...d);for(const f of h){const m=t[f];m&&i.push(...m)}}}function un(n){const e=Ze(n,["red","diffuse_red","r"]),t=Ze(n,["green","diffuse_green","g"]),s=Ze(n,["blue","diffuse_blue","b"]);return e>=0&&t>=0&&s>=0?[e,t,s]:void 0}function Ze(n,e){return n.findIndex(t=>e.includes(t.name.toLowerCase()))}function dn(n,e,t){if(!t)return;const s=t.map(r=>n[r]??Number.NaN);if(!s.some(r=>!Number.isFinite(r)))return s.map((r,i)=>Vr(r,e[t[i]].type))}function Vr(n,e){return _(e==="float"||e==="float32"||e==="double"||e==="float64"?n>1?n/255:n:n/255,0,1)}function $r(n){const e=[new TextEncoder().encode(`end_header
29
+ `),new TextEncoder().encode(`end_header\r
30
+ `)];for(let t=0;t<n.length;t+=1)for(const s of e)if(Wr(n,s,t))return{headerEnd:t+10,dataOffset:t+s.length}}function Wr(n,e,t){if(t+e.length>n.length)return false;for(let s=0;s<e.length;s+=1)if(n[t+s]!==e[s])return false;return true}function qe(n,e,t,s){switch(t){case"char":case"int8":return{value:n.getInt8(e),nextOffset:e+1};case"uchar":case"uint8":return{value:n.getUint8(e),nextOffset:e+1};case"short":case"int16":return{value:n.getInt16(e,s),nextOffset:e+2};case"ushort":case"uint16":return{value:n.getUint16(e,s),nextOffset:e+2};case"int":case"int32":return{value:n.getInt32(e,s),nextOffset:e+4};case"uint":case"uint32":return{value:n.getUint32(e,s),nextOffset:e+4};case"float":case"float32":return{value:n.getFloat32(e,s),nextOffset:e+4};case"double":case"float64":return{value:n.getFloat64(e,s),nextOffset:e+8};default:throw new Error(`Unsupported PLY scalar type "${t}".`)}}function Fe(n,e,t){const s=hn(n);return{positions:new Float32Array(n),normals:new Float32Array(e),...t!=null&&t.length?{colors:new Float32Array(t)}:{},triangleCount:n.length/9,bounds:s}}function hn(n){let e=Number.POSITIVE_INFINITY,t=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let o=0;o<n.length;o+=3){const u=n[o],l=n[o+1],c=n[o+2];e=Math.min(e,u),t=Math.min(t,l),s=Math.min(s,c),r=Math.max(r,u),i=Math.max(i,l),a=Math.max(a,c)}return{min:[e,t,s],max:[r,i,a]}}function Gt(n,e){var t;return{format:e,triangleCount:n.triangleCount,vertexCount:n.positions.length/3,hasVertexColors:!!((t=n.colors)!=null&&t.length),bounds:{min:[...n.bounds.min],max:[...n.bounds.max],size:[n.bounds.max[0]-n.bounds.min[0],n.bounds.max[1]-n.bounds.min[1],n.bounds.max[2]-n.bounds.min[2]]}}}function Kr(n){return n.children.map((e,t)=>mn(e,`node-${t+1}`))}function mn(n,e){const t=n;return t.userData.previewNodeId=e,t.userData.previewOriginalVisible=n.visible,t.userData.previewMaterialKeys=ft(n),{id:e,label:ni(n,e),kind:si(n),visible:n.visible,metadata:ri(n),children:n.children.map((s,r)=>mn(s,`${e}.${r+1}`))}}function ft(n){const e=n;if(e.userData.previewEdgeHelper||e.userData.previewMeasurementHelper)return[];const t=n;return(Array.isArray(t.material)?t.material:t.material?[t.material]:[]).map(r=>Mn(r))}function Yr(n){let e=false;return n.traverse(t=>{const s=t;s.userData.previewEdgeHelper||s.userData.previewMeasurementHelper||!e&&ft(t).length&&(e=true)}),e}function Xr(n){const e=new te,t=new te;let s=false;return n.traverse(r=>{const i=r;if(!(!r.visible||!i.geometry)&&(t.setFromObject(r),!t.isEmpty())){if(!s){e.copy(t),s=true;return}e.union(t)}}),e}function Zr(n){const e=n.object.geometry;if(!e||!n.face)return;const t=e.getAttribute("position");if(!t||t.itemSize<3)return;const s=[Je(n.object,t,e.index,n.face.a),Je(n.object,t,e.index,n.face.b),Je(n.object,t,e.index,n.face.c)].filter(a=>!!a);if(!s.length)return;let r=s[0],i=r.distanceToSquared(n.point);for(let a=1;a<s.length;a+=1){const o=s[a],u=o.distanceToSquared(n.point);u<i&&(r=o,i=u)}return r}function Je(n,e,t,s){const r=t?t.getX(s):s;if(!Number.isFinite(r))return;const i=new E(e.getX(r),e.getY(r),e.getZ(r));return n.localToWorld(i)}function Ut(n,e,t){switch(t){case"x":return new E(n.x,e.y,e.z);case"y":return new E(e.x,n.y,e.z);case"z":return new E(e.x,e.y,n.z);default:return n}}function _t(n){switch(n){case"y":return new E(0,1,0);case"z":return new E(0,0,1);default:return new E(1,0,0)}}function qr(n){switch(n){case"y":return new E(0,-1,0);case"z":return new E(0,0,-1);default:return new E(-1,0,0)}}function Jr(n){switch(n){case"front":return{yaw:0,pitch:0};case"back":return{yaw:180,pitch:0};case"left":return{yaw:-90,pitch:0};case"right":return{yaw:90,pitch:0};case"top":return{yaw:0,pitch:90};case"bottom":return{yaw:0,pitch:-90};case"isometric":return{yaw:-35,pitch:24};default:return}}function Qr(n){return`${String(n??"model-preview").replace(/\.[^.]+$/,"").replace(/[<>:"/\\|?*\u0000-\u001F]+/g,"-").trim()||"model-preview"}.png`}function fn(n){return n.map(e=>({...e,metadata:e.metadata?{...e.metadata,materialNames:[...e.metadata.materialNames??[]],materialDetails:yn(e.metadata.materialDetails),bounds:e.metadata.bounds?{...e.metadata.bounds,min:[...e.metadata.bounds.min],max:[...e.metadata.bounds.max],size:[...e.metadata.bounds.size]}:void 0}:void 0,children:fn(e.children)}))}function pn(n,e,t){return n.map(s=>s.id===e?gn(s,t):{...s,children:pn(s.children,e,t)})}function gn(n,e){return{...n,visible:e,children:n.children.map(t=>gn(t,e))}}function wn(n,e){for(const t of n){if(t.id===e)return t;const s=wn(t.children,e);if(s)return s}}function ei(n,e){const t=ti(n),s=t.children.filter(a=>!new te().setFromObject(a).isEmpty());if(s.length<2)return[];const i=new te().setFromObject(t).getCenter(new E);return s.map((a,o)=>{const u=new te().setFromObject(a),l=u.getCenter(new E),c=u.getSize(new E),d=l.sub(i);if(d.lengthSq()<=1e-6){const h=o/s.length*Math.PI*2;d.set(Math.cos(h),0,Math.sin(h))}else d.normalize();return{object:a,basePosition:a.position.clone(),direction:d,distance:Math.max(c.length()*.45,e*.22)}})}function ti(n){let e=n;for(;e.children.length===1;){const t=e.children[0];if(!t||t.children.length<2)break;e=t}return e}function ni(n,e){var s;const t=(s=n.name)==null?void 0:s.trim();return t||(n.type&&n.type!=="Object3D"?n.type:e)}function si(n){return n instanceof $||n instanceof Ee?"mesh":n instanceof me?"points":n instanceof _e||n instanceof Q||n.type==="LineLoop"?"lines":n.type==="Bone"?"bone":n.type.endsWith("Light")?"light":n.type.endsWith("Camera")?"camera":n instanceof ee?"group":"object"}function T(n,e){var g;let t=0,s=0,r=0,i=0,a=0,o=0,u=false,l=Array.isArray(n.animations)?((g=n.animations)==null?void 0:g.length)??0:0;const c=new Set,d=new Set,h=new Map;n.traverse(w=>{var P;const p=w;if(p.userData.previewEdgeHelper||p.userData.previewMeasurementHelper)return;t+=1,"animations"in w&&Array.isArray(w.animations)&&(l+=((P=w.animations)==null?void 0:P.length)??0);const b=w,y=b.geometry;if(y){const S=y.getAttribute("position");S&&(a+=S.count),y.getAttribute("color")&&(u=true),o+=pt(y)}w instanceof $||w instanceof Ee?s+=1:w instanceof me?i+=1:(w instanceof _e||w instanceof Q||w.type==="LineLoop")&&(r+=1);const C=Array.isArray(b.material)?b.material:b.material?[b.material]:[];for(const S of C)d.add(S),S.name&&c.add(S.name),h.set(S.id,bn(S))});const f=new te().setFromObject(n),m=f.isEmpty()?void 0:(()=>{const w=f.min,p=f.max,b=f.getSize(new E);return{min:[w.x,w.y,w.z],max:[p.x,p.y,p.z],size:[b.x,b.y,b.z]}})();return{format:e,objectCount:t,meshCount:s,lineCount:r,pointCount:i,materialCount:d.size,materialNames:[...c].sort((w,p)=>w.localeCompare(p)),materialDetails:[...h.values()].sort(xn),animationCount:l,bounds:m,triangleCount:o,vertexCount:a,hasVertexColors:u}}function ri(n){let e=0,t=0,s=0,r=0,i=0,a=false;const o=new Set,u=new Set,l=new Map;n.traverse(h=>{const f=h;if(f.userData.previewEdgeHelper||f.userData.previewMeasurementHelper)return;const m=h,g=m.geometry;if(g){const p=g.getAttribute("position");p&&(r+=p.count),g.getAttribute("color")&&(a=true),i+=pt(g)}h instanceof $||h instanceof Ee?e+=1:h instanceof me?s+=1:(h instanceof _e||h instanceof Q||h.type==="LineLoop")&&(t+=1);const w=Array.isArray(m.material)?m.material:m.material?[m.material]:[];for(const p of w)u.add(p),p.name&&o.add(p.name),l.set(p.id,bn(p))});const c=new te().setFromObject(n),d=c.isEmpty()?void 0:(()=>{const h=c.min,f=c.max,m=c.getSize(new E);return{min:[h.x,h.y,h.z],max:[f.x,f.y,f.z],size:[m.x,m.y,m.z]}})();return{meshCount:e,lineCount:t,pointCount:s,materialCount:u.size,materialNames:[...o].sort((h,f)=>h.localeCompare(f)),materialDetails:[...l.values()].sort(xn),triangleCount:i,vertexCount:r,hasVertexColors:a,bounds:d}}function pt(n){const e=n.getAttribute("position");return e?n.index?Math.floor(n.index.count/3):Math.floor(e.count/3):0}function bn(n){const e=n,t=[e.map?"base":void 0,e.alphaMap?"alpha":void 0,e.aoMap?"ao":void 0,e.bumpMap?"bump":void 0,e.displacementMap?"displacement":void 0,e.emissiveMap?"emissive":void 0,e.envMap?"environment":void 0,e.lightMap?"light":void 0,e.metalnessMap?"metalness":void 0,e.normalMap?"normal":void 0,e.roughnessMap?"roughness":void 0,e.specularMap?"specular":void 0].filter(s=>!!s);return{key:Mn(n),...n.name?{name:n.name}:{},type:n.type||n.constructor.name||"Material",...e.color?{color:Jt(e.color)}:{},...e.emissive?{emissiveColor:Jt(e.emissive)}:{},...Number.isFinite(n.opacity)?{opacity:R(n.opacity)}:{},...Number.isFinite(n.alphaTest)?{alphaTest:R(n.alphaTest)}:{},transparent:n.transparent,...typeof e.wireframe=="boolean"?{wireframe:e.wireframe}:{},...typeof e.vertexColors=="boolean"?{vertexColors:e.vertexColors}:{},...typeof e.vertexColors=="number"?{vertexColors:e.vertexColors>0}:{},...typeof e.flatShading=="boolean"?{flatShading:e.flatShading}:{},...typeof e.depthWrite=="boolean"?{depthWrite:e.depthWrite}:{},...typeof e.depthTest=="boolean"?{depthTest:e.depthTest}:{},...n.side===1?{side:"back"}:n.side===2?{side:"double"}:{side:"front"},...Number.isFinite(e.roughness)?{roughness:R(e.roughness)}:{},...Number.isFinite(e.metalness)?{metalness:R(e.metalness)}:{},...Number.isFinite(e.shininess)?{shininess:R(e.shininess)}:{},...Number.isFinite(e.size)?{size:R(e.size)}:{},...t.length?{mapKinds:t}:{}}}function yn(n){return n==null?void 0:n.map(e=>({...e,mapKinds:e.mapKinds?[...e.mapKinds]:void 0}))}function Vt(n){return n?{...n,snapMode:n.snapMode??"surface",axisLock:n.axisLock??"free",start:n.start?[...n.start]:void 0,end:n.end?[...n.end]:void 0,delta:n.delta?[...n.delta]:void 0,previewPoint:n.previewPoint?[...n.previewPoint]:void 0,previewDelta:n.previewDelta?[...n.previewDelta]:void 0,previewDistance:n.previewDistance}:void 0}function $t(n,e){return!n||!e?n===e:n.active===e.active&&n.status===e.status&&(n.snapMode??"surface")===(e.snapMode??"surface")&&(n.axisLock??"free")===(e.axisLock??"free")&&oe(n.start,e.start)&&oe(n.end,e.end)&&oe(n.delta,e.delta)&&oe(n.previewPoint,e.previewPoint)&&oe(n.previewDelta,e.previewDelta)&&n.distance===e.distance&&n.previewDistance===e.previewDistance}function oe(n,e){return!n||!e?n===e:n[0]===e[0]&&n[1]===e[1]&&n[2]===e[2]}function ue(n){const e="x",[t,s]=(n==null?void 0:n[e])??[-1,1];return{active:false,mode:"single",axis:e,offset:_(0,t,s),min:R(t),max:R(s),bounds:Le(n??Ge()),range:xe(n??Ge())}}function ii(n){return n?{...n,mode:n.mode??"single",offset:R(n.offset),min:R(n.min),max:R(n.max),bounds:n.bounds?Le(n.bounds):void 0,range:n.range?Le(n.range):void 0}:void 0}function Qe(n,e){const t=n.axis??"x",[s,r]=e[t];return{active:n.active,mode:n.mode??"single",axis:t,offset:R(_(n.offset,s,r)),min:R(s),max:R(r),bounds:Le(e),range:li(n.range,e)}}function ai(n,e){return!n||!e?n===e:n.active===e.active&&(n.mode??"single")===(e.mode??"single")&&n.axis===e.axis&&n.offset===e.offset&&n.min===e.min&&n.max===e.max&&oi(n.range,e.range)}function oi(n,e){return!n||!e?n===e:n.x[0]===e.x[0]&&n.x[1]===e.x[1]&&n.y[0]===e.y[0]&&n.y[1]===e.y[1]&&n.z[0]===e.z[0]&&n.z[1]===e.z[1]}function li(n,e){const t=xe(e);return{x:et(n==null?void 0:n.x,e.x,t.x),y:et(n==null?void 0:n.y,e.y,t.y),z:et(n==null?void 0:n.z,e.z,t.z)}}function et(n,e,t){if(!n)return[...t];const s=_(Math.min(n[0],n[1]),e[0],e[1]),r=_(Math.max(n[0],n[1]),e[0],e[1]);return[R(s),R(r)]}function Ge(){return{x:[-1,1],y:[-1,1],z:[-1,1]}}function Le(n){return{x:[...n.x],y:[...n.y],z:[...n.z]}}function xe(n){return Le(n)}function Ue(n){return`${n.axis}:${n.offset.toFixed(5)}`}function ci(n){if(n.mode==="box"){const e=n.range;return e?`box:${e.x[0].toFixed(5)}:${e.x[1].toFixed(5)}:${e.y[0].toFixed(5)}:${e.y[1].toFixed(5)}:${e.z[0].toFixed(5)}:${e.z[1].toFixed(5)}`:"box"}return`single:${Ue(n)}`}function ui(n,e){const t=`${e.position.x.toFixed(5)}:${e.position.y.toFixed(5)}:${e.position.z.toFixed(5)}`;if(n.mode==="box"){const s=n.range;return s?`box:${t}:${s.x[0].toFixed(5)}:${s.x[1].toFixed(5)}:${s.y[0].toFixed(5)}:${s.y[1].toFixed(5)}:${s.z[0].toFixed(5)}:${s.z[1].toFixed(5)}`:`box:${t}`}return`single:${t}:${Ue(n)}`}function di(n,e){switch(n.axis){case"x":return{width:Math.max(e.z[1]-e.z[0],0),height:Math.max(e.y[1]-e.y[0],0)};case"y":return{width:Math.max(e.x[1]-e.x[0],0),height:Math.max(e.z[1]-e.z[0],0)};case"z":default:return{width:Math.max(e.x[1]-e.x[0],0),height:Math.max(e.y[1]-e.y[0],0)}}}function hi(n,e){switch(n.axis){case"x":return Be([[n.offset,e.y[0],e.z[0]],[n.offset,e.y[1],e.z[0]],[n.offset,e.y[1],e.z[1]],[n.offset,e.y[0],e.z[1]]]);case"y":return Be([[e.x[0],n.offset,e.z[0]],[e.x[1],n.offset,e.z[0]],[e.x[1],n.offset,e.z[1]],[e.x[0],n.offset,e.z[1]]]);case"z":default:return Be([[e.x[0],e.y[0],n.offset],[e.x[1],e.y[0],n.offset],[e.x[1],e.y[1],n.offset],[e.x[0],e.y[1],n.offset]])}}function Be(n){const e=[];for(let t=0;t<n.length;t+=1){const s=n[t],r=n[(t+1)%n.length];e.push(...s,...r)}return e}function mi(n){const e=[];for(let t=0;t<n.length-1;t+=1)e.push(...n[t],...n[t+1]);return e}function fi(n,e,t=1e-4){const s=[],r=[],i=new Map,a=new Set,o=(c,d,h)=>{const[f,m]=se(n,[c,d,h]),g=`${Math.round(f/t)}:${Math.round(m/t)}`,w=i.get(g);if(typeof w=="number"){const b=s[w];return b.x+=c,b.y+=d,b.z+=h,b.count+=1,w}const p=s.length;return s.push({x:c,y:d,z:h,count:1,edges:[]}),i.set(g,p),p};for(let c=0;c<e.length;c+=6){const d=o(e[c],e[c+1],e[c+2]),h=o(e[c+3],e[c+4],e[c+5]);if(d===h)continue;const f=d<h?`${d}:${h}`:`${h}:${d}`;if(a.has(f))continue;a.add(f);const m=r.length;r.push({a:d,b:h,visited:false}),s[d].edges.push(m),s[h].edges.push(m)}const u=[],l=[];for(let c=0;c<s.length;c+=1)if(s[c].edges.length!==2)for(;;){const d=s[c].edges.find(f=>!r[f].visited);if(typeof d!="number")break;const h=Wt(n,s,r,c,d);Kt(n,s,h,u,l,t)}for(let c=0;c<s.length;c+=1)for(;;){const d=s[c].edges.find(f=>!r[f].visited);if(typeof d!="number")break;const h=Wt(n,s,r,c,d);Kt(n,s,h,u,l,t)}return{loops:Mi(n,u,t).filter(c=>c.length>=3),chains:Si(n,l,t).filter(c=>c.length>=2)}}function pi(n,e,t,s,r,i){const a=e[s].edges.filter(f=>!t[f].visited&&f!==i);if(!a.length)return;if(typeof r!="number")return a[0];const o=ze(e[s]),u=ze(e[r]),l=at(n,u,o),c=Math.hypot(l.x,l.y);if(c<=1e-10)return a[0];let d=a[0],h=Number.NEGATIVE_INFINITY;for(const f of a){const m=t[f],g=m.a===s?m.b:m.a,w=ze(e[g]),p=at(n,o,w),b=Math.hypot(p.x,p.y);if(b<=1e-10)continue;const y=(l.x*p.x+l.y*p.y)/(c*b);y>h&&(h=y,d=f)}return d}function Wt(n,e,t,s,r){const i=t[r];i.visited=true;const a=i.a===s?i.b:i.a,o=[s,a];let u=s,l=a,c=r;for(;l!==s;){const d=pi(n,e,t,l,u,c);if(typeof d!="number")break;const h=t[d];h.visited=true;const f=h.a===l?h.b:h.a;o.push(f),u=l,c=d,l=f}return o}function Kt(n,e,t,s,r,i=1e-4){if(t.length<2)return;const a=t.length>=4&&t[0]===t[t.length-1],o=t.slice(0,a?-1:t.length).map(l=>ze(e[l])),u=gi(n,o,a,i);if(a){const l=Math.abs(gt(u.map(c=>{const[d,h]=se(n,c);return new lt(d,h)})));u.length>=3&&l>i*i&&s.push(u);return}u.length>=2&&wi(n,u)>i&&r.push(u)}function gi(n,e,t,s=1e-5){if(e.length<=(t?3:2))return e;const r=[];for(let i=0;i<e.length;i+=1){if(!t&&(i===0||i===e.length-1)){r.push(e[i]);continue}const a=e[(i-1+e.length)%e.length],o=e[i],u=e[(i+1)%e.length],[l,c]=se(n,a),[d,h]=se(n,o),[f,m]=se(n,u),g=(d-l)*(m-c)-(h-c)*(f-l);Math.abs(g)>s&&r.push(o)}return r.length>=(t?3:2)?r:e}function wi(n,e){let t=0;for(let s=0;s<e.length-1;s+=1){const r=at(n,e[s],e[s+1]);t+=Math.hypot(r.x,r.y)}return t}function ze(n){return[n.x/n.count,n.y/n.count,n.z/n.count]}function at(n,e,t){const[s,r]=se(n,e),[i,a]=se(n,t);return{x:i-s,y:a-r}}function bi(n,e){if(!e.length)return;const t=xi(n,e),s=[],r=[];let i=0;for(let a=0;a<t.length;a+=1){const o=t[a];if(o.depth%2!==0)continue;const u=Xt(o.loop,o.points2d,"ccw"),l=o.children.map(h=>t[h]).filter(h=>h.depth===o.depth+1).map(h=>Xt(h.loop,h.points2d,"cw")),c=gs.triangulateShape(u.points2d,l.map(h=>h.points2d));if(!c.length)continue;const d=[u,...l];s.push(...d.flatMap(h=>h.loop.flat())),r.push(...c.flat().map(h=>h+i)),i+=d.reduce((h,f)=>h+f.loop.length,0)}if(!(!s.length||!r.length))return{positions:s,indices:r}}function yi(n){const e=new Y;return e.setAttribute("position",new Z(n.positions,3)),e.setIndex(n.indices),e.computeVertexNormals(),e.computeBoundingSphere(),e}function vi(n,e,t=5e-4){const s=n.range??xe(e),[r,i]=s.x,[a,o]=s.y,[u,l]=s.z,c=[];if(r>e.x[0]+t&&be(c,[[r,a,u],[r,o,u],[r,o,l],[r,a,l]]),i<e.x[1]-t&&be(c,[[i,a,u],[i,a,l],[i,o,l],[i,o,u]]),a>e.y[0]+t&&be(c,[[r,a,u],[r,a,l],[i,a,l],[i,a,u]]),o<e.y[1]-t&&be(c,[[r,o,u],[i,o,u],[i,o,l],[r,o,l]]),u>e.z[0]+t&&be(c,[[r,a,u],[i,a,u],[i,o,u],[r,o,u]]),l<e.z[1]-t&&be(c,[[r,a,l],[r,o,l],[i,o,l],[i,a,l]]),!c.length)return;const d=new Y;return d.setAttribute("position",new Z(c,3)),d.computeVertexNormals(),d.computeBoundingSphere(),d}function be(n,e){n.push(...e[0],...e[1],...e[2],...e[0],...e[2],...e[3])}function se(n,e){switch(n){case"x":return[e[1],e[2]];case"y":return[e[0],e[2]];case"z":default:return[e[0],e[1]]}}function xi(n,e){const t=e.filter(s=>s.length>=3).map(s=>{const r=s.map(a=>{const[o,u]=se(n,a);return new lt(o,u)}),i=gt(r);return{loop:s,points2d:r,signedArea:i,absoluteArea:Math.abs(i),children:[],depth:0}}).sort((s,r)=>r.absoluteArea-s.absoluteArea);for(let s=0;s<t.length;s+=1){const r=t[s];let i=-1,a=Number.POSITIVE_INFINITY;for(let o=0;o<s;o+=1){const u=t[o];u.absoluteArea>=r.absoluteArea&&Ei(r.points2d[0],u.points2d)&&u.absoluteArea<a&&(a=u.absoluteArea,i=o)}i>=0&&(t[i].children.push(s),r.depth=t[i].depth+1)}return t}function Mi(n,e,t=1e-4){const s=new Set,r=[];for(const i of e){const a=Ci(n,i,t);!a||s.has(a)||(s.add(a),r.push(i))}return r}function Si(n,e,t=1e-4){const s=new Set,r=[];for(const i of e){const a=Pi(n,i,t);!a||s.has(a)||(s.add(a),r.push(i))}return r}function Ci(n,e,t=1e-4){if(e.length<3)return;const s=e.map(o=>ot(n,o,t)),r=[...s].reverse(),i=Yt(s),a=Yt(r);return i<a?i:a}function Pi(n,e,t=1e-4){if(e.length<2)return;const s=e.map(i=>ot(n,i,t)).join("|"),r=[...e].reverse().map(i=>ot(n,i,t)).join("|");return s<r?s:r}function ot(n,e,t=1e-4){const[s,r]=se(n,e);return`${Math.round(s/t)}:${Math.round(r/t)}`}function Yt(n){if(!n.length)return"";let e=0;for(let s=1;s<n.length;s+=1)Li(n,s,e)<0&&(e=s);const t=[];for(let s=0;s<n.length;s+=1)t.push(n[(e+s)%n.length]);return t.join("|")}function Li(n,e,t){for(let s=0;s<n.length;s+=1){const r=n[(e+s)%n.length],i=n[(t+s)%n.length],a=r.localeCompare(i);if(a!==0)return a}return 0}function Xt(n,e,t){const s=gt(e);return(t==="ccw"?s<0:s>0)?{loop:[...n].reverse(),points2d:[...e].reverse().map(i=>i.clone())}:{loop:[...n],points2d:e.map(i=>i.clone())}}function Ei(n,e,t=1e-7){let s=false;for(let r=0,i=e.length-1;r<e.length;i=r,r+=1){const a=e[r],o=e[i];if(Fi(n,o,a,t))return true;a.y>n.y!=o.y>n.y&&n.x<(o.x-a.x)*(n.y-a.y)/(o.y-a.y||t)+a.x&&(s=!s)}return s}function Fi(n,e,t,s=1e-7){const r=(n.y-e.y)*(t.x-e.x)-(n.x-e.x)*(t.y-e.y);if(Math.abs(r)>s)return false;const i=(n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y);if(i<-s)return false;const a=(t.x-e.x)**2+(t.y-e.y)**2;return i<=a+s}function gt(n){let e=0;for(let t=0;t<n.length;t+=1){const s=n[t],r=n[(t+1)%n.length];e+=s.x*r.y-r.x*s.y}return e/2}function Zt(n,e){const t=[];for(let s=0;s<e.length;s+=9){const r=new E(e[s],e[s+1],e[s+2]),i=new E(e[s+3],e[s+4],e[s+5]),a=new E(e[s+6],e[s+7],e[s+8]),o=Ti(n.axis,n.offset,r,i,a);o.length===2&&t.push(o[0].x,o[0].y,o[0].z,o[1].x,o[1].y,o[1].z)}return t}function Ai(n,e,t){var s;if(!e)return[];if((s=e.objects)!=null&&s.length&&t){const r=[];for(const i of e.objects){if(!i.object.visible)continue;const a=Ri(i.positions,i.object,t);r.push(...Zt(n,a))}return r}return e.positions.length?Zt(n,e.positions):[]}function Di(n,e=st){const t=[];if(n.traverse(i=>{if(!(i instanceof $||i instanceof Ee))return;const a=i.geometry,o=a==null?void 0:a.getAttribute("position");if(!a||!o||o.itemSize<3)return;const u=pt(a);u&&t.push({object:i,geometry:a,position:o,triangleCount:u})}),!t.length)return[];const s=Oi(t.map(i=>i.triangleCount),e),r=[];for(let i=0;i<t.length;i+=1){const a=t[i],o=Ni(a.geometry,a.position,s[i]);o.length&&r.push({object:a.object,positions:o})}return r}function Ni(n,e,t){const s=n.index?Math.floor(n.index.count/3):Math.floor(e.count/3);if(!s)return new Float32Array;const r=vn(s,t),i=new Float32Array(r.length*9);let a=0;if(n.index){for(const o of r)for(let u=0;u<3;u+=1){const l=n.index.getX(o*3+u);i[a]=e.getX(l),i[a+1]=e.getY(l),i[a+2]=e.getZ(l),a+=3}return i}for(const o of r){const u=o*3;for(let l=0;l<3;l+=1){const c=u+l;i[a]=e.getX(c),i[a+1]=e.getY(c),i[a+2]=e.getZ(c),a+=3}}return i}function Oi(n,e){if(!n.length||e<=0)return n.map(()=>0);const t=n.reduce((a,o)=>a+o,0);if(t<=e)return[...n];const s=n.map(a=>Math.floor(a/t*e));let r=s.reduce((a,o)=>a+o,0);const i=n.map((a,o)=>({index:o,remainder:a/t*e-s[o],available:a-s[o]})).sort((a,o)=>o.remainder-a.remainder||o.available-a.available);for(const a of i){if(r>=e)break;a.available<=0||(s[a.index]=s[a.index]+1,r+=1)}return s}function ki(n,e){const t=Math.floor(n.length/9);if(!t||t<=e)return n;const s=vn(t,e),r=new Float32Array(s.length*9);let i=0;for(const a of s){const o=a*9;r.set(n.subarray(o,o+9),i),i+=9}return r}function vn(n,e){if(!n)return[];if(typeof e!="number"||e<=0||n<=e)return Array.from({length:n},(r,i)=>i);const t=[],s=n-1;for(let r=0;r<e;r+=1){const i=Math.min(s,Math.floor((r+.5)*n/e));t.push(i)}return t}function Ri(n,e,t){e.updateMatrixWorld(true),t.updateMatrixWorld(true);const s=new en().copy(t.matrixWorld).invert().multiply(e.matrixWorld),r=new Float32Array(n.length),i=new E;for(let a=0;a<n.length;a+=3)i.set(n[a],n[a+1],n[a+2]).applyMatrix4(s),r[a]=i.x,r[a+1]=i.y,r[a+2]=i.z;return r}function Ti(n,e,t,s,r){const i=[t,s,r],a=[],o=[[i[0],i[1]],[i[1],i[2]],[i[2],i[0]]];for(const[u,l]of o){const c=Ii(n,e,u,l);c&&!a.some(d=>d.distanceToSquared(c)<1e-10)&&a.push(c)}return a}function Ii(n,e,t,s){const r=qt(t,n)-e,i=qt(s,n)-e;if(Math.abs(r)<=1e-7&&Math.abs(i)<=1e-7||r>0&&i>0||r<0&&i<0)return;const a=i-r;if(Math.abs(a)<=1e-7)return;const o=-r/a;if(!(o<-1e-7||o>1+1e-7))return t.clone().lerp(s,_(o,0,1))}function qt(n,e){switch(e){case"y":return n.y;case"z":return n.z;default:return n.x}}function Re(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function xn(n,e){const t=`${n.name??""}\0${n.type}\0${n.key}`,s=`${e.name??""}\0${e.type}\0${e.key}`;return t.localeCompare(s)}function Mn(n){return`${n.type||n.constructor.name||"Material"}:${n.name||"unnamed"}:${n.id}`}function Jt(n){return`#${n.getHexString().toUpperCase()}`}function R(n){return Math.round(n*1e3)/1e3}function ye(n){return[R(n.x),R(n.y),R(n.z)]}function Bi(n){return n.byteLength<84?false:84+new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(80,true)*50===n.byteLength}function zi(n){return new E((n.min[0]+n.max[0])/2,(n.min[1]+n.max[1])/2,(n.min[2]+n.max[2])/2)}function Hi(n){return new E(n.max[0]-n.min[0],n.max[1]-n.min[1],n.max[2]-n.min[2])}function ji(n,e){return{x:[n.min[0]-e.x,n.max[0]-e.x],y:[n.min[1]-e.y,n.max[1]-e.y],z:[n.min[2]-e.z,n.max[2]-e.z]}}function Gi(n){const e=new te().setFromObject(n);return e.isEmpty()?{x:[-1,1],y:[-1,1],z:[-1,1]}:{x:[e.min.x,e.max.x],y:[e.min.y,e.max.y],z:[e.min.z,e.max.z]}}function G(n){const e=Number(n);return Number.isFinite(e)?e:0}function tt(n){return n*Math.PI/180}function _(n,e,t){return Math.max(e,Math.min(t,n))}function Qt(n){var e,t;try{const s=new ps(n);if(!((e=s.getContext)==null?void 0:e.call(s)))throw(t=s.dispose)==null||t.call(s),new Error("WebGL unavailable");return s}catch{const s=document.createElement("canvas");return s.width=1,s.height=1,{domElement:s,setPixelRatio:()=>{},setClearColor:()=>{},setSize:(r,i)=>{const a=Math.max(1,Math.floor(r)),o=Math.max(1,Math.floor(i));s.width=a,s.height=o},render:()=>{},dispose:()=>{}}}}function Sn(n){return String(n??"").trim().replace(/^\./,"").toLowerCase()}function Ui(n){try{return JSON.parse(n)}catch{throw new Error("glTF JSON is invalid.")}}function _i(n){const e=n.trim().toLowerCase();return e.startsWith("data:")||e.startsWith("blob:")}function Cn(n){var t;if(typeof n!="string")return;const e=n.trim();if(!(!e||e.toLowerCase().startsWith("data:")||e.toLowerCase().startsWith("blob:")))try{const s=new URL(e,((t=globalThis.location)==null?void 0:t.href)??"http://localhost/");return new URL(".",s).href}catch{return}}function Ce(n){return Cn(n)??""}function Vi(n){return Ce(n)}function $i(n){return(String(n??"model").split(/[\\/]/).pop()??"model").replace(/\.[^.]+$/,"")||"model"}function pe(n,e,t){const s=Ae(n);return{source:ge(s.source,e,t),warnings:s.warnings}}function Ae(n){if(!n)return{warnings:[]};const e=t=>typeof t=="string"||t instanceof Blob||ArrayBuffer.isView(t)||t instanceof ArrayBuffer;return e(n)?{source:n,warnings:[]}:{source:e(n.source)?n.source:void 0,warnings:n.warnings??[]}}function ge(n,e,t){if(n){if(typeof n=="string")return n;if(n instanceof Blob){const s=URL.createObjectURL(n);return t==null||t.push(s),s}if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer){const s=ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(!t)return Wi(s,e);const r=s.buffer instanceof ArrayBuffer?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);return ge(new Blob([r],{type:e}),e,t)}}}async function Pn(n,e){return new TextDecoder().decode(await ht(n,e))}function Ln(n){var t;const e=((t=n.split("?")[0])==null?void 0:t.toLowerCase())??n.toLowerCase();return e.endsWith(".png")?"image/png":e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".webp")?"image/webp":e.endsWith(".ktx2")?"image/ktx2":"application/octet-stream"}function q(n){var t;return(((t=n.split("?")[0])==null?void 0:t.toLowerCase())??n.toLowerCase()).endsWith(".mtl")?"text/plain":Ln(n)}function X(n){const e=n.replace(/\\/g,"/").split(/[?#]/)[0]??"",t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function K(n,e){if(!n||/^[a-z]+:\/\//i.test(e)||/^[a-z]:[\\/]/i.test(e)||e.startsWith("/"))return e.replace(/\\/g,"/");const t=[];for(const s of`${n}/${e}`.replace(/\\/g,"/").split("/"))if(!(!s||s===".")){if(s===".."){t.pop();continue}t.push(s)}return t.join("/")}function Wi(n,e){let t="";for(const s of n)t+=String.fromCharCode(s);return`data:${e};base64,${btoa(t)}`}const Ki=new URL("../filens-step.wasm",import.meta.url).href;class le extends Error{constructor(e,t){super(t),this.code=e,this.name="StepReadError"}}function En(n={}){const e=bs({wasm:n.wasm??Ki,fetch:n.fetch});return{async read(t,{tolerance:s=.1,signal:r}={}){if(r!=null&&r.aborted)throw Object.assign(new Error("STEP loading was aborted."),{name:"AbortError"});if(!Number.isFinite(s)||s<=0)throw new RangeError("STEP tolerance must be positive and finite (millimetres).");const i=typeof t=="string"?new TextEncoder().encode(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);if(i.byteLength>64<<20)throw new RangeError("STEP input exceeds 64 MiB.");const a=await e({args:["filens-step","/work/input.step","/work/mesh.bin",String(s),"--reviewed","--binary"],files:{"/work/input.step":i},readFiles:["/work/mesh.bin"],signal:r,captureStdio:true}),o=(a.stdout??"").trim().split(`
31
+ `);let u;try{u=JSON.parse(o[o.length-1])}catch{throw new le("invalid_step","Rust STEP could not read this file.")}if(a.exitCode||u.error)throw new le("invalid_step",u.error||"Rust STEP could not read this file.");if(!u.success)throw new le("empty_geometry","STEP contains no displayable geometry; external assemblies require their referenced part files.");if(u.missingFaces>0)throw new le("incomplete_mesh",`STEP tessellation left ${u.missingFaces} faces without geometry.`);const l=a.files["/work/mesh.bin"];if(!l)throw new le("invalid_mesh","Rust STEP did not produce a mesh.");const{positions:c,normals:d}=Yi(l),h=["STEP preview omits source colors, names and the assembly tree."];return u.shellFallback&&h.push("Shells were imported without a resolved assembly hierarchy; instance placement may be incomplete."),{positions:c,normals:d,triangleCount:c.length/9,metadata:u,warnings:h}}}}function Yi(n){if(n.byteLength<16||new TextDecoder().decode(n.subarray(0,8))!=="FLNSMESH")throw new le("invalid_mesh","Invalid STEP mesh header.");const e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=e.getUint32(12,true),s=t*3;if(e.getUint32(8,true)!==1||!t||t%3||n.byteLength!==16+s*8)throw new le("invalid_mesh","Invalid STEP mesh version or triangle count.");const r=new Float32Array(s),i=new Float32Array(s);for(let a=0;a<s;a++){const o=e.getFloat32(16+a*4,true),u=e.getFloat32(16+(s+a)*4,true);if(!Number.isFinite(o)||!Number.isFinite(u))throw new le("invalid_mesh","Nonfinite STEP coordinate or normal.");r[a]=o,i[a]=u}return{positions:r,normals:i}}En();async function Xi(){const n=En();return{async ReadStepFile(e,t,s){const r=await n.read(e,{signal:s});return{success:true,root:{meshes:[0]},warnings:r.warnings,meshes:[{attributes:{position:{array:r.positions},normal:{array:r.normals}}}]}}}}const Zi=Object.freeze(Object.defineProperty({__proto__:null,createRustStepImporter:Xi},Symbol.toStringTag,{value:"Module"}));export{na as a,ta as c};
32
+ /*!
33
+ * @license
34
+ * The MIT License
35
+ *
36
+ * Copyright © 2010-2025 three.js authors
37
+ *
38
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
39
+ * of this software and associated documentation files (the "Software"), to deal
40
+ * in the Software without restriction, including without limitation the rights
41
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
42
+ * copies of the Software, and to permit persons to whom the Software is
43
+ * furnished to do so, subject to the following conditions:
44
+ *
45
+ * The above copyright notice and this permission notice shall be included in
46
+ * all copies or substantial portions of the Software.
47
+ *
48
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
51
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
53
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
54
+ * THE SOFTWARE.
55
+ */