@selvajs/compute 2.1.0-beta.0 → 2.1.0-beta.1

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.
Files changed (40) hide show
  1. package/dist/chunk-JPXUC3P5.cjs +54 -0
  2. package/dist/chunk-JPXUC3P5.cjs.map +1 -0
  3. package/dist/chunk-MA6YB3YZ.cjs.map +1 -1
  4. package/dist/{chunk-6GCGLBJM.cjs → chunk-P4SF7AKZ.cjs} +2 -2
  5. package/dist/chunk-P4SF7AKZ.cjs.map +1 -0
  6. package/dist/{chunk-QUD7W5K3.js → chunk-SKAHIC4G.js} +2 -2
  7. package/dist/chunk-Z4TVQVMV.js +54 -0
  8. package/dist/chunk-Z4TVQVMV.js.map +1 -0
  9. package/dist/core.cjs.map +1 -1
  10. package/dist/grasshopper.cjs +1 -1
  11. package/dist/grasshopper.cjs.map +1 -1
  12. package/dist/grasshopper.d.cts +2 -2
  13. package/dist/grasshopper.d.ts +2 -2
  14. package/dist/grasshopper.js +1 -1
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +1 -1
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/{types-DgepKOuU.d.cts → types-BuRCHPlb.d.cts} +6 -1
  21. package/dist/{types-B6KrSthC.d.ts → types-jPuWWtnU.d.ts} +6 -1
  22. package/dist/visualization-R7QUUUWV.js +2 -0
  23. package/dist/visualization-ZDXKGD2L.cjs +2 -0
  24. package/dist/visualization-ZDXKGD2L.cjs.map +1 -0
  25. package/dist/visualization.cjs +1 -1
  26. package/dist/visualization.cjs.map +1 -1
  27. package/dist/visualization.d.cts +173 -2
  28. package/dist/visualization.d.ts +173 -2
  29. package/dist/visualization.js +1 -1
  30. package/package.json +130 -133
  31. package/dist/chunk-6GCGLBJM.cjs.map +0 -1
  32. package/dist/chunk-KAULD2XQ.cjs +0 -2
  33. package/dist/chunk-KAULD2XQ.cjs.map +0 -1
  34. package/dist/chunk-SP73WPYA.js +0 -2
  35. package/dist/chunk-SP73WPYA.js.map +0 -1
  36. package/dist/visualization-5D5Y547Q.cjs +0 -2
  37. package/dist/visualization-5D5Y547Q.cjs.map +0 -1
  38. package/dist/visualization-JF4W754M.js +0 -2
  39. /package/dist/{chunk-QUD7W5K3.js.map → chunk-SKAHIC4G.js.map} +0 -0
  40. /package/dist/{visualization-JF4W754M.js.map → visualization-R7QUUUWV.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{b as l,c as h,d as f,e as m,h as A,i as _,j as q,m as J,n as H,p as Y,r as O}from"./chunk-GTTKNF4G.js";function p(t,e){if(!t||typeof t!="object")return;let r=t;if(e in r)return r[e];let n=e.toLowerCase();for(let s of Object.keys(r))if(s.toLowerCase()===n)return r[s]}function j(t,e){if(!t||typeof t!="object")return!1;let r=t;if(e in r)return!0;let n=e.toLowerCase();return Object.keys(r).some(s=>s.toLowerCase()===n)}function T(t,e){e||typeof window<"u"&&m().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`)}var Ie="Unable to load grasshopper definition";function xe(t){return t instanceof f&&t.message.includes(Ie)}function Q(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let a=p(o,"innerTree");(!a||Object.keys(a).length===0)&&n.push(p(o,"paramName")??"<unnamed>")}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;m().warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function D(t,e,r){r.debug&&T("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let{response:n}=await N(P(e,t),r);return n}async function X(t,e,r){return r.debug&&T("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning),N(P(e,t),r)}async function Z(t,e,r,n){n.debug&&T("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let s={algo:null,pointer:e,values:t};try{return{...await N(s,n),missed:!1}}catch(o){if(!xe(o))throw o;return{...await N(P(r,t),n),missed:!0}}}async function N(t,e){De(t,e);let r=await A("grasshopper",t,e);if("pointer"in r){let{pointer:n,...s}=r,o=s;return Q(o,e.debug),{response:o,cacheKey:typeof n=="string"?n:null}}return Q(r,e.debug),{response:r,cacheKey:null}}function P(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=Y(t):/^https?:\/\//i.test(t)?r.pointer=t:H(t)?r.algo=t:r.algo=J(t),r}function De(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function ee(t){let e=new WeakSet,r=n=>{if(n==null)return JSON.stringify(n);if(typeof n=="number")return Number.isFinite(n)?String(n):JSON.stringify(null);if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return JSON.stringify(n.toString());if(n instanceof Uint8Array){let s=n.length>64?Array.from(n.slice(0,32)).concat(Array.from(n.slice(-32))):Array.from(n);return JSON.stringify({__u8:!0,len:n.length,sample:s})}return Array.isArray(n)?`[${n.map(r).join(",")}]`:typeof n=="object"?e.has(n)?JSON.stringify("[Circular]"):(e.add(n),`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`):JSON.stringify(null)};return r(t)}function te(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function re(t){return te(t.length,e=>t.charCodeAt(e))}function ne(t){return te(t.length,e=>t[e])}function F(t,e){return re(`${G(t)}|${ee(e)}`)}function G(t){return typeof t=="string"?t:`u8:${t.length}:${ne(t)}`}function Pe(t){return t instanceof Uint8Array?!0:!/^https?:\/\//i.test(t)}var C=class{constructor(e,r,n={},s){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheTtl");l(this,"cache",new Map);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.timeoutMs=n.timeoutMs,this.retry=n.retry;let o=n.cache;this.cacheEnabled=o!==void 0&&o!==!1;let a=typeof o=="object"?o:{};this.cacheMax=a.maxEntries??50,this.cacheTtl=a.ttlMs??0,this.reuseServerDefinitionCache=!!s&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){m().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new f("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let s=F(e,r),o={key:s,enqueuedAt:Date.now(),startedAt:null};if(this.cacheEnabled){let a=this.readCache(s);if(a){let i={status:"success",response:a,durationMs:0,fromCache:!0};return this._lastResult=a,this._lastError=null,this._lastDurationMs=0,this.runHook(this.onStart,o),this.runHook(this.onSettle,o,i),this.notify(),Promise.resolve(a)}}return new Promise((a,i)=>{let u={definition:e,dataTree:r,ctx:o,resolve:a,reject:i,externalSignal:n?.signal};if(u.externalSignal?.aborted){this.settleError(u,this.makeAbortError(o));return}this.enqueue(u)})}enqueue(e){switch(this.mode){case"latest-wins":{this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let r of this.inFlight)this.supersede(r),r.controller.abort();this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.fifoQueue.push(e);break}}this.notify()}async execute(e){let r=new AbortController,n={...e,controller:r};this.inFlight.add(n),e.ctx.startedAt=Date.now();let s=()=>r.abort();e.externalSignal?.addEventListener("abort",s,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let o=performance.now();try{let a={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},i=await this.runExecutor(e.definition,e.dataTree,a),u=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,i),!this.settleSuccess(e,i))return;this._lastResult=i,this._lastError=null,this._lastDurationMs=u,this.runHook(this.onSettle,e.ctx,{status:"success",response:i,durationMs:u,fromCache:!1})}catch(a){let i=performance.now()-o,u=this.normalizeExecutionError(a,n);this._lastError=u,this._lastDurationMs=i,this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:i})}finally{e.externalSignal?.removeEventListener("abort",s),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!Pe(e))return this.executor(e,r,n);let s=G(e),o=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,o,n);return a.cacheKey?this.serverCacheKeys.set(s,a.cacheKey):this.serverCacheKeys.delete(s),a.response}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new f("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new f("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},e.resolve(r),!0)}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof f?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new f(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?performance.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){this.settleError(e,this.makeAbortError(e.ctx))}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.cache.delete(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(this.cacheEnabled)for(this.cache.set(e,{response:r,insertedAt:Date.now()});this.cache.size>this.cacheMax;){let n=this.cache.keys().next().value;if(n===void 0)break;this.cache.delete(n)}}clearCache(){this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.cache.clear())}runHook(e,...r){if(e)try{e(...r)}catch(n){m().error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new q(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e);if(!await r.serverStats.isServerOnline())throw new f("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl}});return r}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),V(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),E(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new f("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new f("Definition content is empty",h.INVALID_INPUT);let s={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(o?.errors&&o.errors.length>0)throw new f(o.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r,errors:o.errors,warnings:o.warnings}});return o}catch(s){throw this.config.debug&&m().error("Compute failed:",s),s instanceof f?s:new f(s instanceof Error?s.message:String(s),h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,a)=>D(o,s,a),n=(s,o,a,i)=>a===null?X(o,s,i).then(u=>({...u,missed:!1})):Z(o,a,s,i);return new C(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new f("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var k=new Map;function se(t,e){k.set(t,e)}se("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});se("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Re(t){if(k.has(t))return k.get(t);for(let[e,r]of k)if(t.startsWith(e))return r}function Ee(t){return!t||typeof t!="object"?null:t.data??t.value??null}function oe(t,e,r){let n=Re(e);if(n)try{return n(r,t)}catch(s){m().warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=Ee(t);if(s)return r.CommonObject.decode(s)}catch(s){return m().warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var S={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},ve="Rhino.Geometry.",we=["WebDisplay"],Ae="FileData";function ae(t){return we.some(e=>t.includes(e))}function ie(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Oe(t,e,r){switch(e){case S.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case S.INT:return Number.parseInt(t,10);case S.DOUBLE:return Number.parseFloat(t);case S.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(ve)?oe(t,e,r):t}}function ue(t,e,r,n){if(typeof t!="string")return t;let s=r?ie(t):t;return Oe(s,e,n)}function Ne(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function M(t,e){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)e(n)}function pe(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a={};for(let i of t.values)M(i.InnerTree,u=>{if(ae(u.type)||o&&u.type!==S.STRING)return;let c=e?u.id:i.ParamName;if(!c)return;let d=ue(u.data,u.type,n,s);a[c]===void 0?a[c]=d:Array.isArray(a[c])?a[c].push(d):a[c]=[a[c],d]});return{values:a}}function le(t){let e=[];for(let r of t.values)M(r.InnerTree,n=>{if(!n.type.includes(Ae))return;let s=ie(n.data);Ne(s)&&e.push(s)});return e}function L(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a;if("byName"in e?a=t.values.find(u=>u.ParamName===e.byName):a=t.values.find(u=>{let c=!1;return M(u.InnerTree,d=>{d.id===e.byId&&(c=!0)}),c}),!a)return;let i=[];if(M(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||ae(u.type)||o&&u.type!==S.STRING)return;let c=ue(u.data,u.type,n,s);i.push(c)}),i.length!==0)return i.length===1?i[0]:i}var v=class{constructor(e,r=!1){this.response=e;this.debug=r}getValues(e=!1,r={}){return pe(this.response,e,r)}getValue(e,r){return L(this.response,e,r)}getValueByParamName(e,r){return L(this.response,{byName:e},r)}getValueByParamId(e,r){return L(this.response,{byId:e},r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-JF4W754M.js"))}catch(s){throw new f("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return le(this.response)}getAndDownloadFiles(e,r){let n=this.getFileData();O(n,e,r)}};function ce(t){return p(t,"data")}function Fe(t){return p(t,"type")}function fe(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(!j(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return m().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={};for(let[s,o]of Object.entries(e))n[s]=o.map(a=>{let i=ce(a),u=Fe(a);if(typeof i=="string"){if(u==="System.Double"||u==="System.Int32"){let c=Number(i);return Number.isNaN(c)?i:c}if(u==="System.Boolean")return i.toLowerCase()==="true";if(u?.startsWith("Rhino.Geometry"))try{return JSON.parse(i)}catch{return i}}return i});return{schema:{...t,default:n}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&j(s,"data")&&r.push(ce(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var U=/^\{([\d;]*)\}$/;function w(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>U.test(r)&&Array.isArray(n))}function I(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var Ge=t=>{if(typeof t=="number")return t;if(typeof t=="string"){let e=Number(t.trim());return Number.isNaN(e)?null:e}return null},Ve=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.toLowerCase();if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean string: "${t}"`)}return null},ke=t=>typeof t=="string"?t.startsWith('"')&&t.endsWith('"')||t.startsWith('"')?t.slice(1,-1):t:null,Me=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function de(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(m().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return m().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function me(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function Le(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let y=String(t).split(".")[1];if(y&&y.length>0){let g=Math.min(y.length,12),b=Math.pow(10,-g),$=Number(b.toFixed(g));return Math.abs($-b)<e?$:b}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let x=Number(s[1]);if(x<0||n.toLowerCase().includes("e-")){let y=Math.abs(x),g=Math.pow(10,-y),b=Number(g.toFixed(y));return Math.abs(b-g)<e?b:g}return .1}let o=12,i=r.toFixed(o).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,o);if(u===0)return .1;let c=Math.pow(10,-u),d=Number(c.toFixed(u));return Math.abs(d-c)<e?d:c}function We(t,e=1e-8){let r=t.paramType==="Integer";if(w(t.default))return{default:t.default,stepSize:r?1:.1};let n=I(t.default,Ge,!0);if(r)return Array.isArray(n)?n=n.map(d=>typeof d=="number"?Math.round(d):d):typeof n=="number"&&(n=Math.round(n)),{default:n,stepSize:1};let s=Array.isArray(n)?n[0]:n,o;typeof s=="number"&&Number.isFinite(s)&&s!==0?o=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?o=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(o=t.maximum);let a=o!==void 0?Le(o,e):.1,i=0,u=String(a),c=u.toLowerCase().match(/e(-?\d+)/);if(c?i=Math.abs(Number(c[1])):i=u.split(".")[1]?.length??0,i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let d=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(d)&&d>0&&(i=d)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(d=>typeof d=="number"?me(d,i,e):d):typeof n=="number"&&(n=me(n,i,e)),{default:n,stepSize:a}}var Be={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=We(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,default:r?[0]:0}}},je={types:["Boolean"],parse(t,e){let r;try{r=I(t.default,Ve,!1)}catch(n){throw n instanceof Error?new f(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},Ue={types:["Text"],parse(t,e){let r=I(t.default,ke,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},Ke={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw f.missingValues(t.nickname||"unnamed","ValueList");if(t.default!==void 0&&t.default!==null){let r=String(t.default).toLowerCase();Object.keys(t.values).some(s=>s.toLowerCase()===r)||m().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:t.default}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"ValueList",values:t.values??{},default:r?[t.default]:t.default}}},he={types:["Geometry"],parse(t,e){let r=I(t.default,de(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},ze={types:["File"],parse(t,e){let r=I(t.default,de(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},$e={types:["Color"],parse(t,e){let r=I(t.default,Me,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},_e=[Be,je,Ue,Ke,he,ze,$e],K=new Map(_e.flatMap(t=>t.types.map(e=>[e,t]))),ye=he;var qe=new Map([...K.keys()].map(t=>[t.toLowerCase(),t]));function Je(t){return qe.get(t?.toLowerCase())??t}function ge(t){return z(t).input}function z(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??"",id:t.id},r=Je(t.paramType),{schema:n,warning:s}=fe({...t,paramType:r}),o=s&&{inputName:t.name||"unknown",paramType:r,message:s.message,code:s.code},a=K.get(r);try{if(!a)throw f.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof f)return m().error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(a??ye).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new f(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function be(t){return W(t).inputs}function W(t){let e=[],r=[];for(let n of t){let{input:s,error:o}=z(n);e.push(s),o&&r.push(o)}return{inputs:e,parseErrors:r}}function Te(t){return{id:p(t,"id"),name:p(t,"name"),nickname:p(t,"nickname")??null,description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast"),atMost:p(t,"atMost"),stepSize:p(t,"stepSize"),default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??""}}function Ce(t){return{name:p(t,"name"),nickname:p(t,"nickname")??null,paramType:p(t,"paramType"),id:p(t,"id")}}async function E(t,e){let r=P(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new f("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let s=await A("io",n,e);if(!s||typeof s!="object")throw new f("Invalid IO response structure",h.INVALID_INPUT,{context:{response:s,definition:t}});let o=Se(p(s,"warnings")),a=Se(p(s,"errors")),i=p(s,"inputs"),u=p(s,"outputs");return{inputs:Array.isArray(i)?i.map(Te):[],outputs:Array.isArray(u)?u.map(Ce):[],...o&&{loadWarnings:o},...a&&{loadErrors:a}}}function Se(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}async function V(t,e){T("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await E(t,e),{inputs:a,parseErrors:i}=W(r);return{inputs:a,outputs:n,...i.length>0&&{parseErrors:i},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}var B=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let s=t.parsePathString(r);this.append(s,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(s=>t.deserializeValue(s.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),s=r.default;if(r.treeAccess&&w(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],a=t.processValues(o,r);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let c=e,d=c.findIndex(x=>x.getParamName()===r);return d!==-1?c[d]=o:c.push(o),c}let a=e,i=o.toComputeFormat(),u=a.findIndex(c=>c.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return w(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(a=>a.ParamName===r);if(!n?.InnerTree)return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(a=>a?.data!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):o?.data!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(U);return r?r[1]===""?[]:r[1].split(";").map(Number):(m().warn(`Invalid TreeBuilder path format: ${e}, using [0]`),[0])}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let a=t.deserializeValue(o.data);if(typeof a=="number"){let i=t.clampValue(a,e,r,n);o.data=t.serializeValue(i)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,s){let o=e;return r!=null&&o<r&&(m().warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(m().warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};export{D as a,F as b,C as c,R as d,v as e,ge as f,be as g,E as h,V as i,B as j};
2
- //# sourceMappingURL=chunk-QUD7W5K3.js.map
1
+ import{b as l,c as h,d as f,e as m,h as A,i as _,j as q,m as J,n as H,p as Y,r as O}from"./chunk-GTTKNF4G.js";function p(t,e){if(!t||typeof t!="object")return;let r=t;if(e in r)return r[e];let n=e.toLowerCase();for(let s of Object.keys(r))if(s.toLowerCase()===n)return r[s]}function j(t,e){if(!t||typeof t!="object")return!1;let r=t;if(e in r)return!0;let n=e.toLowerCase();return Object.keys(r).some(s=>s.toLowerCase()===n)}function T(t,e){e||typeof window<"u"&&m().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`)}var Ie="Unable to load grasshopper definition";function xe(t){return t instanceof f&&t.message.includes(Ie)}function Q(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let a=p(o,"innerTree");(!a||Object.keys(a).length===0)&&n.push(p(o,"paramName")??"<unnamed>")}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;m().warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function D(t,e,r){r.debug&&T("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let{response:n}=await N(P(e,t),r);return n}async function X(t,e,r){return r.debug&&T("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning),N(P(e,t),r)}async function Z(t,e,r,n){n.debug&&T("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let s={algo:null,pointer:e,values:t};try{return{...await N(s,n),missed:!1}}catch(o){if(!xe(o))throw o;return{...await N(P(r,t),n),missed:!0}}}async function N(t,e){De(t,e);let r=await A("grasshopper",t,e);if("pointer"in r){let{pointer:n,...s}=r,o=s;return Q(o,e.debug),{response:o,cacheKey:typeof n=="string"?n:null}}return Q(r,e.debug),{response:r,cacheKey:null}}function P(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=Y(t):/^https?:\/\//i.test(t)?r.pointer=t:H(t)?r.algo=t:r.algo=J(t),r}function De(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function ee(t){let e=new WeakSet,r=n=>{if(n==null)return JSON.stringify(n);if(typeof n=="number")return Number.isFinite(n)?String(n):JSON.stringify(null);if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return JSON.stringify(n.toString());if(n instanceof Uint8Array){let s=n.length>64?Array.from(n.slice(0,32)).concat(Array.from(n.slice(-32))):Array.from(n);return JSON.stringify({__u8:!0,len:n.length,sample:s})}return Array.isArray(n)?`[${n.map(r).join(",")}]`:typeof n=="object"?e.has(n)?JSON.stringify("[Circular]"):(e.add(n),`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`):JSON.stringify(null)};return r(t)}function te(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function re(t){return te(t.length,e=>t.charCodeAt(e))}function ne(t){return te(t.length,e=>t[e])}function F(t,e){return re(`${G(t)}|${ee(e)}`)}function G(t){return typeof t=="string"?t:`u8:${t.length}:${ne(t)}`}function Pe(t){return t instanceof Uint8Array?!0:!/^https?:\/\//i.test(t)}var C=class{constructor(e,r,n={},s){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheTtl");l(this,"cache",new Map);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.timeoutMs=n.timeoutMs,this.retry=n.retry;let o=n.cache;this.cacheEnabled=o!==void 0&&o!==!1;let a=typeof o=="object"?o:{};this.cacheMax=a.maxEntries??50,this.cacheTtl=a.ttlMs??0,this.reuseServerDefinitionCache=!!s&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){m().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new f("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let s=F(e,r),o={key:s,enqueuedAt:Date.now(),startedAt:null};if(this.cacheEnabled){let a=this.readCache(s);if(a){let i={status:"success",response:a,durationMs:0,fromCache:!0};return this._lastResult=a,this._lastError=null,this._lastDurationMs=0,this.runHook(this.onStart,o),this.runHook(this.onSettle,o,i),this.notify(),Promise.resolve(a)}}return new Promise((a,i)=>{let u={definition:e,dataTree:r,ctx:o,resolve:a,reject:i,externalSignal:n?.signal};if(u.externalSignal?.aborted){this.settleError(u,this.makeAbortError(o));return}this.enqueue(u)})}enqueue(e){switch(this.mode){case"latest-wins":{this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let r of this.inFlight)this.supersede(r),r.controller.abort();this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.fifoQueue.push(e);break}}this.notify()}async execute(e){let r=new AbortController,n={...e,controller:r};this.inFlight.add(n),e.ctx.startedAt=Date.now();let s=()=>r.abort();e.externalSignal?.addEventListener("abort",s,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let o=performance.now();try{let a={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},i=await this.runExecutor(e.definition,e.dataTree,a),u=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,i),!this.settleSuccess(e,i))return;this._lastResult=i,this._lastError=null,this._lastDurationMs=u,this.runHook(this.onSettle,e.ctx,{status:"success",response:i,durationMs:u,fromCache:!1})}catch(a){let i=performance.now()-o,u=this.normalizeExecutionError(a,n);this._lastError=u,this._lastDurationMs=i,this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:i})}finally{e.externalSignal?.removeEventListener("abort",s),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!Pe(e))return this.executor(e,r,n);let s=G(e),o=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,o,n);return a.cacheKey?this.serverCacheKeys.set(s,a.cacheKey):this.serverCacheKeys.delete(s),a.response}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new f("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new f("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},e.resolve(r),!0)}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof f?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new f(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?performance.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){this.settleError(e,this.makeAbortError(e.ctx))}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.cache.delete(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(this.cacheEnabled)for(this.cache.set(e,{response:r,insertedAt:Date.now()});this.cache.size>this.cacheMax;){let n=this.cache.keys().next().value;if(n===void 0)break;this.cache.delete(n)}}clearCache(){this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.cache.clear())}runHook(e,...r){if(e)try{e(...r)}catch(n){m().error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new q(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e);if(!await r.serverStats.isServerOnline())throw new f("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl}});return r}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),V(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),E(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new f("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new f("Definition content is empty",h.INVALID_INPUT);let s={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(o?.errors&&o.errors.length>0)throw new f(o.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r,errors:o.errors,warnings:o.warnings}});return o}catch(s){throw this.config.debug&&m().error("Compute failed:",s),s instanceof f?s:new f(s instanceof Error?s.message:String(s),h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,a)=>D(o,s,a),n=(s,o,a,i)=>a===null?X(o,s,i).then(u=>({...u,missed:!1})):Z(o,a,s,i);return new C(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new f("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var k=new Map;function se(t,e){k.set(t,e)}se("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});se("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Re(t){if(k.has(t))return k.get(t);for(let[e,r]of k)if(t.startsWith(e))return r}function Ee(t){return!t||typeof t!="object"?null:t.data??t.value??null}function oe(t,e,r){let n=Re(e);if(n)try{return n(r,t)}catch(s){m().warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=Ee(t);if(s)return r.CommonObject.decode(s)}catch(s){return m().warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var S={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},ve="Rhino.Geometry.",we=["WebDisplay"],Ae="FileData";function ae(t){return we.some(e=>t.includes(e))}function ie(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Oe(t,e,r){switch(e){case S.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case S.INT:return Number.parseInt(t,10);case S.DOUBLE:return Number.parseFloat(t);case S.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(ve)?oe(t,e,r):t}}function ue(t,e,r,n){if(typeof t!="string")return t;let s=r?ie(t):t;return Oe(s,e,n)}function Ne(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function M(t,e){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)e(n)}function pe(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a={};for(let i of t.values)M(i.InnerTree,u=>{if(ae(u.type)||o&&u.type!==S.STRING)return;let c=e?u.id:i.ParamName;if(!c)return;let d=ue(u.data,u.type,n,s);a[c]===void 0?a[c]=d:Array.isArray(a[c])?a[c].push(d):a[c]=[a[c],d]});return{values:a}}function le(t){let e=[];for(let r of t.values)M(r.InnerTree,n=>{if(!n.type.includes(Ae))return;let s=ie(n.data);Ne(s)&&e.push(s)});return e}function L(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a;if("byName"in e?a=t.values.find(u=>u.ParamName===e.byName):a=t.values.find(u=>{let c=!1;return M(u.InnerTree,d=>{d.id===e.byId&&(c=!0)}),c}),!a)return;let i=[];if(M(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||ae(u.type)||o&&u.type!==S.STRING)return;let c=ue(u.data,u.type,n,s);i.push(c)}),i.length!==0)return i.length===1?i[0]:i}var v=class{constructor(e,r=!1){this.response=e;this.debug=r}getValues(e=!1,r={}){return pe(this.response,e,r)}getValue(e,r){return L(this.response,e,r)}getValueByParamName(e,r){return L(this.response,{byName:e},r)}getValueByParamId(e,r){return L(this.response,{byId:e},r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-R7QUUUWV.js"))}catch(s){throw new f("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return le(this.response)}getAndDownloadFiles(e,r){let n=this.getFileData();O(n,e,r)}};function ce(t){return p(t,"data")}function Fe(t){return p(t,"type")}function fe(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(!j(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return m().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={};for(let[s,o]of Object.entries(e))n[s]=o.map(a=>{let i=ce(a),u=Fe(a);if(typeof i=="string"){if(u==="System.Double"||u==="System.Int32"){let c=Number(i);return Number.isNaN(c)?i:c}if(u==="System.Boolean")return i.toLowerCase()==="true";if(u?.startsWith("Rhino.Geometry"))try{return JSON.parse(i)}catch{return i}}return i});return{schema:{...t,default:n}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&j(s,"data")&&r.push(ce(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var U=/^\{([\d;]*)\}$/;function w(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>U.test(r)&&Array.isArray(n))}function I(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var Ge=t=>{if(typeof t=="number")return t;if(typeof t=="string"){let e=Number(t.trim());return Number.isNaN(e)?null:e}return null},Ve=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.toLowerCase();if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean string: "${t}"`)}return null},ke=t=>typeof t=="string"?t.startsWith('"')&&t.endsWith('"')||t.startsWith('"')?t.slice(1,-1):t:null,Me=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function de(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(m().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return m().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function me(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function Le(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let y=String(t).split(".")[1];if(y&&y.length>0){let g=Math.min(y.length,12),b=Math.pow(10,-g),$=Number(b.toFixed(g));return Math.abs($-b)<e?$:b}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let x=Number(s[1]);if(x<0||n.toLowerCase().includes("e-")){let y=Math.abs(x),g=Math.pow(10,-y),b=Number(g.toFixed(y));return Math.abs(b-g)<e?b:g}return .1}let o=12,i=r.toFixed(o).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,o);if(u===0)return .1;let c=Math.pow(10,-u),d=Number(c.toFixed(u));return Math.abs(d-c)<e?d:c}function We(t,e=1e-8){let r=t.paramType==="Integer";if(w(t.default))return{default:t.default,stepSize:r?1:.1};let n=I(t.default,Ge,!0);if(r)return Array.isArray(n)?n=n.map(d=>typeof d=="number"?Math.round(d):d):typeof n=="number"&&(n=Math.round(n)),{default:n,stepSize:1};let s=Array.isArray(n)?n[0]:n,o;typeof s=="number"&&Number.isFinite(s)&&s!==0?o=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?o=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(o=t.maximum);let a=o!==void 0?Le(o,e):.1,i=0,u=String(a),c=u.toLowerCase().match(/e(-?\d+)/);if(c?i=Math.abs(Number(c[1])):i=u.split(".")[1]?.length??0,i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let d=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(d)&&d>0&&(i=d)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(d=>typeof d=="number"?me(d,i,e):d):typeof n=="number"&&(n=me(n,i,e)),{default:n,stepSize:a}}var Be={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=We(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,default:r?[0]:0}}},je={types:["Boolean"],parse(t,e){let r;try{r=I(t.default,Ve,!1)}catch(n){throw n instanceof Error?new f(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},Ue={types:["Text"],parse(t,e){let r=I(t.default,ke,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},Ke={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw f.missingValues(t.nickname||"unnamed","ValueList");if(t.default!==void 0&&t.default!==null){let r=String(t.default).toLowerCase();Object.keys(t.values).some(s=>s.toLowerCase()===r)||m().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:t.default}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"ValueList",values:t.values??{},default:r?[t.default]:t.default}}},he={types:["Geometry"],parse(t,e){let r=I(t.default,de(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},ze={types:["File"],parse(t,e){let r=I(t.default,de(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},$e={types:["Color"],parse(t,e){let r=I(t.default,Me,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},_e=[Be,je,Ue,Ke,he,ze,$e],K=new Map(_e.flatMap(t=>t.types.map(e=>[e,t]))),ye=he;var qe=new Map([...K.keys()].map(t=>[t.toLowerCase(),t]));function Je(t){return qe.get(t?.toLowerCase())??t}function ge(t){return z(t).input}function z(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??"",id:t.id},r=Je(t.paramType),{schema:n,warning:s}=fe({...t,paramType:r}),o=s&&{inputName:t.name||"unknown",paramType:r,message:s.message,code:s.code},a=K.get(r);try{if(!a)throw f.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof f)return m().error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(a??ye).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new f(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function be(t){return W(t).inputs}function W(t){let e=[],r=[];for(let n of t){let{input:s,error:o}=z(n);e.push(s),o&&r.push(o)}return{inputs:e,parseErrors:r}}function Te(t){return{id:p(t,"id"),name:p(t,"name"),nickname:p(t,"nickname")??null,description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast"),atMost:p(t,"atMost"),stepSize:p(t,"stepSize"),default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??""}}function Ce(t){return{name:p(t,"name"),nickname:p(t,"nickname")??null,paramType:p(t,"paramType"),id:p(t,"id")}}async function E(t,e){let r=P(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new f("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let s=await A("io",n,e);if(!s||typeof s!="object")throw new f("Invalid IO response structure",h.INVALID_INPUT,{context:{response:s,definition:t}});let o=Se(p(s,"warnings")),a=Se(p(s,"errors")),i=p(s,"inputs"),u=p(s,"outputs");return{inputs:Array.isArray(i)?i.map(Te):[],outputs:Array.isArray(u)?u.map(Ce):[],...o&&{loadWarnings:o},...a&&{loadErrors:a}}}function Se(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}async function V(t,e){T("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await E(t,e),{inputs:a,parseErrors:i}=W(r);return{inputs:a,outputs:n,...i.length>0&&{parseErrors:i},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}var B=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let s=t.parsePathString(r);this.append(s,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(s=>t.deserializeValue(s.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),s=r.default;if(r.treeAccess&&w(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],a=t.processValues(o,r);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let c=e,d=c.findIndex(x=>x.getParamName()===r);return d!==-1?c[d]=o:c.push(o),c}let a=e,i=o.toComputeFormat(),u=a.findIndex(c=>c.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return w(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(a=>a.ParamName===r);if(!n?.InnerTree)return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(a=>a?.data!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):o?.data!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(U);return r?r[1]===""?[]:r[1].split(";").map(Number):(m().warn(`Invalid TreeBuilder path format: ${e}, using [0]`),[0])}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let a=t.deserializeValue(o.data);if(typeof a=="number"){let i=t.clampValue(a,e,r,n);o.data=t.serializeValue(i)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,s){let o=e;return r!=null&&o<r&&(m().warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(m().warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};export{D as a,F as b,C as c,R as d,v as e,ge as f,be as g,E as h,V as i,B as j};
2
+ //# sourceMappingURL=chunk-SKAHIC4G.js.map
@@ -0,0 +1,54 @@
1
+ import{a as we,c as W,d as $,e as w,o as K}from"./chunk-GTTKNF4G.js";import*as P from"three";var F={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function dn(e,r,t,n,i){if(He(e),r.length===0)return;r.forEach(d=>{e.add(d)});let o=_(r),a=o.getCenter(new P.Vector3),c=o.getSize(new P.Vector3),s=Math.max(c.x,c.y,c.z);if(s/Math.min(c.x||1,c.y||1,c.z||1)>F.SCALE_RATIO_THRESHOLD||s>F.HUGE_THRESHOLD?(t.near=s*F.NEAR_PLANE_FACTOR.TINY,t.far=s*F.FAR_PLANE_FACTOR.HUGE):s>F.LARGE_THRESHOLD?(t.near=s*F.NEAR_PLANE_FACTOR.SMALL,t.far=s*F.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,s*F.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,s*F.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),i)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let d=s*F.INITIAL_DISTANCE_MULTIPLIER;t.position.set(a.x+d*.8,a.y+d,a.z+d*1.2),n.target.copy(a),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function Q(e){if(!e||typeof e!="string")return w().warn(`Invalid color input: ${e}, using white`),new P.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new P.Color(t)}catch{return w().warn(`Invalid hex color: ${e}, using white`),new P.Color(16777215)}if(r.includes(",")){let t=r.split(",").map(n=>parseInt(n.trim(),10));if(t.length===3&&t.every(n=>!isNaN(n)&&n>=0&&n<=255))return new P.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new P.Color(r.toLowerCase())}catch{return w().warn(`Invalid color string: ${e}, using white`),new P.Color(16777215)}}function ee(e,r){e.forEach(t=>{t.position.y-=r})}function _(e){let r=new P.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let n=new P.Box3().setFromObject(t);r.union(n)}),r}function He(e){[...e.children].forEach(t=>{t.userData.id!=="floor"&&(t.traverse(n=>{let i=n;if(!i.geometry&&!i.material)return;i.geometry?.dispose();let o=i.material;if(!o)return;(Array.isArray(o)?o:[o]).forEach(c=>{for(let s of Object.values(c))s instanceof P.Texture&&s.dispose();c.dispose()})}),t.removeFromParent())})}import*as B from"three";var Ce={top:new B.Vector3(0,1,0),bottom:new B.Vector3(0,-1,0),front:new B.Vector3(0,0,1),back:new B.Vector3(0,0,-1),right:new B.Vector3(1,0,0),left:new B.Vector3(-1,0,0),iso:new B.Vector3(.8,1,1.2).normalize()};function te(e){let{scene:r,perspective:t,controls:n,onActiveCameraChange:i}=e,o=new B.OrthographicCamera(-1,1,1,-1,t.near,t.far);o.up.copy(t.up);let a="perspective",c=t.aspect,s=()=>a==="perspective"?t:o,l=()=>{let v=t.position.distanceTo(n.target)*Math.tan(t.fov*Math.PI/360),S=v*c;o.left=-S,o.right=S,o.top=v,o.bottom=-v,o.near=t.near,o.far=t.far,o.updateProjectionMatrix()},d=m=>{m!==a&&(m==="orthographic"?(o.position.copy(t.position),o.up.copy(t.up),o.lookAt(n.target),l()):t.position.copy(o.position),a=m,n.object=s(),n.update(),i(s()))};return{getActiveCamera:s,getProjection:()=>a,setProjection:d,toggleProjection:()=>(d(a==="perspective"?"orthographic":"perspective"),a),setView:(m,v=!0)=>{let S=xe(r),T=S.isEmpty()?n.target.clone():S.getCenter(new B.Vector3),b=S.isEmpty()?new B.Vector3(1,1,1):S.getSize(new B.Vector3),H=Math.max(b.x,b.y,b.z)||1,h=t.fov*(Math.PI/180),g=H/(2*Math.tan(h/2))*1.5,R=Ce[m],M=T.clone().add(R.clone().multiplyScalar(g)),y=s();v?Ae(y,n,M,T,()=>{a==="orthographic"&&l()}):(y.position.copy(M),n.target.copy(T),a==="orthographic"&&l(),n.update())},setRotateEnabled:m=>{n.enableRotate=m},isRotateEnabled:()=>n.enableRotate,updateAspect:(m,v)=>{c=v===0?c:m/v,a==="orthographic"&&l()}}}var ve=new Set(["grid","floor","label-layer","measure"]);function Me(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&ve.has(r.userData.id))return!0;r=r.parent}return!1}function xe(e){let r=[];return e.traverse(t=>{let n=t;t.visible&&!Me(t)&&n.geometry&&r.push(t)}),_(r)}var Se=e=>1-Math.pow(1-e,3);function Ae(e,r,t,n,i,o=250){let a=e.position.clone(),c=r.target.clone(),s=performance.now(),l=()=>{let d=Se(Math.min((performance.now()-s)/o,1));e.position.lerpVectors(a,t,d),r.target.lerpVectors(c,n,d),i(),r.update(),d<1&&requestAnimationFrame(l)};requestAnimationFrame(l)}import*as D from"three";var De=`
2
+ varying vec3 vWorldPos;
3
+ void main() {
4
+ vec4 world = modelMatrix * vec4(position, 1.0);
5
+ vWorldPos = world.xyz;
6
+ gl_Position = projectionMatrix * viewMatrix * world;
7
+ }
8
+ `,Le=`
9
+ precision highp float;
10
+ varying vec3 vWorldPos;
11
+
12
+ uniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes
13
+ uniform float uCell;
14
+ uniform float uMajor;
15
+ uniform vec3 uCellColor;
16
+ uniform vec3 uMajorColor;
17
+ uniform vec3 uCenter; // fade center (camera position), projected onto plane
18
+ uniform float uFade;
19
+
20
+ // Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines
21
+ // stay ~1px regardless of zoom (the standard "pristine grid" technique).
22
+ float gridLine(vec2 coord, float spacing) {
23
+ vec2 c = coord / spacing;
24
+ vec2 d = fwidth(c);
25
+ vec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);
26
+ float line = min(g.x, g.y);
27
+ return 1.0 - clamp(line, 0.0, 1.0);
28
+ }
29
+
30
+ // Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).
31
+ float axis(vec3 v, float i) {
32
+ return i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);
33
+ }
34
+
35
+ void main() {
36
+ // Pick the two in-plane world coordinates.
37
+ vec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));
38
+
39
+ float minor = gridLine(coord, uCell);
40
+ float major = gridLine(coord, uCell * uMajor);
41
+
42
+ vec3 color = mix(uCellColor, uMajorColor, major);
43
+ float alpha = max(minor, major);
44
+
45
+ // Radial fade from the camera-projected center.
46
+ float dist = distance(vWorldPos, uCenter);
47
+ float fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);
48
+ alpha *= fade * fade;
49
+
50
+ if (alpha < 0.001) discard;
51
+ gl_FragColor = vec4(color, alpha);
52
+ }
53
+ `;function ne(e={}){let{cellSize:r=1,majorEvery:t=10,cellColor:n=8947848,majorColor:i=4473924,fadeDistance:o=100,plane:a="y"}=e,c=a==="y"?new D.Vector2(0,2):a==="z"?new D.Vector2(0,1):new D.Vector2(1,2),s=o*2.5,l=new D.PlaneGeometry(s,s);a==="y"?l.rotateX(-Math.PI/2):a==="x"&&l.rotateY(Math.PI/2);let d=new D.ShaderMaterial({vertexShader:De,fragmentShader:Le,transparent:!0,depthWrite:!1,side:D.DoubleSide,uniforms:{uAxes:{value:c},uCell:{value:r},uMajor:{value:t},uCellColor:{value:new D.Color(n)},uMajorColor:{value:new D.Color(i)},uCenter:{value:new D.Vector3},uFade:{value:o}}}),u=new D.Mesh(l,d);u.name="grid",u.userData.id="grid",u.renderOrder=-1;let p=new D.Vector3;return{object:u,update:E=>{a==="y"?(u.position.set(E.x,0,E.z),p.set(E.x,0,E.z)):a==="z"?(u.position.set(E.x,E.y,0),p.set(E.x,E.y,0)):(u.position.set(0,E.y,E.z),p.set(0,E.y,E.z)),d.uniforms.uCenter.value.copy(p)},setVisible:E=>{u.visible=E},dispose:()=>{l.dispose(),d.dispose()}}}import{ViewHelper as Oe}from"three/addons/helpers/ViewHelper.js";function re(e){let{camera:r,domElement:t,controls:n,controller:i}=e,o=new Oe(r,t);o.setLabels("X","Y","Z");let a=!0;return{render:s=>{if(!a)return;let l=s.autoClear;s.autoClear=!1,o.render(s),s.autoClear=l},update:s=>{o.animating&&o.update(s)},handleClick:s=>!a||(o.center.copy(n.target),!o.handleClick(s))?!1:(i.getProjection()==="orthographic"&&i.setProjection("perspective"),!0),get isAnimating(){return o.animating},setVisible:s=>{a=s},isVisible:()=>a,dispose:()=>o.dispose()}}import*as j from"three";import{LineSegmentsGeometry as Pe}from"three/addons/lines/LineSegmentsGeometry.js";import{LineSegments2 as oe}from"three/addons/lines/LineSegments2.js";import{LineMaterial as Ie}from"three/addons/lines/LineMaterial.js";var N="edge-overlay",Be=2236962,Ve=1.5,Fe=30;function ae(e,r={}){let t=new j.Color(r.color??Be),n=r.width??Ve,i=r.thresholdAngle??Fe,o=[];return e.traverse(a=>{if(!(a instanceof j.Mesh)||a.userData.id==="floor"||a.userData.id==="grid"||a.userData.kind===N||a.children.some(s=>s.userData?.kind===N)||!a.geometry)return;let c=ze(a.geometry,t,n,i);a.add(c),o.push(c)}),o}function ze(e,r,t,n){let i=new j.EdgesGeometry(e,n),o=new Pe;o.setPositions(Array.from(i.attributes.position.array)),i.dispose();let a=new Ie({color:r});a.linewidth=t,a.polygonOffset=!0,a.polygonOffsetFactor=-1,a.polygonOffsetUnits=-1;let c=new oe(o,a);return c.userData.kind=N,c.raycast=()=>{},c}function ke(e){return e.userData?.kind===N}function Rn(e){let r=[];e.traverse(t=>{t instanceof oe&&ke(t)&&r.push(t)});for(let t of r)t.geometry.dispose(),t.material.dispose(),t.removeFromParent();return r.length}import{EffectComposer as je}from"three/addons/postprocessing/EffectComposer.js";import{RenderPass as _e}from"three/addons/postprocessing/RenderPass.js";import{GTAOPass as Ge}from"three/addons/postprocessing/GTAOPass.js";import{OutputPass as Ne}from"three/addons/postprocessing/OutputPass.js";function ie(e,r,t,n,i,o){let a=new je(e),c=new _e(r,t);a.addPass(c);let s=new Ge(r,t,n,i);s.blendIntensity=o.aoIntensity??1,s.updateGtaoMaterial({screenSpaceRadius:!0}),a.addPass(s);let l=new Ne;return a.addPass(l),e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure,a.setSize(n,i),{render:d=>a.render(d),setSize:(d,u,p)=>{a.setPixelRatio(p),a.setSize(d,u),s.setSize(d,u)},setCamera:d=>{c.camera=d,s.camera=d},dispose:()=>a.dispose()}}import*as se from"three";import{CSS2DRenderer as Ue,CSS2DObject as We}from"three/addons/renderers/CSS2DRenderer.js";function le(e,r){let t=new Ue,n=t.domElement;n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.overflow="hidden",n.style.pointerEvents="none",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(n);let i={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(i.width,i.height);let o=new se.Group;o.name="label-layer",o.userData.id="label-layer",r.add(o);let a=new Set;return{addLabel:(s,l,d)=>{let u=document.createElement("div");u.textContent=s,d&&(u.className=d),u.style.pointerEvents="none";let p=new We(u);return p.position.copy(l),o.add(p),a.add(p),{object:p,setPosition:E=>p.position.copy(E),setText:E=>{u.textContent=E},remove:()=>{p.removeFromParent(),u.remove(),a.delete(p)}}},render:(s,l)=>t.render(s,l),setSize:(s,l)=>t.setSize(s,l),dispose:()=>{a.forEach(s=>{s.removeFromParent(),s.element.remove()}),a.clear(),o.removeFromParent(),n.remove()}}}import*as A from"three";import{Line2 as $e}from"three/addons/lines/Line2.js";import{LineGeometry as Ye}from"three/addons/lines/LineGeometry.js";import{LineMaterial as Xe}from"three/addons/lines/LineMaterial.js";var qe=12,Ze=16763904,Je=e=>`${e.toPrecision(3)} m`;function Ke(e,r,t,n){let i=e.point.clone(),o=e.object;if(!(o instanceof A.Mesh)||e.face==null||!o.geometry)return i;let a=o.geometry.attributes.position;if(!a)return i;let c=u=>{let p=u.clone().project(r);return new A.Vector2((p.x+1)/2*t.width,(1-p.y)/2*t.height)},s=c(i),l=i,d=n;for(let u of[e.face.a,e.face.b,e.face.c]){let E=new A.Vector3().fromBufferAttribute(a,u).applyMatrix4(o.matrixWorld),m=c(E).distanceTo(s);m<d&&(d=m,l=E)}return l}function ce(e){let{canvas:r,scene:t,getActiveCamera:n,labelLayer:i,options:o={}}=e,a=o.snapPixels??qe,c=new A.Color(o.color??Ze),s=o.format??Je,l=new A.Raycaster,d=new A.Vector2,u=!1,p=[],E=[],m=null,v=null,S=new A.PointsMaterial({color:c,size:8,sizeAttenuation:!1,depthTest:!1}),T=g=>{let R=new A.BufferGeometry;R.setAttribute("position",new A.Float32BufferAttribute([g.x,g.y,g.z],3));let M=new A.Points(R,S);return M.renderOrder=999,M.userData.id="measure",M.raycast=()=>{},t.add(M),M},b=()=>{p.length=0,E.forEach(g=>{g.geometry.dispose(),g.removeFromParent()}),E.length=0,m&&(m.geometry.dispose(),m.material.dispose(),m.removeFromParent(),m=null),v?.remove(),v=null},H=()=>{if(p.length!==2)return;let[g,R]=p,M=new Ye;M.setPositions([g.x,g.y,g.z,R.x,R.y,R.z]);let y=new Xe({color:c});y.linewidth=2,y.depthTest=!1,m=new $e(M,y),m.renderOrder=998,m.userData.id="measure",m.raycast=()=>{},t.add(m);let L=g.clone().add(R).multiplyScalar(.5);v=i.addLabel(s(g.distanceTo(R)),L,o.labelClassName)};return{setEnabled:g=>{u=g,g||b()},isEnabled:()=>u,handleClick:g=>{if(!u)return!1;p.length===2&&b();let R=r.getBoundingClientRect();d.x=(g.clientX-R.left)/R.width*2-1,d.y=-((g.clientY-R.top)/R.height)*2+1;let M=n();l.setFromCamera(d,M);let y=l.intersectObjects(t.children,!0).filter(C=>C.object.userData.id!=="measure"&&C.object.userData.id!=="grid");if(y.length===0)return!0;let L=Ke(y[0],M,{width:R.width,height:R.height},a);return p.push(L),E.push(T(L)),p.length===2&&H(),!0},clear:b,dispose:()=>{b(),S.dispose()}}}import*as f from"three";import{OrbitControls as Qe}from"three/addons/controls/OrbitControls.js";import{HDRLoader as et}from"three/addons/loaders/HDRLoader.js";var de=new f.Vector3(0,0,1),Y=(e,r,t,n)=>{switch(e){case"mm":return r;case"cm":return t;default:return n}},Nn=function(e,r){let t=tt(r||{}),n=ot(t),i=dt(t,e),o=ut(e,t),a=pt(i,e,t),c=te({scene:n,perspective:i,controls:a,onActiveCameraChange:()=>{}}),s=()=>c.getActiveCamera();st(n,t),lt(n,t),t.floor?.enabled&&ct(n,t);let l=t.grid.enabled?ne({cellSize:t.grid.cellSize,majorEvery:t.grid.majorEvery,cellColor:t.grid.cellColor,majorColor:t.grid.majorColor,fadeDistance:t.grid.fadeDistance,plane:t.grid.plane}):null;l&&n.add(l.object);let d=t.gizmo.enabled?re({camera:i,domElement:e,controls:a,controller:c}):null,u=e.parentElement??e,p=t.measure.enabled?le(u,n):null,E=t.measure.enabled&&p?ce({canvas:e,scene:n,getActiveCamera:s,labelLayer:p,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,format:t.measure.format}}):null,m=t.events.enableEventHandlers!==!1?mt(e,n,s,i,a,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},v=C=>{if(E?.handleClick(C)){C.stopImmediatePropagation();return}d?.handleClick(C)&&C.stopImmediatePropagation()};(d||E)&&e.addEventListener("click",v,{capture:!0});let S=C=>{ae(C,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},T=e.parentElement,b=()=>T?{width:T.clientWidth,height:T.clientHeight}:{width:window.innerWidth,height:window.innerHeight},H=null,h=()=>{let{width:C,height:O}=b(),k=Math.min(window.devicePixelRatio,2),G=ie(o,n,s(),Math.max(1,C),Math.max(1,O),{toneMapping:t.render.toneMapping??f.NeutralToneMapping,toneMappingExposure:t.render.toneMappingExposure??1,aoIntensity:t.render.aoIntensity});return G.setSize(Math.max(1,C),Math.max(1,O),k),G},g=C=>{C&&!H?H=h():!C&&H&&(H.dispose(),H=null)};t.render.ambientOcclusion&&(H=h());let{animate:R,dispose:M}=it(o,n,i,s,c,a,b,t.events.onFrame,l,d,()=>H,p);R();let y=t.environment?.sceneUp||de;return n.up.set(y.x,y.y,y.z),{scene:n,camera:i,controls:a,renderer:o,cameraController:c,grid:l,gizmo:d,measureTool:E,applyEdges:S,setAmbientOcclusion:g,dispose:()=>{M(),m.dispose(),(d||E)&&e.removeEventListener("click",v,{capture:!0}),E?.dispose(),p?.dispose(),d?.dispose(),l?.dispose(),H?.dispose(),a.dispose(),o.dispose(),n.traverse(C=>{let O=C;!O.geometry&&!O.material||(O.geometry?.dispose(),Array.isArray(O.material)?O.material.forEach(k=>k.dispose()):O.material?.dispose())})},fitToView:m.fitToView,clearSelection:m.clearSelection}};function tt(e){let r=e.sceneScale||"m",n={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:e.camera?.position||new f.Vector3(-n.cameraDistance,n.cameraDistance,n.cameraDistance),fov:e.camera?.fov||20,near:e.camera?.near||n.near,far:e.camera?.far||n.far,target:e.camera?.target||new f.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity||1,sunlightPosition:e.lighting?.sunlightPosition||new f.Vector3(n.lightDistance,n.lightHeight,n.lightDistance),ambientLightColor:e.lighting?.ambientLightColor||new f.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity||1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new f.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||de,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||n.floorSize,color:e.floor?.color||new f.Color(8421504),roughness:e.floor?.roughness||.7,metalness:e.floor?.metalness||0,receiveShadow:e.floor?.receiveShadow??!0},render:{enableShadows:e.render?.enableShadows??!0,shadowMapSize:e.render?.shadowMapSize||2048,antialias:e.render?.antialias??!0,pixelRatio:e.render?.pixelRatio||Math.min(window.devicePixelRatio,2),toneMapping:e.render?.toneMapping||f.NeutralToneMapping,toneMappingExposure:e.render?.toneMappingExposure||1,preserveDrawingBuffer:e.render?.preserveDrawingBuffer??!1,ambientOcclusion:e.render?.ambientOcclusion??!1,aoIntensity:e.render?.aoIntensity??1},controls:{enableDamping:e.controls?.enableDamping??!1,dampingFactor:e.controls?.dampingFactor||.05,autoRotate:e.controls?.autoRotate??!1,autoRotateSpeed:e.controls?.autoRotateSpeed||.5,enableZoom:e.controls?.enableZoom??!0,enablePan:e.controls?.enablePan??!0,minDistance:e.controls?.minDistance||n.minDistance,maxDistance:e.controls?.maxDistance||1/0},grid:{enabled:e.grid?.enabled??!1,cellSize:e.grid?.cellSize??1,majorEvery:e.grid?.majorEvery??10,cellColor:e.grid?.cellColor??8947848,majorColor:e.grid?.majorColor??4473924,fadeDistance:e.grid?.fadeDistance??100,plane:e.grid?.plane??"y"},gizmo:{enabled:e.gizmo?.enabled??!1},edges:{enabled:e.edges?.enabled??!1,color:e.edges?.color??2236962,width:e.edges?.width??1.5,thresholdAngle:e.edges?.thresholdAngle??30},measure:{enabled:e.measure?.enabled??!1,snapPixels:e.measure?.snapPixels,color:e.measure?.color,labelClassName:e.measure?.labelClassName,format:e.measure?.format},events:{onBackgroundClicked:e.events?.onBackgroundClicked,onObjectSelected:e.events?.onObjectSelected,onMeshMetadataClicked:e.events?.onMeshMetadataClicked,onMeshDoubleClicked:e.events?.onMeshDoubleClicked,selectionColor:e.events?.selectionColor||"#ff0000",enableEventHandlers:e.events?.enableEventHandlers??!0,enableKeyboardControls:e.events?.enableKeyboardControls??!0,enableClickToFocus:e.events?.enableClickToFocus??!0,enableDoubleClickZoom:e.events?.enableDoubleClickZoom??!0,onReady:e.events?.onReady,onFrame:e.events?.onFrame}}}var nt=new Set(["grid","floor","label-layer","measure"]);function rt(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&nt.has(r.userData.id))return!0;r=r.parent}return!1}function ot(e){let r=new f.Scene,t=typeof e.environment.backgroundColor=="string"?new f.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function at(e,r,t,n,i=200){let o=e.position.clone(),a=r.target.clone(),c=performance.now(),s=d=>1-Math.pow(1-d,3),l=()=>{let d=performance.now()-c,u=s(Math.min(d/i,1));e.position.lerpVectors(o,t,u),r.target.lerpVectors(a,n,u),r.update(),u<1&&requestAnimationFrame(l)};requestAnimationFrame(l)}function it(e,r,t,n,i,o,a,c,s,l,d,u){let p=null,E=performance.now(),m=()=>{let{width:T,height:b}=a();if(T===0||b===0)return;let H=Math.min(window.devicePixelRatio,2),h=Math.round(T*H),g=Math.round(b*H);(e.domElement.width!==h||e.domElement.height!==g)&&(e.setPixelRatio(H),e.setSize(T,b,!1),t.aspect=T/b,t.updateProjectionMatrix(),i.updateAspect(T,b),d?.()?.setSize(T,b,H),u?.setSize(T,b))},v=function(){p=requestAnimationFrame(v);let T=performance.now(),b=(T-E)/1e3;E=T,m(),(o.enableDamping||o.autoRotate)&&o.update(),s&&s.update(n().position),l&&l.update(b),c?.(b);let H=n(),h=d?.();h?(h.setCamera(H),h.render(b)):e.render(r,H),u&&u.render(r,H),l&&l.render(e)};return{animate:v,dispose:()=>{p!==null&&(cancelAnimationFrame(p),p=null)}}}function st(e,r){r.environment.enableEnvironmentLighting?new et().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){if(!t?.image){w().warn("HDR loaded without image data; skipping environment map."),r.events.onReady?.();return}t.mapping=f.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t),r.events.onReady?.()},void 0,function(t){w().warn("HDR texture could not be loaded, falling back to basic lighting:",t),r.events.onReady?.()}):r.events.onReady?.()}function lt(e,r){let t=new f.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),r.lighting.enableSunlight){let n=new f.DirectionalLight(r.lighting.sunlightColor??16777215,r.lighting.sunlightIntensity),i=r.lighting.sunlightPosition;if(i&&n.position.set(i.x,i.y,i.z),r.render.enableShadows){n.castShadow=!0;let o=Y(r.sceneScale,.1,10,100);n.shadow.camera.left=-o,n.shadow.camera.right=o,n.shadow.camera.top=o,n.shadow.camera.bottom=-o;let a=Y(r.sceneScale,.001,.1,.5),c=Y(r.sceneScale,1,100,500);n.shadow.camera.near=a,n.shadow.camera.far=c,n.shadow.mapSize.width=r.render.shadowMapSize||2048,n.shadow.mapSize.height=r.render.shadowMapSize||2048,n.shadow.bias=-1e-4,n.shadow.normalBias=.02}e.add(n)}}function ct(e,r){let t=r.floor.size,n=new f.PlaneGeometry(t,t),i=typeof r.floor.color=="string"?new f.Color(r.floor.color):r.floor.color,o=new f.MeshStandardMaterial({color:i,roughness:r.floor.roughness,metalness:r.floor.metalness,side:f.DoubleSide}),a=new f.Mesh(n,o);a.userData.id="floor",a.name="floor",a.rotation.x=-Math.PI/2,a.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(a.receiveShadow=!0),e.add(a)}function dt(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,i=t?t.clientHeight:window.innerHeight,o=new f.PerspectiveCamera(e.camera.fov,n/i,e.camera.near,e.camera.far),a=e.camera.position;return a&&o.position.set(a.x,a.y,a.z),o}function ut(e,r){let t=new f.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,i=n?n.clientWidth:window.innerWidth,o=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(i,o,!1),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=f.VSMShadowMap),t.toneMapping=r.render.toneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=f.SRGBColorSpace,t.sortObjects=!0,t}function mt(e,r,t,n,i,o){let a=new Set,c=new Map,s=new f.Raycaster,l=new f.Vector2,d=new f.Vector2,u=h=>{let g=h;for(;g;){if(!g.visible)return!1;g=g.parent}return!0},p=()=>{let h=new f.Box3;if(r.traverse(O=>{let k=O;O.visible&&!rt(O)&&k.geometry&&h.expandByObject(O)}),h.isEmpty()){w().warn("No objects to fit to view");return}let g=h.getCenter(new f.Vector3),R=h.getSize(new f.Vector3),M=Math.max(R.x,R.y,R.z),y=n.fov*(Math.PI/180),L=M/(2*Math.tan(y/2));L*=1.5;let C=n.position.clone().sub(i.target);C.lengthSq()<1e-12&&C.set(.8,1,1.2),C.normalize(),n.position.copy(g.clone().add(C.multiplyScalar(L))),i.target.copy(g),i.update()},E=typeof o.events.selectionColor=="string"?new f.Color(o.events.selectionColor):o.events.selectionColor instanceof f.Color?o.events.selectionColor:new f.Color("#ff0000"),m=()=>{a.forEach(h=>{h instanceof f.Mesh&&c.has(h)&&(h.material=c.get(h),c.delete(h))}),a.clear()},v=h=>{d.set(h.clientX,h.clientY)},S=h=>{let g=new f.Vector2(h.clientX,h.clientY);if(d.distanceTo(g)>5)return;let R=e.getBoundingClientRect();l.x=(h.clientX-R.left)/R.width*2-1,l.y=-((h.clientY-R.top)/R.height)*2+1,s.setFromCamera(l,t());let M=s.intersectObjects(r.children,!0).filter(y=>u(y.object));if(M.length>0){let y=M[0].object;if(!a.has(y)){if(m(),a.add(y),y instanceof f.Mesh&&y.material instanceof f.Material){c.set(y,y.material);let L=y.material.clone();L.emissive=E.clone(),y.material=L}o.events?.onObjectSelected?.(y),y instanceof f.Mesh&&Object.keys(y.userData).length>0&&o.events?.onMeshMetadataClicked?.(y.userData)}}else m(),o.events?.onBackgroundClicked?.({x:l.x,y:l.y})},T=h=>{let g=e.getBoundingClientRect();l.x=(h.clientX-g.left)/g.width*2-1,l.y=-((h.clientY-g.top)/g.height)*2+1,s.setFromCamera(l,t());let R=s.intersectObjects(r.children,!0).filter(Te=>u(Te.object));if(R.length===0)return;let M=R[0].object;if(o.events?.onMeshDoubleClicked?.(M),!o.events?.enableDoubleClickZoom)return;let y=new f.Box3().setFromObject(M);if(y.isEmpty())return;let L=y.getCenter(new f.Vector3),C=y.getSize(new f.Vector3),O=Math.max(C.x,C.y,C.z),k=n.fov*(Math.PI/180),G=O/(2*Math.tan(k/2))*1.5,ye=n.position.clone().sub(i.target).normalize(),Re=L.clone().add(ye.multiplyScalar(G));at(n,i,Re,L)},b=h=>{if(o.events?.enableKeyboardControls)switch(h.key.toLowerCase()){case"f":h.preventDefault(),p();break;case"escape":h.preventDefault(),m();break;case" ":h.preventDefault(),p();break}};return o.events?.enableClickToFocus&&(e.addEventListener("mousedown",v),e.addEventListener("click",S),e.addEventListener("dblclick",T)),o.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",b)),{dispose:()=>{e.removeEventListener("mousedown",v),e.removeEventListener("click",S),e.removeEventListener("dblclick",T),e.removeEventListener("keydown",b),m()},fitToView:p,clearSelection:m}}function pt(e,r,t){let n=new Qe(e,r),i=t.camera.target;return i&&n.target.set(i.x,i.y,i.z),n.enableDamping=t.controls.enableDamping||!1,n.dampingFactor=t.controls.dampingFactor||.05,n.autoRotate=t.controls.autoRotate||!1,n.autoRotateSpeed=t.controls.autoRotateSpeed||.5,n.enableZoom=t.controls.enableZoom??!0,n.enablePan=t.controls.enablePan??!0,n.minDistance=t.controls.minDistance||.001,n.maxDistance=t.controls.maxDistance||1/0,n.screenSpacePanning=!1,n.maxPolarAngle=Math.PI,n.update(),n}var Tt={};we(Tt,{CONCRETE_MATERIAL:()=>ht,EMISSIVE_MATERIAL:()=>ft,GLASS_MATERIAL:()=>bt,METAL_MATERIAL:()=>Et,PLASTIC_MATERIAL:()=>gt,RUBBER_MATERIAL:()=>yt,WOOD_MATERIAL:()=>Rt});import*as x from"three";var ft=new x.MeshPhysicalMaterial({color:0,emissive:new x.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:x.FrontSide,dithering:!0}),Et=new x.MeshPhysicalMaterial({color:new x.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:x.FrontSide,dithering:!0}),ht=new x.MeshPhysicalMaterial({color:new x.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:x.FrontSide,dithering:!0}),gt=new x.MeshPhysicalMaterial({color:new x.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:x.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),bt=new x.MeshPhysicalMaterial({color:new x.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:x.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),yt=new x.MeshPhysicalMaterial({color:new x.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:x.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Rt=new x.MeshPhysicalMaterial({color:new x.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:x.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});import*as V from"three";import{Line2 as wt}from"three/addons/lines/Line2.js";import{LineGeometry as Ht}from"three/addons/lines/LineGeometry.js";import{LineMaterial as Ct}from"three/addons/lines/LineMaterial.js";function U(e,r,t,n=!0){return n?{x:e,y:t,z:-r}:{x:e,y:r,z:t}}var vt="#ffffff",X=12,Mt=4e-4,xt=12,St=.05;function ue(e,r={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:n=!0}=r,i=[];for(let o of e)switch(o.kind){case"curve":{let a=Dt(o,t,n);a&&i.push(a);break}case"point":{i.push(Lt(o,n));break}default:{let a=o;w().warn(`Skipping unknown display item kind: ${String(a.kind)}`);break}}return i}var At=2;function Dt(e,r,t){if(!r)return w().warn("No rhino3dm instance provided; skipping curve display item."),null;let n=Ot(e.json,r);if(!n)return null;let i=Pt(n,t);if(i.length<2)return null;let o=[];for(let u of i)o.push(u.x,u.y,u.z);let a=new Ht;a.setPositions(o);let c=me(e.color,e.opacity),s=new Ct({color:c.color}),l=s;l.linewidth=e.width??At,l.transparent=c.transparent,l.opacity=c.opacity;let d=new wt(a,s);return d.computeLineDistances(),d.name=e.name,d.userData={id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},d}function Lt(e,r){let{x:t,y:n,z:i}=U(e.position.X,e.position.Y,e.position.Z,r),o=new V.BufferGeometry;o.setAttribute("position",new V.Float32BufferAttribute([t,n,i],3));let a=new V.PointsMaterial({...me(e.color,e.opacity),size:6,sizeAttenuation:!1}),c=new V.Points(o,a);return c.name=e.name,c.userData={id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},c}function Ot(e,r){try{let t=JSON.parse(e),n=r.CommonObject.decode(t);return n&&typeof n.pointAt=="function"?n:(w().warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return w().warn("Failed to decode curve display item JSON:",t),null}}function Pt(e,r){let t=It(e,r);return t||Bt(e,r)}function It(e,r){if(!e.isPolyline())return null;let t=e.tryGetPolyline(),n=Array.isArray(t)?t[1]:t;if(!n||typeof n.count!="number"||n.count<2)return null;let i=[];for(let o=0;o<n.count;o++){let a=n.get(o),{x:c,y:s,z:l}=U(a[0],a[1],a[2],r);i.push(new V.Vector3(c,s,l))}return i}function Bt(e,r){let t=e.domain,n=t[0],o=t[1]-n,a=l=>{let d=e.pointAt(l),{x:u,y:p,z:E}=U(d[0],d[1],d[2],r);return new V.Vector3(u,p,E)},c=Vt(e),s=[a(n)];for(let l=0;l<X;l++){let d=n+o*l/X,u=n+o*(l+1)/X;q(d,a(d),u,a(u),a,c,xt,s),s.push(a(u))}return s}function q(e,r,t,n,i,o,a,c){if(a<=0)return;let s=(e+t)/2,l=i(s),d=zt(l,r,n),u=Ft(r,l,n);d<=o&&u<=St||(q(e,r,s,l,i,o,a-1,c),c.push(l),q(s,l,t,n,i,o,a-1,c))}function Vt(e){let r=e.getBoundingBox(),t=r.min,n=r.max,i=Math.hypot(n[0]-t[0],n[1]-t[1],n[2]-t[2]);return Math.max(i*Mt,1e-6)}function Ft(e,r,t){let n=r.clone().sub(e),i=t.clone().sub(r),o=n.length(),a=i.length();if(o===0||a===0)return 0;let c=Math.max(-1,Math.min(1,n.dot(i)/(o*a)));return Math.acos(c)}function zt(e,r,t){let n=t.clone().sub(r),i=n.lengthSq();if(i===0)return e.distanceTo(r);let o=Math.max(0,Math.min(1,e.clone().sub(r).dot(n)/i)),a=r.clone().addScaledVector(n,o);return e.distanceTo(a)}function me(e,r){let t=r??1;return{color:new V.Color(e??vt),transparent:t<1,opacity:t}}var pe=1096174675,fe=1,Z=1,Ee=12,he=56;function J(e){let r=kt(e),t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Ee)throw z("Blob too small to contain SLVA header.",{expectedBytes:Ee,availableBytes:r.byteLength});let n=0,i=t.getUint32(n,!0);if(n+=4,i!==pe)throw z(`Invalid SLVA magic: 0x${i.toString(16)}`,{expectedMagic:`0x${pe.toString(16)}`,actualMagic:`0x${i.toString(16)}`});let o=t.getUint32(n,!0);if(n+=4,o!==fe)throw z(`Unsupported SLVA version: ${o}`,{expectedVersion:fe,actualVersion:o});let a=t.getUint32(n,!0);if(n+=4,n+a>r.byteLength)throw z("Insufficient data to read metadata JSON.",{expectedBytes:a,availableBytes:r.byteLength-n,offset:n});let c=r.subarray(n,n+a);n+=a;let s;try{s=JSON.parse(jt(c))}catch(C){throw z(`Failed to parse metadata JSON: ${C instanceof Error?C.message:String(C)}`,{metadataLen:a})}if(n+he>r.byteLength)throw z("Insufficient data to read geometry header.",{expectedBytes:he,availableBytes:r.byteLength-n,offset:n});let l=t.getUint32(n,!0);n+=4;let d=t.getFloat64(n,!0);n+=8;let u=t.getFloat64(n,!0);n+=8;let p=t.getFloat64(n,!0);n+=8;let E=t.getFloat64(n,!0);n+=8;let m=t.getFloat64(n,!0);n+=8;let v=t.getFloat64(n,!0);n+=8;let S=t.getUint32(n,!0);n+=4;let T=(l&Z)!==0,b=S*3,h=b*(T?4:2);if(n+h>r.byteLength)throw z("Insufficient data to read vertices.",{expectedBytes:h,availableBytes:r.byteLength-n,offset:n,useFloat32:T,vertexCount:S});let g=r.byteOffset+n,R=T?Gt(r.buffer,g,b):_t(r.buffer,g,b);if(n+=h,n+4>r.byteLength)throw z("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-n,offset:n});let M=t.getUint32(n,!0);n+=4;let y=M*4;if(n+y>r.byteLength)throw z("Insufficient data to read indices.",{expectedBytes:y,availableBytes:r.byteLength-n,offset:n,indexCount:M});let L=Nt(r.buffer,r.byteOffset+n,M);return{metadata:s,flags:l,vertices:R,indices:L,origin:[d,u,p],scale:[E,m,v]}}function kt(e){return typeof e=="string"?K(e):e instanceof Uint8Array?e:new Uint8Array(e)}function jt(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new $("No UTF-8 decoder available in this environment.",W.INVALID_STATE)}function _t(e,r,t){if(t===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,t);let n=new Uint8Array(t*2);return n.set(new Uint8Array(e,r,t*2)),new Int16Array(n.buffer)}function Gt(e,r,t){if(t===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,t);let n=new Uint8Array(t*4);return n.set(new Uint8Array(e,r,t*4)),new Float32Array(n.buffer)}function Nt(e,r,t){if(t===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,t);let n=new Uint8Array(t*4);return n.set(new Uint8Array(e,r,t*4)),new Uint32Array(n.buffer)}function z(e,r){return new $(e,W.VALIDATION_ERROR,{context:r})}import*as I from"three";async function ge(e,r){let{debug:t=!1}=r??{},n=t?performance.now():0;try{let i=performance.now(),o=JSON.parse(e),a=performance.now()-i;return await Ut(o,r,{parseTime:a,perfStart:n})}catch(i){return w().error("Error parsing mesh batch:",i),[]}}async function Ut(e,r,t){let{mergeByMaterial:n=!0,applyTransforms:i=!0,scaleFactor:o=1,debug:a=!1}=r??{},{parseTime:c=0,perfStart:s=a?performance.now():0}=t??{};try{let l=performance.now(),d=J(e.compressedData),u=performance.now()-l,p=a?Zt(e.compressedData):0;return be(d,{mergeByMaterial:n,applyTransforms:i,scaleFactor:o,debug:a,parseTime:c,decodeTime:u,perfStart:s,blobBytes:p,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(l){return w().error("Error parsing mesh batch object:",l),[]}}async function or(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:i=1,debug:o=!1}=r??{},a=o?performance.now():0;try{let c=performance.now(),s=J(e),l=performance.now()-c,d=e.byteLength;return be(s,{mergeByMaterial:t,applyTransforms:n,scaleFactor:i,debug:o,parseTime:0,decodeTime:l,perfStart:a,blobBytes:d})}catch(c){return w().error("Error parsing mesh batch blob:",c),[]}}function be(e,r){let{mergeByMaterial:t,applyTransforms:n,scaleFactor:i,debug:o,parseTime:a,decodeTime:c,perfStart:s,blobBytes:l,fallback:d}=r,u=e.metadata.materials??d?.materials??[],p=e.metadata.groups??d?.groups??[],E=e.metadata.sourceComponentId??d?.sourceComponentId,m=(e.flags&Z)!==0,v=m?$t(e.vertices,n):Wt(e.vertices,e.origin,e.scale,n);if(o){let h=e.vertices.byteLength+e.indices.byteLength;w().debug("Mesh Batch Stats:"),w().debug(` Materials: ${u.length} | Groups: ${p.length}`),w().debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),w().debug(` Format: ${m?"float32":"int16 quantized"}`),w().debug(` Blob: ${(l/1024/1024).toFixed(2)} MB | Geometry on wire: ${(h/1024/1024).toFixed(2)} MB`)}let S=performance.now(),T=u.map(Yt),b=[];for(let h of p)if(t&&h.meshes.length>1){let g=Xt(h,v,e.indices,T);g.userData.sourceComponentId=E??null,b.push(g)}else{let g=qt(h,v,e.indices,T);for(let R of g)R.userData.sourceComponentId=E??null;b.push(...g)}if(i!==1)for(let h of b)h.scale.set(i,i,i);let H=performance.now()-S;if(o){let h=performance.now()-s;w().debug("Performance:"),a>0&&w().debug(` Parse JSON: ${a.toFixed(2)}ms`),w().debug(` Decode binary: ${c.toFixed(2)}ms`),w().debug(` Create Meshes: ${H.toFixed(2)}ms`),w().debug(` Total: ${h.toFixed(2)}ms`)}return Promise.resolve(b)}function Wt(e,r,t,n){let i=new Float32Array(e.length),o=r[0],a=r[1],c=r[2],s=t[0],l=t[1],d=t[2];if(n)for(let u=0;u<e.length;u+=3){let p=o+(e[u]+32767)*s,E=a+(e[u+1]+32767)*l,m=c+(e[u+2]+32767)*d;i[u]=p,i[u+1]=m,i[u+2]=-E}else for(let u=0;u<e.length;u+=3)i[u]=o+(e[u]+32767)*s,i[u+1]=a+(e[u+1]+32767)*l,i[u+2]=c+(e[u+2]+32767)*d;return i}function $t(e,r){if(!r)return e;let t=new Float32Array(e.length);for(let n=0;n<e.length;n+=3){let i=e[n],o=e[n+1],a=e[n+2];t[n]=i,t[n+1]=a,t[n+2]=-o}return t}function Yt(e){let r=Q(e.color);return new I.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:I.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function Xt(e,r,t,n){let i=0,o=0;for(let m of e.meshes)i+=m.vertexCount,o+=m.indexCount;let a=new Float32Array(i*3),c=new Uint32Array(o),s=0,l=0;for(let m of e.meshes){let v=m.vertexStart*3,S=m.vertexCount*3;a.set(r.subarray(v,v+S),s*3);let T=t.subarray(m.indexStart,m.indexStart+m.indexCount),b=s-m.vertexStart;if(b===0)c.set(T,l);else for(let H=0;H<T.length;H++)c[l+H]=T[H]+b;s+=m.vertexCount,l+=m.indexCount}let d=new I.BufferGeometry;d.setAttribute("position",new I.BufferAttribute(a,3)),d.setIndex(new I.BufferAttribute(c,1)),d.computeVertexNormals();let u=new I.Mesh(d,n[e.materialId]),p=e.meshes[0],E=e.meshes.map(m=>m.name).filter(m=>m&&m.length>0);return u.name=E.length>0?E[0]:`merged_material_${e.materialId}`,u.castShadow=!0,u.receiveShadow=!0,u.userData={name:u.name,layer:p?.layer??"",originalIndex:p?.originalIndex??0,metadata:p?.metadata??{},mergedFrom:e.meshes.slice(1).map(m=>({name:m.name,layer:m.layer,originalIndex:m.originalIndex}))},u}function qt(e,r,t,n){let i=[];for(let o of e.meshes){let a=o.vertexStart*3,c=o.vertexCount*3,s=r.slice(a,a+c),l=t.subarray(o.indexStart,o.indexStart+o.indexCount),d=new Uint32Array(l.length),u=o.vertexStart;for(let m=0;m<l.length;m++)d[m]=l[m]-u;let p=new I.BufferGeometry;p.setAttribute("position",new I.BufferAttribute(s,3)),p.setIndex(new I.BufferAttribute(d,1)),p.computeVertexNormals();let E=new I.Mesh(p,n[e.materialId]);E.name=o.name,E.userData={name:o.name,layer:o.layer??"",originalIndex:o.originalIndex,metadata:o.metadata??{}},E.castShadow=!0,E.receiveShadow=!0,i.push(E)}return i}function Zt(e){return Math.floor(e.length*3/4)}var Jt={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},Kt="Display";async function dr(e,r){let t=performance.now(),n=[],{allowScaling:i=!0,allowAutoPosition:o=!0,rhino:a,debug:c=!1,parsing:s={}}=r??{};try{let l=i?Qt(e.modelunits):1;return await en(e,n,l,s,a,c),o&&on(n),n}catch(l){throw an(l,n),l}finally{c&&ln(t)}}function Qt(e){return Jt[e]??1}async function en(e,r,t,n,i,o){for(let a of e.values){let c=a.InnerTree;for(let s in c){let l=c[s];l&&await tn(l,r,t,n,i,o)}}}async function tn(e,r,t,n,i,o){for(let a of e){if(!a.type.includes(Kt))continue;let c={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},s=await ge(a.data,c),l=ue(nn(a.data),{rhino:i,applyTransforms:c.applyTransforms}),d=[...s,...l];if(t!==1)for(let u of d)u.scale.set(t,t,t);r.push(...d),o&&w().debug(`Extracted ${s.length} meshes and ${l.length} items from batch`)}}function nn(e){return(typeof e=="string"?rn(e):e)?.items}function rn(e){try{return JSON.parse(e)}catch{return}}function on(e){if(e.length===0)return;let t=_(e).min.y;ee(e,t)}function an(e,r){w().error("An unexpected error occurred:",e),sn(r)}function sn(e){for(let r of e){let t=r;t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose())}}function ln(e){let r=performance.now()-e;w().info("Time to process meshes:",`${r.toFixed(2)}ms`)}export{dn as a,Q as b,ee as c,_ as d,te as e,ne as f,re as g,N as h,ae as i,ke as j,Rn as k,ie as l,le as m,Ke as n,ce as o,Nn as p,Tt as q,ue as r,pe as s,fe as t,Z as u,J as v,ge as w,Ut as x,or as y,Jt as z,dr as A};
54
+ //# sourceMappingURL=chunk-Z4TVQVMV.js.map