@selvajs/compute 2.1.0 → 2.3.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-NFPYFIYS.cjs → chunk-3GX67Y6H.cjs} +5 -5
- package/dist/{chunk-NFPYFIYS.cjs.map → chunk-3GX67Y6H.cjs.map} +1 -1
- package/dist/chunk-4UOOVSGL.cjs +4 -0
- package/dist/{chunk-BTH6J34X.cjs.map → chunk-4UOOVSGL.cjs.map} +1 -1
- package/dist/chunk-AXAMGKTJ.js +4 -0
- package/dist/chunk-AXAMGKTJ.js.map +1 -0
- package/dist/{chunk-6L56B3Q3.js → chunk-TPVXQREC.js} +2 -2
- package/dist/chunk-TPVXQREC.js.map +1 -0
- package/dist/{chunk-HG24GZ3A.cjs → chunk-XFKKZQUK.cjs} +2 -2
- package/dist/{chunk-HG24GZ3A.cjs.map → chunk-XFKKZQUK.cjs.map} +1 -1
- package/dist/{chunk-UQ7TD57L.js → chunk-XULKNW75.js} +5 -5
- package/dist/{chunk-UQ7TD57L.js.map → chunk-XULKNW75.js.map} +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.d.cts +3 -3
- package/dist/core.d.ts +3 -3
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.d.cts +9 -8
- package/dist/grasshopper.d.ts +9 -8
- package/dist/grasshopper.js +1 -1
- package/dist/{handle-files-D-_fiXu4.d.cts → handle-files-VUQET1YU.d.cts} +162 -4
- package/dist/{handle-files-D-_fiXu4.d.ts → handle-files-VUQET1YU.d.ts} +162 -4
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/{types-jPuWWtnU.d.ts → types-CIsBR_xd.d.ts} +1 -1
- package/dist/{types-D1SkNje_.d.cts → types-ChF690kY.d.cts} +4 -3
- package/dist/{types-D1SkNje_.d.ts → types-ChF690kY.d.ts} +4 -3
- package/dist/{types-BuRCHPlb.d.cts → types-DqSisB8v.d.cts} +1 -1
- package/dist/{visualization-42QQ22YF.js → visualization-TRW2EKLH.js} +2 -2
- package/dist/visualization-WRUF5FKI.cjs +2 -0
- package/dist/{visualization-6ZLI4ANV.cjs.map → visualization-WRUF5FKI.cjs.map} +1 -1
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.d.cts +3 -3
- package/dist/visualization.d.ts +3 -3
- package/dist/visualization.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-6L56B3Q3.js.map +0 -1
- package/dist/chunk-BTH6J34X.cjs +0 -4
- package/dist/chunk-H2FJSNMM.js +0 -4
- package/dist/chunk-H2FJSNMM.js.map +0 -1
- package/dist/visualization-6ZLI4ANV.cjs +0 -2
- /package/dist/{visualization-42QQ22YF.js.map → visualization-TRW2EKLH.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkBTH6J34Xcjs = require('./chunk-BTH6J34X.cjs');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 C(t,e){e||typeof window<"u"&&_chunkBTH6J34Xcjs.e.call(void 0, ).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 _chunkBTH6J34Xcjs.d&&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(_nullishCoalesce(p(o,"paramName"), () => ("<unnamed>")))}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;_chunkBTH6J34Xcjs.e.call(void 0, ).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&&C("solveGrasshopperDefinition",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning)));let{response:n}=await N(P(e,t),r);return n}async function X(t,e,r){return r.debug&&C("solveGrasshopperDefinitionWithCacheKey",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning))),N(P(e,t),r)}async function Z(t,e,r,n){n.debug&&C("solveByCacheKey",_nullishCoalesce(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 _chunkBTH6J34Xcjs.h.call(void 0, "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=_chunkBTH6J34Xcjs.p.call(void 0, t):/^https?:\/\//i.test(t)?r.pointer=t:_chunkBTH6J34Xcjs.n.call(void 0, t)?r.algo=t:r.algo=_chunkBTH6J34Xcjs.m.call(void 0, 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 S=class{constructor(e,r,n={},s){_chunkBTH6J34Xcjs.b.call(void 0, this,"executor");_chunkBTH6J34Xcjs.b.call(void 0, this,"baseConfig");_chunkBTH6J34Xcjs.b.call(void 0, this,"mode");_chunkBTH6J34Xcjs.b.call(void 0, this,"maxConcurrent");_chunkBTH6J34Xcjs.b.call(void 0, this,"timeoutMs");_chunkBTH6J34Xcjs.b.call(void 0, this,"retry");_chunkBTH6J34Xcjs.b.call(void 0, this,"cacheEnabled");_chunkBTH6J34Xcjs.b.call(void 0, this,"cacheMax");_chunkBTH6J34Xcjs.b.call(void 0, this,"cacheTtl");_chunkBTH6J34Xcjs.b.call(void 0, this,"cache",new Map);_chunkBTH6J34Xcjs.b.call(void 0, this,"cacheKeyExecutor");_chunkBTH6J34Xcjs.b.call(void 0, this,"reuseServerDefinitionCache");_chunkBTH6J34Xcjs.b.call(void 0, this,"serverCacheKeys",new Map);_chunkBTH6J34Xcjs.b.call(void 0, this,"onStart");_chunkBTH6J34Xcjs.b.call(void 0, this,"onSettle");_chunkBTH6J34Xcjs.b.call(void 0, this,"onSuperseded");_chunkBTH6J34Xcjs.b.call(void 0, this,"subscribers",new Set);_chunkBTH6J34Xcjs.b.call(void 0, this,"inFlight",new Set);_chunkBTH6J34Xcjs.b.call(void 0, this,"pendingForLatestWins",null);_chunkBTH6J34Xcjs.b.call(void 0, this,"fifoQueue",[]);_chunkBTH6J34Xcjs.b.call(void 0, this,"_lastResult",null);_chunkBTH6J34Xcjs.b.call(void 0, this,"_lastError",null);_chunkBTH6J34Xcjs.b.call(void 0, this,"_lastDurationMs",null);_chunkBTH6J34Xcjs.b.call(void 0, this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=_nullishCoalesce(n.mode, () => ("latest-wins")),this.maxConcurrent=Math.max(1,_nullishCoalesce(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=_nullishCoalesce(a.maxEntries, () => (50)),this.cacheTtl=_nullishCoalesce(a.ttlMs, () => (0)),this.reuseServerDefinitionCache=!!s&&(_nullishCoalesce(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){_chunkBTH6J34Xcjs.e.call(void 0, ).error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new (0, _chunkBTH6J34Xcjs.d)("SolveScheduler has been disposed and cannot be used",_chunkBTH6J34Xcjs.c.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:_optionalChain([n, 'optionalAccess', _2 => _2.signal])};if(_optionalChain([u, 'access', _3 => _3.externalSignal, 'optionalAccess', _4 => _4.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();_optionalChain([e, 'access', _5 => _5.externalSignal, 'optionalAccess', _6 => _6.addEventListener, 'call', _7 => _7("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{_optionalChain([e, 'access', _8 => _8.externalSignal, 'optionalAccess', _9 => _9.removeEventListener, 'call', _10 => _10("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=_nullishCoalesce(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 (0, _chunkBTH6J34Xcjs.d)("Superseded by newer solve",_chunkBTH6J34Xcjs.c.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new (0, _chunkBTH6J34Xcjs.d)("Request aborted by caller",_chunkBTH6J34Xcjs.c.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 _chunkBTH6J34Xcjs.d?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new (0, _chunkBTH6J34Xcjs.d)(e instanceof Error?e.message:String(e),_chunkBTH6J34Xcjs.c.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){_chunkBTH6J34Xcjs.e.call(void 0, ).error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){_chunkBTH6J34Xcjs.b.call(void 0, this,"config");_chunkBTH6J34Xcjs.b.call(void 0, this,"serverStats");_chunkBTH6J34Xcjs.b.call(void 0, this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new (0, _chunkBTH6J34Xcjs.j)(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(_nullishCoalesce(_optionalChain([e, 'access', _11 => _11.retry, 'optionalAccess', _12 => _12.attempts]), () => (2)))+1),s=_nullishCoalesce(_optionalChain([e, 'access', _13 => _13.retry, 'optionalAccess', _14 => _14.baseDelayMs]), () => (250)),o=_nullishCoalesce(_optionalChain([e, 'access', _15 => _15.retry, 'optionalAccess', _16 => _16.maxDelayMs]), () => (1e3));for(let a=0;a<n;a++){if(await r.serverStats.isServerOnline())return r;if(a<n-1){let i=Math.min(s*2**a,o);await new Promise(u=>setTimeout(u,i))}}throw await r.dispose(),new (0, _chunkBTH6J34Xcjs.d)("Rhino Compute server is not online",_chunkBTH6J34Xcjs.c.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),V(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),w(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!_optionalChain([e, 'optionalAccess', _17 => _17.trim, 'call', _18 => _18()]))throw new (0, _chunkBTH6J34Xcjs.d)("Definition URL/content is required",_chunkBTH6J34Xcjs.c.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new (0, _chunkBTH6J34Xcjs.d)("Definition content is empty",_chunkBTH6J34Xcjs.c.INVALID_INPUT);let s={...this.config,..._optionalChain([n, 'optionalAccess', _19 => _19.signal])!==void 0&&{signal:n.signal},..._optionalChain([n, 'optionalAccess', _20 => _20.timeoutMs])!==void 0&&{timeoutMs:n.timeoutMs},..._optionalChain([n, 'optionalAccess', _21 => _21.retry])!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(_optionalChain([o, 'optionalAccess', _22 => _22.errors])&&o.errors.length>0)throw new (0, _chunkBTH6J34Xcjs.d)(o.errors.join("; ")||"Computation failed",_chunkBTH6J34Xcjs.c.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&&_chunkBTH6J34Xcjs.e.call(void 0, ).error("Compute failed:",s),s instanceof _chunkBTH6J34Xcjs.d?s:new (0, _chunkBTH6J34Xcjs.d)(s instanceof Error?s.message:String(s),_chunkBTH6J34Xcjs.c.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 S(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new (0, _chunkBTH6J34Xcjs.d)("GrasshopperClient has been disposed and cannot be used",_chunkBTH6J34Xcjs.c.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_chunkBTH6J34Xcjs.i.call(void 0, e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:_nullishCoalesce(e.debug, () => (!1)),suppressBrowserWarning:_nullishCoalesce(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 we(t){return!t||typeof t!="object"?null:_nullishCoalesce(_nullishCoalesce(t.data, () => (t.value)), () => (null))}function oe(t,e,r){let n=Re(e);if(n)try{return n(r,t)}catch(s){_chunkBTH6J34Xcjs.e.call(void 0, ).warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=we(t);if(s)return r.CommonObject.decode(s)}catch(s){return _chunkBTH6J34Xcjs.e.call(void 0, ).warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ee="Rhino.Geometry.",ve=["WebDisplay"],Ae="FileData";function ae(t){return ve.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 (e2){return n}return n}catch (e3){return t}}function Oe(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ee)?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={},i=new Set;for(let u of t.values)M(u.InnerTree,m=>{if(ae(m.type)||o&&m.type!==I.STRING)return;let f=e?m.id:u.ParamName;if(!f)return;let y=ue(m.data,m.type,n,s);f in a?i.has(f)?a[f].push(y):(a[f]=[a[f],y],i.add(f)):a[f]=y});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 m=!1;return M(u.InnerTree,f=>{f.id===e.byId&&(m=!0)}),m}),!a)return;let i=[];if(M(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||ae(u.type)||o&&u.type!==I.STRING)return;let m=ue(u.data,u.type,n,s);i.push(m)}),i.length!==0)return i.length===1?i[0]:i}var E=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 Promise.resolve().then(() => _interopRequireWildcard(require("./visualization-6ZLI4ANV.cjs"))))}catch(s){throw new (0, _chunkBTH6J34Xcjs.d)("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",_chunkBTH6J34Xcjs.c.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return le(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await _chunkBTH6J34Xcjs.r.call(void 0, 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 "${_nullishCoalesce(t.name, () => ("unknown"))}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return _chunkBTH6J34Xcjs.e.call(void 0, ).warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=_nullishCoalesce(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 m=Number(i);return Number.isNaN(m)?i:m}if(u==="System.Boolean")return i.toLowerCase()==="true";if(_optionalChain([u, 'optionalAccess', _23 => _23.startsWith, 'call', _24 => _24("Rhino.Geometry")]))try{return JSON.parse(i)}catch (e4){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 v(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 x(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.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(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:(_chunkBTH6J34Xcjs.e.call(void 0, ).warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return _chunkBTH6J34Xcjs.e.call(void 0, ).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 g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),T=Math.pow(10,-b),$=Number(T.toFixed(b));return Math.abs($-T)<e?$:T}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let y=Number(s[1]);if(y<0||n.toLowerCase().includes("e-")){let g=Math.abs(y),b=Math.pow(10,-g),T=Number(b.toFixed(g));return Math.abs(T-b)<e?T:b}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 m=Math.pow(10,-u),f=Number(m.toFixed(u));return Math.abs(f-m)<e?f:m}function We(t,e=1e-8){let r=t.paramType==="Integer";if(v(t.default))return{default:t.default,stepSize:r?1:.1};let n=x(t.default,Ge,!0);if(r)return Array.isArray(n)?n=n.map(f=>typeof f=="number"?Math.round(f):f):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),m=u.toLowerCase().match(/e(-?\d+)/);if(m?i=Math.abs(Number(m[1])):i=_nullishCoalesce(_optionalChain([u, 'access', _25 => _25.split, 'call', _26 => _26("."), 'access', _27 => _27[1], 'optionalAccess', _28 => _28.length]), () => (0)),i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let f=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(f)&&f>0&&(i=f)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(f=>typeof f=="number"?me(f,i,e):f):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=(_nullishCoalesce(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=x(t.default,Ve,!1)}catch(n){throw n instanceof Error?new (0, _chunkBTH6J34Xcjs.d)(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},Ue={types:["Text"],parse(t,e){let r=x(t.default,ke,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(_nullishCoalesce(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 _chunkBTH6J34Xcjs.d.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)||_chunkBTH6J34Xcjs.e.call(void 0, ).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=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"ValueList",values:_nullishCoalesce(t.values, () => ({})),default:r?[t.default]:t.default}}},he={types:["Geometry"],parse(t,e){let r=x(t.default,de(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},ze={types:["File"],parse(t,e){let r=x(t.default,de(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"File",default:r?[null]:null}}},$e={types:["Color"],parse(t,e){let r=x(t.default,Me,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(_nullishCoalesce(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 _nullishCoalesce(qe.get(_optionalChain([t, 'optionalAccess', _29 => _29.toLowerCase, 'call', _30 => _30()])), () => (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:_nullishCoalesce(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 _chunkBTH6J34Xcjs.d.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof _chunkBTH6J34Xcjs.d)return _chunkBTH6J34Xcjs.e.call(void 0, ).error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(_nullishCoalesce(a, () => (ye))).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new (0, _chunkBTH6J34Xcjs.d)(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:_nullishCoalesce(p(t,"nickname"), () => (null)),description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:_nullishCoalesce(p(t,"minimum"), () => (null)),maximum:_nullishCoalesce(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:_nullishCoalesce(p(t,"groupName"), () => (""))}}function Ce(t){return{name:p(t,"name"),nickname:_nullishCoalesce(p(t,"nickname"), () => (null)),paramType:p(t,"paramType"),id:p(t,"id")}}async function w(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 (0, _chunkBTH6J34Xcjs.d)("Definition must resolve to either a URL pointer or base64 algo",_chunkBTH6J34Xcjs.c.INVALID_INPUT,{context:{definition:t}});let s=await _chunkBTH6J34Xcjs.h.call(void 0, "io",n,e);if(!s||typeof s!="object")throw new (0, _chunkBTH6J34Xcjs.d)("Invalid IO response structure",_chunkBTH6J34Xcjs.c.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){C("fetchParsedDefinitionIO",_nullishCoalesce(e.suppressBrowserWarning, () => (e.suppressClientSideWarning)));let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await w(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){_chunkBTH6J34Xcjs.b.call(void 0, this,"innerTree");_chunkBTH6J34Xcjs.b.call(void 0, 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&&v(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 m=e,f=m.findIndex(y=>y.getParamName()===r);return f!==-1?m[f]=o:m.push(o),m}let a=e,i=o.toComputeFormat(),u=a.findIndex(m=>m.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return v(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(!_optionalChain([n, 'optionalAccess', _31 => _31.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=>_optionalChain([a, 'optionalAccess', _32 => _32.data])!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):_optionalChain([o, 'optionalAccess', _33 => _33.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):(_chunkBTH6J34Xcjs.e.call(void 0, ).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 (e5){return e}return e.trim()!==""&&!isNaN(Number(e))?Number(e):e==="true"?!0:e==="false"?!1: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&&(_chunkBTH6J34Xcjs.e.call(void 0, ).warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(_chunkBTH6J34Xcjs.e.call(void 0, ).warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};exports.a = D; exports.b = F; exports.c = S; exports.d = R; exports.e = E; exports.f = ge; exports.g = be; exports.h = w; exports.i = V; exports.j = B;
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk4UOOVSGLcjs = require('./chunk-4UOOVSGL.cjs');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 C(t,e){e||typeof window<"u"&&_chunk4UOOVSGLcjs.e.call(void 0, ).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 _chunk4UOOVSGLcjs.d&&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(_nullishCoalesce(p(o,"paramName"), () => ("<unnamed>")))}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;_chunk4UOOVSGLcjs.e.call(void 0, ).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&&C("solveGrasshopperDefinition",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning)));let{response:n}=await N(P(e,t),r);return n}async function X(t,e,r){return r.debug&&C("solveGrasshopperDefinitionWithCacheKey",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning))),N(P(e,t),r)}async function Z(t,e,r,n){n.debug&&C("solveByCacheKey",_nullishCoalesce(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 _chunk4UOOVSGLcjs.h.call(void 0, "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=_chunk4UOOVSGLcjs.p.call(void 0, t):/^https?:\/\//i.test(t)?r.pointer=t:_chunk4UOOVSGLcjs.n.call(void 0, t)?r.algo=t:r.algo=_chunk4UOOVSGLcjs.m.call(void 0, 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 S=class{constructor(e,r,n={},s){_chunk4UOOVSGLcjs.b.call(void 0, this,"executor");_chunk4UOOVSGLcjs.b.call(void 0, this,"baseConfig");_chunk4UOOVSGLcjs.b.call(void 0, this,"mode");_chunk4UOOVSGLcjs.b.call(void 0, this,"maxConcurrent");_chunk4UOOVSGLcjs.b.call(void 0, this,"timeoutMs");_chunk4UOOVSGLcjs.b.call(void 0, this,"retry");_chunk4UOOVSGLcjs.b.call(void 0, this,"cacheEnabled");_chunk4UOOVSGLcjs.b.call(void 0, this,"cacheMax");_chunk4UOOVSGLcjs.b.call(void 0, this,"cacheTtl");_chunk4UOOVSGLcjs.b.call(void 0, this,"cache",new Map);_chunk4UOOVSGLcjs.b.call(void 0, this,"cacheKeyExecutor");_chunk4UOOVSGLcjs.b.call(void 0, this,"reuseServerDefinitionCache");_chunk4UOOVSGLcjs.b.call(void 0, this,"serverCacheKeys",new Map);_chunk4UOOVSGLcjs.b.call(void 0, this,"onStart");_chunk4UOOVSGLcjs.b.call(void 0, this,"onSettle");_chunk4UOOVSGLcjs.b.call(void 0, this,"onSuperseded");_chunk4UOOVSGLcjs.b.call(void 0, this,"subscribers",new Set);_chunk4UOOVSGLcjs.b.call(void 0, this,"inFlight",new Set);_chunk4UOOVSGLcjs.b.call(void 0, this,"pendingForLatestWins",null);_chunk4UOOVSGLcjs.b.call(void 0, this,"fifoQueue",[]);_chunk4UOOVSGLcjs.b.call(void 0, this,"_lastResult",null);_chunk4UOOVSGLcjs.b.call(void 0, this,"_lastError",null);_chunk4UOOVSGLcjs.b.call(void 0, this,"_lastDurationMs",null);_chunk4UOOVSGLcjs.b.call(void 0, this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=_nullishCoalesce(n.mode, () => ("latest-wins")),this.maxConcurrent=Math.max(1,_nullishCoalesce(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=_nullishCoalesce(a.maxEntries, () => (50)),this.cacheTtl=_nullishCoalesce(a.ttlMs, () => (0)),this.reuseServerDefinitionCache=!!s&&(_nullishCoalesce(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){_chunk4UOOVSGLcjs.e.call(void 0, ).error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new (0, _chunk4UOOVSGLcjs.d)("SolveScheduler has been disposed and cannot be used",_chunk4UOOVSGLcjs.c.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:_optionalChain([n, 'optionalAccess', _2 => _2.signal])};if(_optionalChain([u, 'access', _3 => _3.externalSignal, 'optionalAccess', _4 => _4.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();_optionalChain([e, 'access', _5 => _5.externalSignal, 'optionalAccess', _6 => _6.addEventListener, 'call', _7 => _7("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{_optionalChain([e, 'access', _8 => _8.externalSignal, 'optionalAccess', _9 => _9.removeEventListener, 'call', _10 => _10("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=_nullishCoalesce(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 (0, _chunk4UOOVSGLcjs.d)("Superseded by newer solve",_chunk4UOOVSGLcjs.c.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new (0, _chunk4UOOVSGLcjs.d)("Request aborted by caller",_chunk4UOOVSGLcjs.c.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 _chunk4UOOVSGLcjs.d?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new (0, _chunk4UOOVSGLcjs.d)(e instanceof Error?e.message:String(e),_chunk4UOOVSGLcjs.c.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){_chunk4UOOVSGLcjs.e.call(void 0, ).error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){_chunk4UOOVSGLcjs.b.call(void 0, this,"config");_chunk4UOOVSGLcjs.b.call(void 0, this,"serverStats");_chunk4UOOVSGLcjs.b.call(void 0, this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new (0, _chunk4UOOVSGLcjs.j)(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(_nullishCoalesce(_optionalChain([e, 'access', _11 => _11.retry, 'optionalAccess', _12 => _12.attempts]), () => (2)))+1),s=_nullishCoalesce(_optionalChain([e, 'access', _13 => _13.retry, 'optionalAccess', _14 => _14.baseDelayMs]), () => (250)),o=_nullishCoalesce(_optionalChain([e, 'access', _15 => _15.retry, 'optionalAccess', _16 => _16.maxDelayMs]), () => (1e3));for(let a=0;a<n;a++){if(await r.serverStats.isServerOnline())return r;if(a<n-1){let i=Math.min(s*2**a,o);await new Promise(u=>setTimeout(u,i))}}throw await r.dispose(),new (0, _chunk4UOOVSGLcjs.d)("Rhino Compute server is not online",_chunk4UOOVSGLcjs.c.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),V(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),w(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!_optionalChain([e, 'optionalAccess', _17 => _17.trim, 'call', _18 => _18()]))throw new (0, _chunk4UOOVSGLcjs.d)("Definition URL/content is required",_chunk4UOOVSGLcjs.c.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new (0, _chunk4UOOVSGLcjs.d)("Definition content is empty",_chunk4UOOVSGLcjs.c.INVALID_INPUT);let s={...this.config,..._optionalChain([n, 'optionalAccess', _19 => _19.signal])!==void 0&&{signal:n.signal},..._optionalChain([n, 'optionalAccess', _20 => _20.timeoutMs])!==void 0&&{timeoutMs:n.timeoutMs},..._optionalChain([n, 'optionalAccess', _21 => _21.retry])!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(_optionalChain([o, 'optionalAccess', _22 => _22.errors])&&o.errors.length>0)throw new (0, _chunk4UOOVSGLcjs.d)(o.errors.join("; ")||"Computation failed",_chunk4UOOVSGLcjs.c.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&&_chunk4UOOVSGLcjs.e.call(void 0, ).error("Compute failed:",s),s instanceof _chunk4UOOVSGLcjs.d?s:new (0, _chunk4UOOVSGLcjs.d)(s instanceof Error?s.message:String(s),_chunk4UOOVSGLcjs.c.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 S(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new (0, _chunk4UOOVSGLcjs.d)("GrasshopperClient has been disposed and cannot be used",_chunk4UOOVSGLcjs.c.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_chunk4UOOVSGLcjs.i.call(void 0, e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:_nullishCoalesce(e.debug, () => (!1)),suppressBrowserWarning:_nullishCoalesce(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 we(t){return!t||typeof t!="object"?null:_nullishCoalesce(_nullishCoalesce(t.data, () => (t.value)), () => (null))}function oe(t,e,r){let n=Re(e);if(n)try{return n(r,t)}catch(s){_chunk4UOOVSGLcjs.e.call(void 0, ).warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=we(t);if(s)return r.CommonObject.decode(s)}catch(s){return _chunk4UOOVSGLcjs.e.call(void 0, ).warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ee="Rhino.Geometry.",ve=["WebDisplay"],Ae="FileData";function ae(t){return ve.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 (e2){return n}return n}catch (e3){return t}}function Oe(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ee)?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={},i=new Set;for(let u of t.values)M(u.InnerTree,m=>{if(ae(m.type)||o&&m.type!==I.STRING)return;let f=e?m.id:u.ParamName;if(!f)return;let y=ue(m.data,m.type,n,s);f in a?i.has(f)?a[f].push(y):(a[f]=[a[f],y],i.add(f)):a[f]=y});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 m=!1;return M(u.InnerTree,f=>{f.id===e.byId&&(m=!0)}),m}),!a)return;let i=[];if(M(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||ae(u.type)||o&&u.type!==I.STRING)return;let m=ue(u.data,u.type,n,s);i.push(m)}),i.length!==0)return i.length===1?i[0]:i}var E=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 Promise.resolve().then(() => _interopRequireWildcard(require("./visualization-WRUF5FKI.cjs"))))}catch(s){throw new (0, _chunk4UOOVSGLcjs.d)("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",_chunk4UOOVSGLcjs.c.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return le(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await _chunk4UOOVSGLcjs.r.call(void 0, 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 "${_nullishCoalesce(t.name, () => ("unknown"))}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return _chunk4UOOVSGLcjs.e.call(void 0, ).warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=_nullishCoalesce(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 m=Number(i);return Number.isNaN(m)?i:m}if(u==="System.Boolean")return i.toLowerCase()==="true";if(_optionalChain([u, 'optionalAccess', _23 => _23.startsWith, 'call', _24 => _24("Rhino.Geometry")]))try{return JSON.parse(i)}catch (e4){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 v(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 x(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.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(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:(_chunk4UOOVSGLcjs.e.call(void 0, ).warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return _chunk4UOOVSGLcjs.e.call(void 0, ).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 g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),T=Math.pow(10,-b),$=Number(T.toFixed(b));return Math.abs($-T)<e?$:T}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let y=Number(s[1]);if(y<0||n.toLowerCase().includes("e-")){let g=Math.abs(y),b=Math.pow(10,-g),T=Number(b.toFixed(g));return Math.abs(T-b)<e?T:b}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 m=Math.pow(10,-u),f=Number(m.toFixed(u));return Math.abs(f-m)<e?f:m}function We(t,e=1e-8){let r=t.paramType==="Integer";if(v(t.default))return{default:t.default,stepSize:r?1:.1};let n=x(t.default,Ge,!0);if(r)return Array.isArray(n)?n=n.map(f=>typeof f=="number"?Math.round(f):f):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),m=u.toLowerCase().match(/e(-?\d+)/);if(m?i=Math.abs(Number(m[1])):i=_nullishCoalesce(_optionalChain([u, 'access', _25 => _25.split, 'call', _26 => _26("."), 'access', _27 => _27[1], 'optionalAccess', _28 => _28.length]), () => (0)),i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let f=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(f)&&f>0&&(i=f)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(f=>typeof f=="number"?me(f,i,e):f):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=(_nullishCoalesce(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=x(t.default,Ve,!1)}catch(n){throw n instanceof Error?new (0, _chunk4UOOVSGLcjs.d)(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},Ue={types:["Text"],parse(t,e){let r=x(t.default,ke,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(_nullishCoalesce(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 _chunk4UOOVSGLcjs.d.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)||_chunk4UOOVSGLcjs.e.call(void 0, ).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=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"ValueList",values:_nullishCoalesce(t.values, () => ({})),default:r?[t.default]:t.default}}},he={types:["Geometry"],parse(t,e){let r=x(t.default,de(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},ze={types:["File"],parse(t,e){let r=x(t.default,de(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"File",default:r?[null]:null}}},$e={types:["Color"],parse(t,e){let r=x(t.default,Me,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(_nullishCoalesce(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 _nullishCoalesce(qe.get(_optionalChain([t, 'optionalAccess', _29 => _29.toLowerCase, 'call', _30 => _30()])), () => (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:_nullishCoalesce(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 _chunk4UOOVSGLcjs.d.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof _chunk4UOOVSGLcjs.d)return _chunk4UOOVSGLcjs.e.call(void 0, ).error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(_nullishCoalesce(a, () => (ye))).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new (0, _chunk4UOOVSGLcjs.d)(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:_nullishCoalesce(p(t,"nickname"), () => (null)),description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:_nullishCoalesce(p(t,"minimum"), () => (null)),maximum:_nullishCoalesce(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:_nullishCoalesce(p(t,"groupName"), () => (""))}}function Ce(t){return{name:p(t,"name"),nickname:_nullishCoalesce(p(t,"nickname"), () => (null)),paramType:p(t,"paramType"),id:p(t,"id")}}async function w(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 (0, _chunk4UOOVSGLcjs.d)("Definition must resolve to either a URL pointer or base64 algo",_chunk4UOOVSGLcjs.c.INVALID_INPUT,{context:{definition:t}});let s=await _chunk4UOOVSGLcjs.h.call(void 0, "io",n,e);if(!s||typeof s!="object")throw new (0, _chunk4UOOVSGLcjs.d)("Invalid IO response structure",_chunk4UOOVSGLcjs.c.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){C("fetchParsedDefinitionIO",_nullishCoalesce(e.suppressBrowserWarning, () => (e.suppressClientSideWarning)));let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await w(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){_chunk4UOOVSGLcjs.b.call(void 0, this,"innerTree");_chunk4UOOVSGLcjs.b.call(void 0, 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&&v(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 m=e,f=m.findIndex(y=>y.getParamName()===r);return f!==-1?m[f]=o:m.push(o),m}let a=e,i=o.toComputeFormat(),u=a.findIndex(m=>m.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return v(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(!_optionalChain([n, 'optionalAccess', _31 => _31.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=>_optionalChain([a, 'optionalAccess', _32 => _32.data])!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):_optionalChain([o, 'optionalAccess', _33 => _33.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):(_chunk4UOOVSGLcjs.e.call(void 0, ).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 (e5){return e}return e.trim()!==""&&!isNaN(Number(e))?Number(e):e==="true"?!0:e==="false"?!1: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&&(_chunk4UOOVSGLcjs.e.call(void 0, ).warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(_chunk4UOOVSGLcjs.e.call(void 0, ).warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};exports.a = D; exports.b = F; exports.c = S; exports.d = R; exports.e = E; exports.f = ge; exports.g = be; exports.h = w; exports.i = V; exports.j = B;
|
|
2
|
+
//# sourceMappingURL=chunk-XFKKZQUK.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-HG24GZ3A.cjs","../src/core/utils/read-field.ts","../src/core/utils/warnings.ts","../src/features/grasshopper/solve.ts"],"names":["readField","obj","name","record","lower","key","hasField","warnIfClientSide","functionName","suppress","getLogger","DEFINITION_LOAD_FAILED","isDefinitionLoadMiss","error","RhinoComputeError","warnOnEmptyInnerTrees","response","debug","values","empty","param","innerTree","scope"],"mappings":"AAAA,2/BAA8G,SCyB9FA,CAAAA,CAAuBC,CAAAA,CAAcC,CAAAA,CAA6B,CACjF,EAAA,CAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CAAU,MAAA,CAErC,IAAME,CAAAA,CAASF,CAAAA,CACf,EAAA,CAAIC,EAAAA,GAAQC,CAAAA,CAAQ,OAAOA,CAAAA,CAAOD,CAAI,CAAA,CAEtC,IAAME,CAAAA,CAAQF,CAAAA,CAAK,WAAA,CAAY,CAAA,CAC/B,GAAA,CAAA,IAAWG,EAAAA,GAAO,MAAA,CAAO,IAAA,CAAKF,CAAM,CAAA,CACnC,EAAA,CAAIE,CAAAA,CAAI,WAAA,CAAY,CAAA,GAAMD,CAAAA,CAAO,OAAOD,CAAAA,CAAOE,CAAG,CAGpD,CAOO,SAASC,CAAAA,CAASL,CAAAA,CAAcC,CAAAA,CAAuB,CAC7D,EAAA,CAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CAAU,MAAO,CAAA,CAAA,CAC5C,IAAME,CAAAA,CAASF,CAAAA,CACf,EAAA,CAAIC,EAAAA,GAAQC,CAAAA,CAAQ,MAAO,CAAA,CAAA,CAC3B,IAAMC,CAAAA,CAAQF,CAAAA,CAAK,WAAA,CAAY,CAAA,CAC/B,OAAO,MAAA,CAAO,IAAA,CAAKC,CAAM,CAAA,CAAE,IAAA,CAAME,CAAAA,EAAQA,CAAAA,CAAI,WAAA,CAAY,CAAA,GAAMD,CAAK,CACrE,CC/CO,SAASG,CAAAA,CAAiBC,CAAAA,CAAsBC,CAAAA,CAA0B,CAC5EA,CAAAA,EAIA,OAAO,MAAA,CAAW,GAAA,EACrBC,iCAAAA,CAAU,CAAE,IAAA,CACX,CAAA,SAAA,EAAYF,CAAY,CAAA,8GAAA,CACzB,CAEF,CCSA,IAAMG,EAAAA,CAAyB,uCAAA,CAG/B,SAASC,EAAAA,CAAqBC,CAAAA,CAAyB,CACtD,OAAOA,EAAAA,WAAiBC,mBAAAA,EAAqBD,CAAAA,CAAM,OAAA,CAAQ,QAAA,CAASF,EAAsB,CAC3F,CAeO,SAASI,CAAAA,CAAsBC,CAAAA,CAAsCC,CAAAA,CAAuB,CAClG,EAAA,CAAI,CAACA,CAAAA,CAAO,MAAA,CAEZ,IAAMC,CAAAA,CAASlB,CAAAA,CAAqBgB,CAAAA,CAAU,QAAQ,CAAA,CACtD,EAAA,CAAI,CAAC,KAAA,CAAM,OAAA,CAAQE,CAAM,CAAA,EAAKA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAEnD,IAAMC,CAAAA,CAAkB,CAAC,CAAA,CACzB,GAAA,CAAA,IAAWC,EAAAA,GAASF,CAAAA,CAAQ,CAC3B,IAAMG,CAAAA,CAAYrB,CAAAA,CAAmCoB,CAAAA,CAAO,WAAW,CAAA,CAAA,CAEnE,CAACC,CAAAA,EAAa,MAAA,CAAO,IAAA,CAAKA,CAAS,CAAA,CAAE,MAAA,GAAW,CAAA,CAAA,EACnDF,CAAAA,CAAM,IAAA,kBAAKnB,CAAAA,CAAkBoB,CAAAA,CAAO,WAAW,CAAA,SAAK,aAAW,CAEjE,CAEA,EAAA,CAAID,CAAAA,CAAM,MAAA,GAAW,CAAA,CAAG,MAAA,CAExB,IAAMG,CAAAA,CAAQH,CAAAA,CAAM,MAAA,GAAWD,CAAAA,CAAO,MAAA,CAAS,KAAA,CAAQ,CAAA,EAAA","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-HG24GZ3A.cjs","sourcesContent":[null,"/**\n * Case-insensitive single-key reader for wire payloads.\n *\n * The Rhino Compute family serializes the same logical field with different\n * casing depending on the server branch:\n *\n * - mcneel 8.x / 9.x: the IO schema is PascalCase (`ParamType`, `Default`,\n * `InnerTree`, …) because those C# classes carry no `[JsonProperty]`.\n * - VektorNode Compute8: the IO schema is camelCase (`paramType`, `default`,\n * …) because the fork added `[JsonProperty(\"camelCase\")]`, BUT the nested\n * `default` DataTree wrapper stays PascalCase (`ParamName` / `InnerTree`)\n * since `Resthopper.IO.DataTree` is an external type the fork can't attribute.\n *\n * So a single response can mix casings, and which casing a given field uses\n * depends on the server branch. Rather than deep-camelCasing the whole payload\n * (the old `camelcaseKeys` approach — which corrupted user-authored value-list\n * label keys and item `data` JSON), read the specific fields we care about\n * case-insensitively and leave everything else verbatim.\n *\n * Prefers an exact-case match when present, then falls back to the first\n * case-insensitive match. Returns `undefined` when no key matches.\n *\n * @param obj - The source object (any non-object input yields `undefined`).\n * @param name - The logical field name, in any casing.\n */\nexport function readField<T = unknown>(obj: unknown, name: string): T | undefined {\n\tif (!obj || typeof obj !== 'object') return undefined;\n\n\tconst record = obj as Record<string, unknown>;\n\tif (name in record) return record[name] as T;\n\n\tconst lower = name.toLowerCase();\n\tfor (const key of Object.keys(record)) {\n\t\tif (key.toLowerCase() === lower) return record[key] as T;\n\t}\n\treturn undefined;\n}\n\n/**\n * True when `obj` has a key matching `name` (case-insensitively). Distinguishes\n * \"field present but value is null/undefined\" from \"field absent\" — needed where\n * presence itself carries meaning (e.g. an `innerTree` that exists but is empty).\n */\nexport function hasField(obj: unknown, name: string): boolean {\n\tif (!obj || typeof obj !== 'object') return false;\n\tconst record = obj as Record<string, unknown>;\n\tif (name in record) return true;\n\tconst lower = name.toLowerCase();\n\treturn Object.keys(record).some((key) => key.toLowerCase() === lower);\n}\n","import { getLogger } from './logger';\n\nexport function warnIfClientSide(functionName: string, suppress?: boolean): void {\n\tif (suppress) {\n\t\treturn;\n\t}\n\n\tif (typeof window !== 'undefined') {\n\t\tgetLogger().warn(\n\t\t\t`Warning: ${functionName} is running on the client side. For better performance and security, consider running this on the server side.`\n\t\t);\n\t}\n}\n","import { fetchRhinoCompute, RhinoComputeError } from '@/core';\nimport { base64ByteArray, encodeStringToBase64, isBase64 } from '@/core/utils/encoding';\nimport { getLogger } from '@/core/utils/logger';\nimport { readField } from '@/core/utils/read-field';\nimport { warnIfClientSide } from '@/core/utils/warnings';\n\nimport {\n\tGrasshopperRequestSchema,\n\tGrasshopperComputeConfig,\n\tGrasshopperComputeResponse,\n\tDataTree\n} from './types';\n\n/**\n * The exact message the server throws when it can neither resolve a `pointer`\n * nor a base64 `algo` to a definition (ResthopperEndpoints.cs). This is the\n * signal that a cache-key pointer missed the server's definition cache (GC'd, or\n * a different child in the pool), so the caller should retry with the full\n * definition. Matched as a substring because the server wraps it with a category\n * prefix in its exception handler.\n */\nconst DEFINITION_LOAD_FAILED = 'Unable to load grasshopper definition';\n\n/** Does this error look like a server-side definition-load miss? */\nfunction isDefinitionLoadMiss(error: unknown): boolean {\n\treturn error instanceof RhinoComputeError && error.message.includes(DEFINITION_LOAD_FAILED);\n}\n\n/**\n * Debug aid: a solve can return successfully yet hand back outputs whose\n * `InnerTree` is empty (`{}`), meaning that parameter produced nothing — often a\n * sign the definition didn't actually compute (wrong/missing inputs, a guarded\n * branch). The names tell you exactly which output was empty so you can trace it\n * back to the responsible branch.\n *\n * Only logs when `debug` is set: an empty output can be legitimate, so this is a\n * diagnostic, never a hard failure. Reads `ParamName` / `InnerTree`\n * case-insensitively to stay robust across server-branch casing.\n *\n * @internal Exported for testing.\n */\nexport function warnOnEmptyInnerTrees(response: GrasshopperComputeResponse, debug?: boolean): void {\n\tif (!debug) return;\n\n\tconst values = readField<unknown[]>(response, 'values');\n\tif (!Array.isArray(values) || values.length === 0) return;\n\n\tconst empty: string[] = [];\n\tfor (const param of values) {\n\t\tconst innerTree = readField<Record<string, unknown>>(param, 'innerTree');\n\t\t// Treat a missing or empty innerTree as \"produced nothing\".\n\t\tif (!innerTree || Object.keys(innerTree).length === 0) {\n\t\t\tempty.push(readField<string>(param, 'paramName') ?? '<unnamed>');\n\t\t}\n\t}\n\n\tif (empty.length === 0) return;\n\n\tconst scope = empty.length === values.length ? 'all' : `${empty.length}/${values.length}`;\n\tgetLogger().warn(\n\t\t`Solve returned empty output(s) (${scope}): ${empty.join(', ')}. ` +\n\t\t\t`These parameters produced no data — check the definition's inputs and the branch feeding each.`\n\t);\n}\n\n/**\n * Result of a solve that also reports the definition's server-side cache key.\n *\n * `cacheKey` is the `md5_…` identifier the server assigned to the (base64)\n * definition — stable for identical content. A caller that holds it can solve\n * the same definition again by reference (`pointer: cacheKey`) instead of\n * re-uploading the full base64, which matters a lot for large (multi-MB)\n * definitions on a live UI. `null` when the server didn't return one (e.g. a\n * URL-pointer solve).\n */\nexport interface SolveWithCacheKey {\n\tresponse: GrasshopperComputeResponse;\n\tcacheKey: string | null;\n}\n\n/**\n * Runs a Rhino Compute job using the provided tree prototypes and Grasshopper definition.\n *\n * @public Use this for direct compute control. For high-level API, use `GrasshopperClient.solve()`.\n *\n * @param dataTree - An array of `DataTree` objects representing the input data for the compute job.\n * @param definition - The Grasshopper definition, which can be:\n * - A URL string (e.g., 'https://example.com/definition.gh')\n * - A base64-encoded string of the .gh file\n * - A plain string (will be base64-encoded)\n * - A Uint8Array of the .gh file (will be base64-encoded)\n * @param config - Compute configuration (server URL, API key, etc. along with optional timeout, units, etc.)\n * @returns An object containing the compute result and extracted file data.\n *\n * @example\n * // Using a URL\n * await solveGrasshopperDefinition(trees, 'https://example.com/definition.gh', config);\n *\n * // Using a base64 string\n * await solveGrasshopperDefinition(trees, 'UEsDBBQAAAAIAL...', config);\n *\n * // Using binary data\n * const fileData = new Uint8Array([...]);\n * await solveGrasshopperDefinition(trees, fileData, config);\n */\nexport async function solveGrasshopperDefinition(\n\tdataTree: DataTree[],\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<GrasshopperComputeResponse> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveGrasshopperDefinition',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\tconst { response } = await runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n\treturn response;\n}\n\n/**\n * Solve while reporting the server's definition cache key.\n *\n * Behaves like {@link solveGrasshopperDefinition} but returns the `cacheKey` the\n * server assigned, so a caller (e.g. the scheduler) can later solve the same\n * definition by reference instead of re-uploading it. The cache key is only\n * meaningful for base64/binary definitions; a URL-pointer solve returns the URL.\n *\n * @internal\n */\nexport async function solveGrasshopperDefinitionWithCacheKey(\n\tdataTree: DataTree[],\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveGrasshopperDefinitionWithCacheKey',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\treturn runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n}\n\n/**\n * Solve a definition by its server-side cache key (`pointer: cacheKey`),\n * skipping the (potentially multi-MB) base64 upload. If the key has been evicted\n * from the server's definition cache — `DEFINITION_LOAD_FAILED` — transparently\n * retry once with the full `definition` and report the fresh cache key so the\n * caller can update its mapping.\n *\n * @returns The solve result plus the (possibly refreshed) cache key, and whether\n * the fast path missed (so callers can record the new key / track hit rate).\n * @internal\n */\nexport async function solveByCacheKey(\n\tdataTree: DataTree[],\n\tcacheKey: string,\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey & { missed: boolean }> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveByCacheKey',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\tconst pointerArgs: GrasshopperRequestSchema = { algo: null, pointer: cacheKey, values: dataTree };\n\n\ttry {\n\t\tconst fast = await runSolve(pointerArgs, config);\n\t\treturn { ...fast, missed: false };\n\t} catch (error) {\n\t\tif (!isDefinitionLoadMiss(error)) throw error;\n\t\t// Cache miss — fall back to the full upload and capture the fresh key.\n\t\tconst full = await runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n\t\treturn { ...full, missed: true };\n\t}\n}\n\n/**\n * Shared solve body: apply optional settings, POST, and split the server's\n * `pointer` (its cache key) off the response. Stripping via shallow copy rather\n * than `delete` keeps any already-observed response object unmutated.\n */\nasync function runSolve(\n\targs: GrasshopperRequestSchema,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey> {\n\tapplyOptionalComputeSettings(args, config);\n\n\tconst result = await fetchRhinoCompute<GrasshopperComputeResponse>('grasshopper', args, config);\n\n\tif ('pointer' in result) {\n\t\tconst { pointer, ...rest } = result as GrasshopperComputeResponse & { pointer?: unknown };\n\t\tconst response = rest as GrasshopperComputeResponse;\n\t\twarnOnEmptyInnerTrees(response, config.debug);\n\t\treturn {\n\t\t\tresponse,\n\t\t\tcacheKey: typeof pointer === 'string' ? pointer : null\n\t\t};\n\t}\n\n\twarnOnEmptyInnerTrees(result, config.debug);\n\treturn { response: result, cacheKey: null };\n}\n\n// ============================================================================\n// Grasshopper Arguments\n// ============================================================================\n\n/**\n * Prepares Grasshopper arguments from a definition and data tree.\n * Automatically detects the definition format and converts it appropriately.\n *\n * @param definition - Can be a URL, base64 string, plain string, or Uint8Array\n * @param dataTree - Array of DataTree objects for compute inputs\n * @internal\n */\nexport function prepareGrasshopperArgs(\n\tdefinition: string | Uint8Array,\n\tdataTree: DataTree[]\n): GrasshopperRequestSchema {\n\tconst args: GrasshopperRequestSchema = {\n\t\talgo: null,\n\t\tpointer: null,\n\t\tvalues: dataTree\n\t};\n\n\tif (definition instanceof Uint8Array) {\n\t\t// Binary data → convert to base64\n\t\targs.algo = base64ByteArray(definition);\n\t} else if (/^https?:\\/\\//i.test(definition)) {\n\t\t// URL → use as pointer reference\n\t\targs.pointer = definition;\n\t} else if (isBase64(definition)) {\n\t\t// Already base64 → use as-is\n\t\targs.algo = definition;\n\t} else {\n\t\t// Plain string → encode to base64\n\t\targs.algo = encodeStringToBase64(definition);\n\t}\n\n\treturn args;\n}\n\n/**\n * @internal\n */\nexport function applyOptionalComputeSettings(\n\targlist: GrasshopperRequestSchema,\n\toptions: GrasshopperComputeConfig\n): void {\n\tif (options.cachesolve != null) arglist.cachesolve = options.cachesolve;\n\tif (options.modelunits != null) arglist.modelunits = options.modelunits;\n\tif (options.angletolerance != null) arglist.angletolerance = options.angletolerance;\n\tif (options.absolutetolerance != null) arglist.absolutetolerance = options.absolutetolerance;\n\tif (options.dataversion != null) arglist.dataversion = options.dataversion;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-XFKKZQUK.cjs","../src/core/utils/read-field.ts","../src/core/utils/warnings.ts","../src/features/grasshopper/solve.ts"],"names":["readField","obj","name","record","lower","key","hasField","warnIfClientSide","functionName","suppress","getLogger","DEFINITION_LOAD_FAILED","isDefinitionLoadMiss","error","RhinoComputeError","warnOnEmptyInnerTrees","response","debug","values","empty","param","innerTree","scope"],"mappings":"AAAA,2/BAA8G,SCyB9FA,CAAAA,CAAuBC,CAAAA,CAAcC,CAAAA,CAA6B,CACjF,EAAA,CAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CAAU,MAAA,CAErC,IAAME,CAAAA,CAASF,CAAAA,CACf,EAAA,CAAIC,EAAAA,GAAQC,CAAAA,CAAQ,OAAOA,CAAAA,CAAOD,CAAI,CAAA,CAEtC,IAAME,CAAAA,CAAQF,CAAAA,CAAK,WAAA,CAAY,CAAA,CAC/B,GAAA,CAAA,IAAWG,EAAAA,GAAO,MAAA,CAAO,IAAA,CAAKF,CAAM,CAAA,CACnC,EAAA,CAAIE,CAAAA,CAAI,WAAA,CAAY,CAAA,GAAMD,CAAAA,CAAO,OAAOD,CAAAA,CAAOE,CAAG,CAGpD,CAOO,SAASC,CAAAA,CAASL,CAAAA,CAAcC,CAAAA,CAAuB,CAC7D,EAAA,CAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CAAU,MAAO,CAAA,CAAA,CAC5C,IAAME,CAAAA,CAASF,CAAAA,CACf,EAAA,CAAIC,EAAAA,GAAQC,CAAAA,CAAQ,MAAO,CAAA,CAAA,CAC3B,IAAMC,CAAAA,CAAQF,CAAAA,CAAK,WAAA,CAAY,CAAA,CAC/B,OAAO,MAAA,CAAO,IAAA,CAAKC,CAAM,CAAA,CAAE,IAAA,CAAME,CAAAA,EAAQA,CAAAA,CAAI,WAAA,CAAY,CAAA,GAAMD,CAAK,CACrE,CC/CO,SAASG,CAAAA,CAAiBC,CAAAA,CAAsBC,CAAAA,CAA0B,CAC5EA,CAAAA,EAIA,OAAO,MAAA,CAAW,GAAA,EACrBC,iCAAAA,CAAU,CAAE,IAAA,CACX,CAAA,SAAA,EAAYF,CAAY,CAAA,8GAAA,CACzB,CAEF,CCSA,IAAMG,EAAAA,CAAyB,uCAAA,CAG/B,SAASC,EAAAA,CAAqBC,CAAAA,CAAyB,CACtD,OAAOA,EAAAA,WAAiBC,mBAAAA,EAAqBD,CAAAA,CAAM,OAAA,CAAQ,QAAA,CAASF,EAAsB,CAC3F,CAeO,SAASI,CAAAA,CAAsBC,CAAAA,CAAsCC,CAAAA,CAAuB,CAClG,EAAA,CAAI,CAACA,CAAAA,CAAO,MAAA,CAEZ,IAAMC,CAAAA,CAASlB,CAAAA,CAAqBgB,CAAAA,CAAU,QAAQ,CAAA,CACtD,EAAA,CAAI,CAAC,KAAA,CAAM,OAAA,CAAQE,CAAM,CAAA,EAAKA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAEnD,IAAMC,CAAAA,CAAkB,CAAC,CAAA,CACzB,GAAA,CAAA,IAAWC,EAAAA,GAASF,CAAAA,CAAQ,CAC3B,IAAMG,CAAAA,CAAYrB,CAAAA,CAAmCoB,CAAAA,CAAO,WAAW,CAAA,CAAA,CAEnE,CAACC,CAAAA,EAAa,MAAA,CAAO,IAAA,CAAKA,CAAS,CAAA,CAAE,MAAA,GAAW,CAAA,CAAA,EACnDF,CAAAA,CAAM,IAAA,kBAAKnB,CAAAA,CAAkBoB,CAAAA,CAAO,WAAW,CAAA,SAAK,aAAW,CAEjE,CAEA,EAAA,CAAID,CAAAA,CAAM,MAAA,GAAW,CAAA,CAAG,MAAA,CAExB,IAAMG,CAAAA,CAAQH,CAAAA,CAAM,MAAA,GAAWD,CAAAA,CAAO,MAAA,CAAS,KAAA,CAAQ,CAAA,EAAA","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-XFKKZQUK.cjs","sourcesContent":[null,"/**\n * Case-insensitive single-key reader for wire payloads.\n *\n * The Rhino Compute family serializes the same logical field with different\n * casing depending on the server branch:\n *\n * - mcneel 8.x / 9.x: the IO schema is PascalCase (`ParamType`, `Default`,\n * `InnerTree`, …) because those C# classes carry no `[JsonProperty]`.\n * - VektorNode Compute8: the IO schema is camelCase (`paramType`, `default`,\n * …) because the fork added `[JsonProperty(\"camelCase\")]`, BUT the nested\n * `default` DataTree wrapper stays PascalCase (`ParamName` / `InnerTree`)\n * since `Resthopper.IO.DataTree` is an external type the fork can't attribute.\n *\n * So a single response can mix casings, and which casing a given field uses\n * depends on the server branch. Rather than deep-camelCasing the whole payload\n * (the old `camelcaseKeys` approach — which corrupted user-authored value-list\n * label keys and item `data` JSON), read the specific fields we care about\n * case-insensitively and leave everything else verbatim.\n *\n * Prefers an exact-case match when present, then falls back to the first\n * case-insensitive match. Returns `undefined` when no key matches.\n *\n * @param obj - The source object (any non-object input yields `undefined`).\n * @param name - The logical field name, in any casing.\n */\nexport function readField<T = unknown>(obj: unknown, name: string): T | undefined {\n\tif (!obj || typeof obj !== 'object') return undefined;\n\n\tconst record = obj as Record<string, unknown>;\n\tif (name in record) return record[name] as T;\n\n\tconst lower = name.toLowerCase();\n\tfor (const key of Object.keys(record)) {\n\t\tif (key.toLowerCase() === lower) return record[key] as T;\n\t}\n\treturn undefined;\n}\n\n/**\n * True when `obj` has a key matching `name` (case-insensitively). Distinguishes\n * \"field present but value is null/undefined\" from \"field absent\" — needed where\n * presence itself carries meaning (e.g. an `innerTree` that exists but is empty).\n */\nexport function hasField(obj: unknown, name: string): boolean {\n\tif (!obj || typeof obj !== 'object') return false;\n\tconst record = obj as Record<string, unknown>;\n\tif (name in record) return true;\n\tconst lower = name.toLowerCase();\n\treturn Object.keys(record).some((key) => key.toLowerCase() === lower);\n}\n","import { getLogger } from './logger';\n\nexport function warnIfClientSide(functionName: string, suppress?: boolean): void {\n\tif (suppress) {\n\t\treturn;\n\t}\n\n\tif (typeof window !== 'undefined') {\n\t\tgetLogger().warn(\n\t\t\t`Warning: ${functionName} is running on the client side. For better performance and security, consider running this on the server side.`\n\t\t);\n\t}\n}\n","import { fetchRhinoCompute, RhinoComputeError } from '@/core';\nimport { base64ByteArray, encodeStringToBase64, isBase64 } from '@/core/utils/encoding';\nimport { getLogger } from '@/core/utils/logger';\nimport { readField } from '@/core/utils/read-field';\nimport { warnIfClientSide } from '@/core/utils/warnings';\n\nimport {\n\tGrasshopperRequestSchema,\n\tGrasshopperComputeConfig,\n\tGrasshopperComputeResponse,\n\tDataTree\n} from './types';\n\n/**\n * The exact message the server throws when it can neither resolve a `pointer`\n * nor a base64 `algo` to a definition (ResthopperEndpoints.cs). This is the\n * signal that a cache-key pointer missed the server's definition cache (GC'd, or\n * a different child in the pool), so the caller should retry with the full\n * definition. Matched as a substring because the server wraps it with a category\n * prefix in its exception handler.\n */\nconst DEFINITION_LOAD_FAILED = 'Unable to load grasshopper definition';\n\n/** Does this error look like a server-side definition-load miss? */\nfunction isDefinitionLoadMiss(error: unknown): boolean {\n\treturn error instanceof RhinoComputeError && error.message.includes(DEFINITION_LOAD_FAILED);\n}\n\n/**\n * Debug aid: a solve can return successfully yet hand back outputs whose\n * `InnerTree` is empty (`{}`), meaning that parameter produced nothing — often a\n * sign the definition didn't actually compute (wrong/missing inputs, a guarded\n * branch). The names tell you exactly which output was empty so you can trace it\n * back to the responsible branch.\n *\n * Only logs when `debug` is set: an empty output can be legitimate, so this is a\n * diagnostic, never a hard failure. Reads `ParamName` / `InnerTree`\n * case-insensitively to stay robust across server-branch casing.\n *\n * @internal Exported for testing.\n */\nexport function warnOnEmptyInnerTrees(response: GrasshopperComputeResponse, debug?: boolean): void {\n\tif (!debug) return;\n\n\tconst values = readField<unknown[]>(response, 'values');\n\tif (!Array.isArray(values) || values.length === 0) return;\n\n\tconst empty: string[] = [];\n\tfor (const param of values) {\n\t\tconst innerTree = readField<Record<string, unknown>>(param, 'innerTree');\n\t\t// Treat a missing or empty innerTree as \"produced nothing\".\n\t\tif (!innerTree || Object.keys(innerTree).length === 0) {\n\t\t\tempty.push(readField<string>(param, 'paramName') ?? '<unnamed>');\n\t\t}\n\t}\n\n\tif (empty.length === 0) return;\n\n\tconst scope = empty.length === values.length ? 'all' : `${empty.length}/${values.length}`;\n\tgetLogger().warn(\n\t\t`Solve returned empty output(s) (${scope}): ${empty.join(', ')}. ` +\n\t\t\t`These parameters produced no data — check the definition's inputs and the branch feeding each.`\n\t);\n}\n\n/**\n * Result of a solve that also reports the definition's server-side cache key.\n *\n * `cacheKey` is the `md5_…` identifier the server assigned to the (base64)\n * definition — stable for identical content. A caller that holds it can solve\n * the same definition again by reference (`pointer: cacheKey`) instead of\n * re-uploading the full base64, which matters a lot for large (multi-MB)\n * definitions on a live UI. `null` when the server didn't return one (e.g. a\n * URL-pointer solve).\n */\nexport interface SolveWithCacheKey {\n\tresponse: GrasshopperComputeResponse;\n\tcacheKey: string | null;\n}\n\n/**\n * Runs a Rhino Compute job using the provided tree prototypes and Grasshopper definition.\n *\n * @public Use this for direct compute control. For high-level API, use `GrasshopperClient.solve()`.\n *\n * @param dataTree - An array of `DataTree` objects representing the input data for the compute job.\n * @param definition - The Grasshopper definition, which can be:\n * - A URL string (e.g., 'https://example.com/definition.gh')\n * - A base64-encoded string of the .gh file\n * - A plain string (will be base64-encoded)\n * - A Uint8Array of the .gh file (will be base64-encoded)\n * @param config - Compute configuration (server URL, API key, etc. along with optional timeout, units, etc.)\n * @returns An object containing the compute result and extracted file data.\n *\n * @example\n * // Using a URL\n * await solveGrasshopperDefinition(trees, 'https://example.com/definition.gh', config);\n *\n * // Using a base64 string\n * await solveGrasshopperDefinition(trees, 'UEsDBBQAAAAIAL...', config);\n *\n * // Using binary data\n * const fileData = new Uint8Array([...]);\n * await solveGrasshopperDefinition(trees, fileData, config);\n */\nexport async function solveGrasshopperDefinition(\n\tdataTree: DataTree[],\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<GrasshopperComputeResponse> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveGrasshopperDefinition',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\tconst { response } = await runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n\treturn response;\n}\n\n/**\n * Solve while reporting the server's definition cache key.\n *\n * Behaves like {@link solveGrasshopperDefinition} but returns the `cacheKey` the\n * server assigned, so a caller (e.g. the scheduler) can later solve the same\n * definition by reference instead of re-uploading it. The cache key is only\n * meaningful for base64/binary definitions; a URL-pointer solve returns the URL.\n *\n * @internal\n */\nexport async function solveGrasshopperDefinitionWithCacheKey(\n\tdataTree: DataTree[],\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveGrasshopperDefinitionWithCacheKey',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\treturn runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n}\n\n/**\n * Solve a definition by its server-side cache key (`pointer: cacheKey`),\n * skipping the (potentially multi-MB) base64 upload. If the key has been evicted\n * from the server's definition cache — `DEFINITION_LOAD_FAILED` — transparently\n * retry once with the full `definition` and report the fresh cache key so the\n * caller can update its mapping.\n *\n * @returns The solve result plus the (possibly refreshed) cache key, and whether\n * the fast path missed (so callers can record the new key / track hit rate).\n * @internal\n */\nexport async function solveByCacheKey(\n\tdataTree: DataTree[],\n\tcacheKey: string,\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey & { missed: boolean }> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveByCacheKey',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\tconst pointerArgs: GrasshopperRequestSchema = { algo: null, pointer: cacheKey, values: dataTree };\n\n\ttry {\n\t\tconst fast = await runSolve(pointerArgs, config);\n\t\treturn { ...fast, missed: false };\n\t} catch (error) {\n\t\tif (!isDefinitionLoadMiss(error)) throw error;\n\t\t// Cache miss — fall back to the full upload and capture the fresh key.\n\t\tconst full = await runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n\t\treturn { ...full, missed: true };\n\t}\n}\n\n/**\n * Shared solve body: apply optional settings, POST, and split the server's\n * `pointer` (its cache key) off the response. Stripping via shallow copy rather\n * than `delete` keeps any already-observed response object unmutated.\n */\nasync function runSolve(\n\targs: GrasshopperRequestSchema,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey> {\n\tapplyOptionalComputeSettings(args, config);\n\n\tconst result = await fetchRhinoCompute<GrasshopperComputeResponse>('grasshopper', args, config);\n\n\tif ('pointer' in result) {\n\t\tconst { pointer, ...rest } = result as GrasshopperComputeResponse & { pointer?: unknown };\n\t\tconst response = rest as GrasshopperComputeResponse;\n\t\twarnOnEmptyInnerTrees(response, config.debug);\n\t\treturn {\n\t\t\tresponse,\n\t\t\tcacheKey: typeof pointer === 'string' ? pointer : null\n\t\t};\n\t}\n\n\twarnOnEmptyInnerTrees(result, config.debug);\n\treturn { response: result, cacheKey: null };\n}\n\n// ============================================================================\n// Grasshopper Arguments\n// ============================================================================\n\n/**\n * Prepares Grasshopper arguments from a definition and data tree.\n * Automatically detects the definition format and converts it appropriately.\n *\n * @param definition - Can be a URL, base64 string, plain string, or Uint8Array\n * @param dataTree - Array of DataTree objects for compute inputs\n * @internal\n */\nexport function prepareGrasshopperArgs(\n\tdefinition: string | Uint8Array,\n\tdataTree: DataTree[]\n): GrasshopperRequestSchema {\n\tconst args: GrasshopperRequestSchema = {\n\t\talgo: null,\n\t\tpointer: null,\n\t\tvalues: dataTree\n\t};\n\n\tif (definition instanceof Uint8Array) {\n\t\t// Binary data → convert to base64\n\t\targs.algo = base64ByteArray(definition);\n\t} else if (/^https?:\\/\\//i.test(definition)) {\n\t\t// URL → use as pointer reference\n\t\targs.pointer = definition;\n\t} else if (isBase64(definition)) {\n\t\t// Already base64 → use as-is\n\t\targs.algo = definition;\n\t} else {\n\t\t// Plain string → encode to base64\n\t\targs.algo = encodeStringToBase64(definition);\n\t}\n\n\treturn args;\n}\n\n/**\n * @internal\n */\nexport function applyOptionalComputeSettings(\n\targlist: GrasshopperRequestSchema,\n\toptions: GrasshopperComputeConfig\n): void {\n\tif (options.cachesolve != null) arglist.cachesolve = options.cachesolve;\n\tif (options.modelunits != null) arglist.modelunits = options.modelunits;\n\tif (options.angletolerance != null) arglist.angletolerance = options.angletolerance;\n\tif (options.absolutetolerance != null) arglist.absolutetolerance = options.absolutetolerance;\n\tif (options.dataversion != null) arglist.dataversion = options.dataversion;\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as Le,c as ee,d as te,e as M,o as ce}from"./chunk-AXAMGKTJ.js";import*as V from"three";var _={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 An(e,r,t,n,o){if(Oe(e),r.length===0)return;r.forEach(u=>{e.add(u)});let a=Y(r),i=a.getCenter(new V.Vector3),s=a.getSize(new V.Vector3),l=Math.max(s.x,s.y,s.z);if(l/Math.min(s.x||1,s.y||1,s.z||1)>_.SCALE_RATIO_THRESHOLD||l>_.HUGE_THRESHOLD?(t.near=l*_.NEAR_PLANE_FACTOR.TINY,t.far=l*_.FAR_PLANE_FACTOR.HUGE):l>_.LARGE_THRESHOLD?(t.near=l*_.NEAR_PLANE_FACTOR.SMALL,t.far=l*_.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,l*_.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,l*_.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let u=l*_.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+u*.8,i.y+u,i.z+u*1.2),n.target.copy(i),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function ue(e){if(!e||typeof e!="string")return M().warn(`Invalid color input: ${e}, using white`),new V.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new V.Color(t)}catch{return M().warn(`Invalid hex color: ${e}, using white`),new V.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 V.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new V.Color(r.toLowerCase())}catch{return M().warn(`Invalid color string: ${e}, using white`),new V.Color(16777215)}}function de(e,r,t="z"){e.forEach(n=>{n.position[t]-=r})}function Y(e){let r=new V.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let n=new V.Box3().setFromObject(t);r.union(n)}),r}var Pe=new Set(["floor","grid","label-layer"]);function Oe(e){[...e.children].forEach(t=>{Pe.has(t.userData.id)||(t.traverse(n=>{let o=n;if(!o.geometry&&!o.material)return;o.geometry?.dispose();let a=o.material;if(!a)return;(Array.isArray(a)?a:[a]).forEach(s=>{for(let l of Object.values(s))l instanceof V.Texture&&l.dispose();s.dispose()})}),t.removeFromParent())})}import*as z from"three";function Ie(e){let r=e.clone().normalize(),t=new z.Vector3(0,0,1),n=new z.Vector3(0,1,0),o=Math.abs(r.dot(t))>.9?n:t,a=new z.Vector3().crossVectors(r,o).normalize(),i=new z.Vector3().crossVectors(a,r).normalize();return{top:r.clone(),bottom:r.clone().negate(),front:i.clone(),back:i.clone().negate(),right:a.clone(),left:a.clone().negate(),iso:i.clone().multiplyScalar(1.2).add(a.clone()).add(r.clone()).normalize()}}function me(e){let{scene:r,perspective:t,controls:n,onActiveCameraChange:o}=e,a=(e.up??t.up).clone().normalize(),i=Ie(a),s=new z.OrthographicCamera(-1,1,1,-1,t.near,t.far);s.up.copy(a);let l="perspective",c=t.aspect,u=()=>l==="perspective"?t:s,d=()=>{let h=t.position.distanceTo(n.target)*Math.tan(t.fov*Math.PI/360),T=h*c;s.left=-T,s.right=T,s.top=h,s.bottom=-h,s.near=t.near,s.far=t.far,s.updateProjectionMatrix()},m=b=>{b!==l&&(b==="orthographic"?(s.position.copy(t.position),s.up.copy(t.up),s.lookAt(n.target),d()):t.position.copy(s.position),l=b,n.object=u(),n.update(),o(u()))},E=(b,h=!0)=>{let T=ze(r),v=T.isEmpty()?n.target.clone():T.getCenter(new z.Vector3),P=T.isEmpty()?new z.Vector3(1,1,1):T.getSize(new z.Vector3),y=Math.max(P.x,P.y,P.z)||1,w=t.fov*(Math.PI/180),C=y/(2*Math.tan(w/2))*1.5,O=Fe(b,a),g=v.clone().add(O.clone().multiplyScalar(C)),R=u();h?ke(R,n,g,v,()=>{l==="orthographic"&&d()}):(R.position.copy(g),n.target.copy(v),l==="orthographic"&&d(),n.update())};return{getActiveCamera:u,getProjection:()=>l,setProjection:m,toggleProjection:()=>(m(l==="perspective"?"orthographic":"perspective"),l),setView:(b,h=!0)=>{E(i[b],h)},setViewDirection:E,setRotateEnabled:b=>{n.enableRotate=b},isRotateEnabled:()=>n.enableRotate,updateAspect:(b,h)=>{c=h===0?c:b/h,l==="orthographic"&&d()}}}var Ve=new Set(["grid","floor","label-layer","measure"]);function Be(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 ze(e){let r=[];return e.traverse(t=>{let n=t;t.visible&&!Be(t)&&n.geometry&&r.push(t)}),Y(r)}function Fe(e,r){let t=r.clone().normalize(),n=e.clone().normalize();if(Math.abs(n.dot(t))<.9999)return e;let o=Math.abs(t.dot(new z.Vector3(0,0,1)))>.9?new z.Vector3(0,1,0):new z.Vector3(0,0,1),a=new z.Vector3().crossVectors(t,o).normalize(),i=.5*Math.PI/180;return n.multiplyScalar(Math.cos(i)).add(a.multiplyScalar(Math.sin(i))).normalize()}var je=e=>1-Math.pow(1-e,3);function ke(e,r,t,n,o,a=250){let i=e.position.clone(),s=r.target.clone(),l=performance.now(),c=()=>{let u=je(Math.min((performance.now()-l)/a,1));e.position.lerpVectors(i,t,u),r.target.lerpVectors(s,n,u),o(),r.update(),u<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}import*as I from"three";var _e=`
|
|
2
2
|
varying vec3 vWorldPos;
|
|
3
3
|
void main() {
|
|
4
4
|
vec4 world = modelMatrix * vec4(position, 1.0);
|
|
5
5
|
vWorldPos = world.xyz;
|
|
6
6
|
gl_Position = projectionMatrix * viewMatrix * world;
|
|
7
7
|
}
|
|
8
|
-
`,
|
|
8
|
+
`,Ue=`
|
|
9
9
|
precision highp float;
|
|
10
10
|
varying vec3 vWorldPos;
|
|
11
11
|
|
|
@@ -50,6 +50,6 @@ import{a as De,c as ee,d as te,e as v,o as ce}from"./chunk-H2FJSNMM.js";import*a
|
|
|
50
50
|
if (alpha < 0.001) discard;
|
|
51
51
|
gl_FragColor = vec4(color, alpha);
|
|
52
52
|
}
|
|
53
|
-
`;function Ee(e={}){let{cellSize:r=1,majorEvery:t=10,cellColor:n=8947848,majorColor:o=4473924,fadeDistance:a=100,plane:i="y"}=e,s=i==="y"?new I.Vector2(0,2):i==="z"?new I.Vector2(0,1):new I.Vector2(1,2),l=a*2.5,c=new I.PlaneGeometry(l,l);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let
|
|
54
|
-
\u0394x ${q(r.x)} \u0394y ${q(r.y)} \u0394z ${q(r.z)}`;function lt(e){let r=e.object;return r instanceof A.Mesh?e.face?[e.face.a,e.face.b,e.face.c]:null:r instanceof A.Points?e.index!=null?[e.index]:null:r instanceof A.Line&&e.index!=null?[e.index,e.index+1]:null}function ct(e,r,t,n){let o=e.point.clone(),a=e.object,i=lt(e);if(!i||!a.geometry)return o;let s=a.geometry.attributes.position;if(!s)return o;let l=m=>{let E=m.clone().project(r);return new A.Vector2((E.x+1)/2*t.width,(1-E.y)/2*t.height)},c=l(o),d=o,u=n;for(let m of i){if(m>=s.count)continue;let f=new A.Vector3().fromBufferAttribute(s,m).applyMatrix4(a.matrixWorld),x=l(f).distanceTo(c);x<u&&(u=x,d=f)}return d}function Te(e){let{canvas:r,scene:t,getActiveCamera:n,labelLayer:o,options:a={}}=e,i=a.snapPixels??at,s=new A.Color(a.color??it),l=a.format??st,c=new A.Raycaster,d=new A.Vector2,u=!1,m=[],E=[],f=null,x=null,S=new A.PointsMaterial({color:s,size:8,sizeAttenuation:!1,depthTest:!1}),b=new A.PointsMaterial({color:s,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),g=null,R=h=>{if(!h){g&&(g.visible=!1);return}if(!g){let T=new A.BufferGeometry;T.setAttribute("position",new A.Float32BufferAttribute([0,0,0],3)),g=new A.Points(T,b),g.renderOrder=1e3,g.userData.id="measure",g.raycast=()=>{},t.add(g)}g.position.copy(h),g.visible=!0},H=h=>{let T=new A.BufferGeometry;T.setAttribute("position",new A.Float32BufferAttribute([h.x,h.y,h.z],3));let M=new A.Points(T,S);return M.renderOrder=999,M.userData.id="measure",M.raycast=()=>{},t.add(M),M},P=()=>{m.length=0,E.forEach(h=>{h.geometry.dispose(),h.removeFromParent()}),E.length=0,f&&(f.geometry.dispose(),f.material.dispose(),f.removeFromParent(),f=null),x?.remove(),x=null},y=()=>{if(m.length!==2)return;let[h,T]=m,M=new rt;M.setPositions([h.x,h.y,h.z,T.x,T.y,T.z]);let k=new ot({color:s});k.linewidth=2,k.depthTest=!1,f=new nt(M,k),f.renderOrder=998,f.userData.id="measure",f.raycast=()=>{},t.add(f);let U=h.clone().add(T).multiplyScalar(.5),W=new A.Vector3(Math.abs(T.x-h.x),Math.abs(T.y-h.y),Math.abs(T.z-h.z));x=o.addLabel(l(h.distanceTo(T),W),U,a.labelClassName)},w=h=>{let T=r.getBoundingClientRect();d.x=(h.clientX-T.left)/T.width*2-1,d.y=-((h.clientY-T.top)/T.height)*2+1;let M=n();c.setFromCamera(d,M);let k=M.position.length();c.params.Line={threshold:k*Re},c.params.Points={threshold:k*Re};let U=c.intersectObjects(t.children,!0).filter(W=>W.object.userData.id!=="measure"&&W.object.userData.id!=="grid");return U.length===0?null:ct(U[0],M,{width:T.width,height:T.height},i)};return{setEnabled:h=>{u=h,h||(P(),R(null))},isEnabled:()=>u,handleClick:h=>{if(!u)return!1;m.length===2&&P();let T=w(h);return T===null||(m.push(T),E.push(H(T)),m.length===2&&y()),!0},handleMove:h=>{u&&R(w(h))},clear:P,dispose:()=>{P(),g&&(g.geometry.dispose(),g.removeFromParent(),g=null),S.dispose(),b.dispose()}}}import*as p from"three";import{OrbitControls as dt}from"three/addons/controls/OrbitControls.js";import{HDRLoader as ut}from"three/addons/loaders/HDRLoader.js";var Z=new p.Vector3(0,0,1);function mt(e){let r=Math.abs(e.x),t=Math.abs(e.y),n=Math.abs(e.z);return n>=r&&n>=t?"z":t>=r&&t>=n?"y":"x"}var nr=function(e,r){let t=Et(r||{}),n=t.environment?.sceneUp||Z,o=gt(t),a=Ht(t,e);a.up.copy(n);let i=vt(e,t),s=Ct(a,e,t),l=me({scene:o,perspective:a,controls:s,onActiveCameraChange:()=>{},up:n}),c=()=>l.getActiveCamera();Rt(o,t);let d=Tt(o,t),u=()=>{d&&ht(d,ne(o))};t.floor?.enabled&&wt(o,t);let m=t.grid.enabled?Ee({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;m&&o.add(m.object);let E=t.gizmo.enabled?pe({camera:a,domElement:e,controller:l}):null,f=e.parentElement??e,x=t.measure.enabled?ye(f,o):null,S=t.measure.enabled&&x?Te({canvas:e,scene:o,getActiveCamera:c,labelLayer:x,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,format:t.measure.format}}):null,b=t.events.enableEventHandlers!==!1?Mt(e,o,c,a,s,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},g=5,R=0,H=0,P=D=>{R=D.clientX,H=D.clientY},y=D=>Math.hypot(D.clientX-R,D.clientY-H)>g,w=D=>{if(!y(D)){if(S?.handleClick(D)){D.stopImmediatePropagation();return}E?.handleClick(D)&&D.stopImmediatePropagation()}};(E||S)&&(e.addEventListener("mousedown",P,{capture:!0}),e.addEventListener("click",w,{capture:!0}));let C=D=>S?.handleMove(D);S&&e.addEventListener("mousemove",C,{passive:!0});let O=D=>{he(D,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},h=e.parentElement,T=()=>h?{width:h.clientWidth,height:h.clientHeight}:{width:window.innerWidth,height:window.innerHeight},M=null,k=()=>{let{width:D,height:G}=T(),Q=Math.min(window.devicePixelRatio,2),le=ge(i,o,c(),Math.max(1,D),Math.max(1,G),{toneMapping:t.render.toneMapping??p.NeutralToneMapping,toneMappingExposure:t.render.toneMappingExposure??1,aoIntensity:t.render.aoIntensity});return le.setSize(Math.max(1,D),Math.max(1,G),Q),le},U=D=>{D&&!M?M=k():!D&&M&&(M.dispose(),M=null)};t.render.ambientOcclusion&&(M=k());let{animate:W,dispose:K}=yt(i,o,a,c,l,s,T,t.events.onFrame,m,E,()=>M,x);return W(),o.up.set(n.x,n.y,n.z),u(),{scene:o,camera:a,controls:s,renderer:i,cameraController:l,grid:m,gizmo:E,measureTool:S,applyEdges:O,setAmbientOcclusion:U,updateShadowBounds:u,dispose:()=>{K(),b.dispose(),(E||S)&&(e.removeEventListener("mousedown",P,{capture:!0}),e.removeEventListener("click",w,{capture:!0})),S&&e.removeEventListener("mousemove",C),S?.dispose(),x?.dispose(),E?.dispose(),m?.dispose(),M?.dispose(),s.dispose(),i.dispose(),o.traverse(D=>{let G=D;!G.geometry&&!G.material||(G.geometry?.dispose(),Array.isArray(G.material)?G.material.forEach(Q=>Q.dispose()):G.material?.dispose())})},fitToView:b.fitToView,clearSelection:b.clearSelection}};function Et(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 p.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 p.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity||1,sunlightPosition:e.lighting?.sunlightPosition||new p.Vector3(n.lightDistance,n.lightDistance,n.lightHeight),ambientLightColor:e.lighting?.ambientLightColor||new p.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity||1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new p.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||Z,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||n.floorSize,color:e.floor?.color||new p.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||p.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??mt(e.environment?.sceneUp??Z)},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 pt=new Set(["grid","floor","label-layer","measure"]);function ft(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&pt.has(r.userData.id))return!0;r=r.parent}return!1}function ne(e){let r=new p.Box3;return e.traverse(t=>{let n=t;t.visible&&!ft(t)&&n.geometry&&r.expandByObject(t)}),r}function ht(e,r){if(r.isEmpty())return;let t=r.getCenter(new p.Vector3),n=r.getSize(new p.Vector3).length()*.5*1.2,o=e.shadow.camera;o.left=-n,o.right=n,o.top=n,o.bottom=-n,e.target.position.copy(t),e.target.updateMatrixWorld();let a=e.position.distanceTo(t);o.near=Math.max(n*.01,a-n),o.far=a+n,o.updateProjectionMatrix()}function gt(e){let r=new p.Scene,t=typeof e.environment.backgroundColor=="string"?new p.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function bt(e,r,t,n,o=200){let a=e.position.clone(),i=r.target.clone(),s=performance.now(),l=d=>1-Math.pow(1-d,3),c=()=>{let d=performance.now()-s,u=l(Math.min(d/o,1));e.position.lerpVectors(a,t,u),r.target.lerpVectors(i,n,u),r.update(),u<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}function yt(e,r,t,n,o,a,i,s,l,c,d,u){let m=null,E=performance.now(),f=()=>{let{width:b,height:g}=i();if(b===0||g===0)return;let R=Math.min(window.devicePixelRatio,2),H=Math.round(b*R),P=Math.round(g*R);(e.domElement.width!==H||e.domElement.height!==P)&&(e.setPixelRatio(R),e.setSize(b,g,!1),t.aspect=b/g,t.updateProjectionMatrix(),o.updateAspect(b,g),d?.()?.setSize(b,g,R),u?.setSize(b,g))},x=function(){m=requestAnimationFrame(x);let b=performance.now(),g=(b-E)/1e3;E=b,f(),(a.enableDamping||a.autoRotate)&&a.update(),l&&l.update(n().position),c&&c.update(g),s?.(g);let R=n(),H=d?.();H?(H.setCamera(R),H.render(g)):e.render(r,R),u&&u.render(r,R),c&&c.render(e)};return{animate:x,dispose:()=>{m!==null&&(cancelAnimationFrame(m),m=null)}}}function Rt(e,r){r.environment.enableEnvironmentLighting?new ut().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){if(!t?.image){v().warn("HDR loaded without image data; skipping environment map."),r.events.onReady?.();return}t.mapping=p.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t),r.events.onReady?.()},void 0,function(t){v().warn("HDR texture could not be loaded, falling back to basic lighting:",t),r.events.onReady?.()}):r.events.onReady?.()}function Tt(e,r){let t=new p.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),!r.lighting.enableSunlight)return null;let n=new p.DirectionalLight(r.lighting.sunlightColor??16777215,r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;return o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows?(n.castShadow=!0,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,n.shadow.radius=4,e.add(n),e.add(n.target),n):(e.add(n),null)}function wt(e,r){let t=r.floor.size,n=new p.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new p.Color(r.floor.color):r.floor.color,a=new p.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:p.DoubleSide}),i=new p.Mesh(n,a);i.userData.id="floor",i.name="floor";let s=(r.environment?.sceneUp||Z).clone().normalize();i.quaternion.setFromUnitVectors(new p.Vector3(0,0,1),s),i.position.set(0,0,0),r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function Ht(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,a=new p.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function vt(e,r){let t=new p.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,a=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,a,!1),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=p.VSMShadowMap),t.toneMapping=r.render.toneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=p.SRGBColorSpace,t.sortObjects=!0,t}function Mt(e,r,t,n,o,a){let i=new Set,s=new Map,l=new p.Raycaster,c=new p.Vector2,d=new p.Vector2,u=y=>{let w=y;for(;w;){if(!w.visible)return!1;w=w.parent}return!0},m=()=>{let y=ne(r);if(y.isEmpty()){v().warn("No objects to fit to view");return}let w=y.getCenter(new p.Vector3),C=y.getSize(new p.Vector3),O=Math.max(C.x,C.y,C.z),h=n.fov*(Math.PI/180),T=O/(2*Math.tan(h/2));T*=1.5;let M=n.position.clone().sub(o.target);M.lengthSq()<1e-12&&M.set(.8,1,1.2),M.normalize(),n.position.copy(w.clone().add(M.multiplyScalar(T))),o.target.copy(w),o.update()},E=typeof a.events.selectionColor=="string"?new p.Color(a.events.selectionColor):a.events.selectionColor instanceof p.Color?a.events.selectionColor:new p.Color("#ff0000"),f=()=>{i.forEach(y=>{let w=y;if(s.has(y)){let C=s.get(y),O=w.material;O instanceof p.Material?O.dispose():Array.isArray(O)&&O.forEach(h=>h.dispose()),w.material=C,s.delete(y)}}),i.clear()},x=y=>{let w=y;if(!(w.material instanceof p.Material))return!1;s.set(y,w.material);let C=w.material.clone();return y instanceof p.Mesh&&"emissive"in C?C.emissive=E.clone():"color"in C&&(C.color=E.clone()),w.material=C,!0},S=()=>{let y=ne(r),w=y.isEmpty()?1:y.getSize(new p.Vector3).length();l.params.Points.threshold=w*.01},b=y=>{d.set(y.clientX,y.clientY)},g=y=>{let w=new p.Vector2(y.clientX,y.clientY);if(d.distanceTo(w)>5)return;let C=e.getBoundingClientRect();c.x=(y.clientX-C.left)/C.width*2-1,c.y=-((y.clientY-C.top)/C.height)*2+1,S(),l.setFromCamera(c,t());let O=l.intersectObjects(r.children,!0).filter(h=>u(h.object));if(O.length>0){let h=O[0].object;i.has(h)||(f(),i.add(h),x(h),a.events?.onObjectSelected?.(h),h instanceof p.Mesh&&Object.keys(h.userData).length>0&&a.events?.onMeshMetadataClicked?.(h.userData))}else f(),a.events?.onBackgroundClicked?.({x:c.x,y:c.y})},R=y=>{let w=e.getBoundingClientRect();c.x=(y.clientX-w.left)/w.width*2-1,c.y=-((y.clientY-w.top)/w.height)*2+1,S(),l.setFromCamera(c,t());let C=l.intersectObjects(r.children,!0).filter(D=>u(D.object));if(C.length===0)return;let O=C[0].object;if(a.events?.onMeshDoubleClicked?.(O),!a.events?.enableDoubleClickZoom)return;let h=new p.Box3().setFromObject(O);if(h.isEmpty())return;let T=h.getCenter(new p.Vector3),M=h.getSize(new p.Vector3),k=Math.max(M.x,M.y,M.z),U=n.fov*(Math.PI/180),W=k/(2*Math.tan(U/2))*1.5,K=n.position.clone().sub(o.target).normalize(),se=T.clone().add(K.multiplyScalar(W));bt(n,o,se,T)},H=y=>{if(a.events?.enableKeyboardControls)switch(y.key.toLowerCase()){case"f":y.preventDefault(),m();break;case"escape":y.preventDefault(),f();break;case" ":y.preventDefault(),m();break}};return a.events?.enableClickToFocus&&(e.addEventListener("mousedown",b),e.addEventListener("click",g),e.addEventListener("dblclick",R)),a.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",H)),{dispose:()=>{e.removeEventListener("mousedown",b),e.removeEventListener("click",g),e.removeEventListener("dblclick",R),e.removeEventListener("keydown",H),f()},fitToView:m,clearSelection:f}}function Ct(e,r,t){let n=new dt(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.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 It={};De(It,{CONCRETE_MATERIAL:()=>At,EMISSIVE_MATERIAL:()=>xt,GLASS_MATERIAL:()=>Lt,METAL_MATERIAL:()=>St,PLASTIC_MATERIAL:()=>Dt,RUBBER_MATERIAL:()=>Pt,WOOD_MATERIAL:()=>Ot});import*as L from"three";var xt=new L.MeshPhysicalMaterial({color:0,emissive:new L.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),St=new L.MeshPhysicalMaterial({color:new L.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:L.FrontSide,dithering:!0}),At=new L.MeshPhysicalMaterial({color:new L.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:L.FrontSide,dithering:!0}),Dt=new L.MeshPhysicalMaterial({color:new L.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Lt=new L.MeshPhysicalMaterial({color:new L.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:L.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Pt=new L.MeshPhysicalMaterial({color:new L.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ot=new L.MeshPhysicalMaterial({color:new L.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});import*as j from"three";import{Line2 as Vt}from"three/addons/lines/Line2.js";import{LineGeometry as Bt}from"three/addons/lines/LineGeometry.js";import{LineMaterial as zt}from"three/addons/lines/LineMaterial.js";function J(e,r,t,n=!0){return{x:e,y:r,z:t}}var Ft="#ffffff",re=12,jt=4e-4,kt=12,_t=.05;function we(e,r={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:n=!0}=r,o=[];for(let a of e)switch(a.kind){case"curve":{let i=Nt(a,t,n);i&&o.push(i);break}case"point":{o.push(Ut(a,n));break}default:{let i=a;v().warn(`Skipping unknown display item kind: ${String(i.kind)}`);break}}return o}var Gt=2;function Nt(e,r,t){if(!r)return v().warn("No rhino3dm instance provided; skipping curve display item."),null;let n=Wt(e.json,r);if(!n)return null;let o=$t(n,t);if(o.length<2)return null;let a=[];for(let u of o)a.push(u.x,u.y,u.z);let i=new Bt;i.setPositions(a);let s=He(e.color,e.opacity),l=new zt({color:s.color}),c=l;c.linewidth=e.width??Gt,c.transparent=s.transparent,c.opacity=s.opacity;let d=new Vt(i,l);return d.computeLineDistances(),d.name=e.name,d.userData={id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},d}function Ut(e,r){let{x:t,y:n,z:o}=J(e.position.X,e.position.Y,e.position.Z,r),a=new j.BufferGeometry;a.setAttribute("position",new j.Float32BufferAttribute([t,n,o],3));let i=new j.PointsMaterial({...He(e.color,e.opacity),size:6,sizeAttenuation:!1}),s=new j.Points(a,i);return s.name=e.name,s.userData={id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},s}function Wt(e,r){try{let t=JSON.parse(e),n=r.CommonObject.decode(t);return n&&typeof n.pointAt=="function"?n:(v().warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return v().warn("Failed to decode curve display item JSON:",t),null}}function $t(e,r){let t=Yt(e,r);return t||Xt(e,r)}function Yt(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 o=[];for(let a=0;a<n.count;a++){let i=n.get(a),{x:s,y:l,z:c}=J(i[0],i[1],i[2],r);o.push(new j.Vector3(s,l,c))}return o}function Xt(e,r){let t=e.domain,n=t[0],a=t[1]-n,i=c=>{let d=e.pointAt(c),{x:u,y:m,z:E}=J(d[0],d[1],d[2],r);return new j.Vector3(u,m,E)},s=qt(e),l=[i(n)];for(let c=0;c<re;c++){let d=n+a*c/re,u=n+a*(c+1)/re;oe(d,i(d),u,i(u),i,s,kt,l),l.push(i(u))}return l}function oe(e,r,t,n,o,a,i,s){if(i<=0)return;let l=(e+t)/2,c=o(l),d=Jt(c,r,n),u=Zt(r,c,n);d<=a&&u<=_t||(oe(e,r,l,c,o,a,i-1,s),s.push(c),oe(l,c,t,n,o,a,i-1,s))}function qt(e){let r=e.getBoundingBox(),t=r.min,n=r.max,o=Math.hypot(n[0]-t[0],n[1]-t[1],n[2]-t[2]);return Math.max(o*jt,1e-6)}function Zt(e,r,t){let n=r.clone().sub(e),o=t.clone().sub(r),a=n.length(),i=o.length();if(a===0||i===0)return 0;let s=Math.max(-1,Math.min(1,n.dot(o)/(a*i)));return Math.acos(s)}function Jt(e,r,t){let n=t.clone().sub(r),o=n.lengthSq();if(o===0)return e.distanceTo(r);let a=Math.max(0,Math.min(1,e.clone().sub(r).dot(n)/o)),i=r.clone().addScaledVector(n,a);return e.distanceTo(i)}function He(e,r){let t=r??1;return{color:new j.Color(e??Ft),transparent:t<1,opacity:t}}var ve=1096174675,Me=1,ae=1,Ce=12,xe=56;function ie(e){let r=Kt(e),t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Ce)throw N("Blob too small to contain SLVA header.",{expectedBytes:Ce,availableBytes:r.byteLength});let n=0,o=t.getUint32(n,!0);if(n+=4,o!==ve)throw N(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${ve.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=t.getUint32(n,!0);if(n+=4,a!==Me)throw N(`Unsupported SLVA version: ${a}`,{expectedVersion:Me,actualVersion:a});let i=t.getUint32(n,!0);if(n+=4,n+i>r.byteLength)throw N("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-n,offset:n});let s=r.subarray(n,n+i);n+=i;let l;try{l=JSON.parse(Qt(s))}catch(h){throw N(`Failed to parse metadata JSON: ${h instanceof Error?h.message:String(h)}`,{metadataLen:i})}if(n+xe>r.byteLength)throw N("Insufficient data to read geometry header.",{expectedBytes:xe,availableBytes:r.byteLength-n,offset:n});let c=t.getUint32(n,!0);n+=4;let d=t.getFloat64(n,!0);n+=8;let u=t.getFloat64(n,!0);n+=8;let m=t.getFloat64(n,!0);n+=8;let E=t.getFloat64(n,!0);n+=8;let f=t.getFloat64(n,!0);n+=8;let x=t.getFloat64(n,!0);n+=8;let S=t.getUint32(n,!0);n+=4;let b=(c&ae)!==0,g=S*3,H=g*(b?4:2);if(n+H>r.byteLength)throw N("Insufficient data to read vertices.",{expectedBytes:H,availableBytes:r.byteLength-n,offset:n,useFloat32:b,vertexCount:S});let P=r.byteOffset+n,y=b?tn(r.buffer,P,g):en(r.buffer,P,g);if(n+=H,n+4>r.byteLength)throw N("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-n,offset:n});let w=t.getUint32(n,!0);n+=4;let C=w*4;if(n+C>r.byteLength)throw N("Insufficient data to read indices.",{expectedBytes:C,availableBytes:r.byteLength-n,offset:n,indexCount:w});let O=nn(r.buffer,r.byteOffset+n,w);return{metadata:l,flags:c,vertices:y,indices:O,origin:[d,u,m],scale:[E,f,x]}}function Kt(e){return typeof e=="string"?ce(e):e instanceof Uint8Array?e:new Uint8Array(e)}function Qt(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 te("No UTF-8 decoder available in this environment.",ee.INVALID_STATE)}function en(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 tn(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 nn(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 N(e,r){return new te(e,ee.VALIDATION_ERROR,{context:r})}import*as B from"three";async function Se(e,r){let{debug:t=!1}=r??{},n=t?performance.now():0;try{let o=performance.now(),a=JSON.parse(e),i=performance.now()-o;return await rn(a,r,{parseTime:i,perfStart:n})}catch(o){return v().error("Error parsing mesh batch:",o),[]}}async function rn(e,r,t){let{mergeByMaterial:n=!0,applyTransforms:o=!0,scaleFactor:a=1,debug:i=!1}=r??{},{parseTime:s=0,perfStart:l=i?performance.now():0}=t??{};try{let c=performance.now(),d=ie(e.compressedData),u=performance.now()-c,m=i?dn(e.compressedData):0;return Ae(d,{mergeByMaterial:n,applyTransforms:o,scaleFactor:a,debug:i,parseTime:s,decodeTime:u,perfStart:l,blobBytes:m,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(c){return v().error("Error parsing mesh batch object:",c),[]}}async function gr(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:a=!1}=r??{},i=a?performance.now():0;try{let s=performance.now(),l=ie(e),c=performance.now()-s,d=e.byteLength;return Ae(l,{mergeByMaterial:t,applyTransforms:n,scaleFactor:o,debug:a,parseTime:0,decodeTime:c,perfStart:i,blobBytes:d})}catch(s){return v().error("Error parsing mesh batch blob:",s),[]}}function Ae(e,r){let{mergeByMaterial:t,applyTransforms:n,scaleFactor:o,debug:a,parseTime:i,decodeTime:s,perfStart:l,blobBytes:c,fallback:d}=r,u=e.metadata.materials??d?.materials??[],m=e.metadata.groups??d?.groups??[],E=e.metadata.sourceComponentId??d?.sourceComponentId,f=(e.flags&ae)!==0,x=f?an(e.vertices,n):on(e.vertices,e.origin,e.scale,n);if(a){let H=e.vertices.byteLength+e.indices.byteLength;v().debug("Mesh Batch Stats:"),v().debug(` Materials: ${u.length} | Groups: ${m.length}`),v().debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),v().debug(` Format: ${f?"float32":"int16 quantized"}`),v().debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(H/1024/1024).toFixed(2)} MB`)}let S=performance.now(),b=u.map(sn),g=[];for(let H of m)if(t&&H.meshes.length>1){let P=ln(H,x,e.indices,b);P.userData.sourceComponentId=E??null,g.push(P)}else{let P=cn(H,x,e.indices,b);for(let y of P)y.userData.sourceComponentId=E??null;g.push(...P)}if(o!==1)for(let H of g)H.scale.set(o,o,o);let R=performance.now()-S;if(a){let H=performance.now()-l;v().debug("Performance:"),i>0&&v().debug(` Parse JSON: ${i.toFixed(2)}ms`),v().debug(` Decode binary: ${s.toFixed(2)}ms`),v().debug(` Create Meshes: ${R.toFixed(2)}ms`),v().debug(` Total: ${H.toFixed(2)}ms`)}return Promise.resolve(g)}function on(e,r,t,n){let o=new Float32Array(e.length),a=r[0],i=r[1],s=r[2],l=t[0],c=t[1],d=t[2];for(let u=0;u<e.length;u+=3)o[u]=a+(e[u]+32767)*l,o[u+1]=i+(e[u+1]+32767)*c,o[u+2]=s+(e[u+2]+32767)*d;return o}function an(e,r){return e}function sn(e){let r=de(e.color);return new B.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:B.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function ln(e,r,t,n){let o=0,a=0;for(let f of e.meshes)o+=f.vertexCount,a+=f.indexCount;let i=new Float32Array(o*3),s=new Uint32Array(a),l=0,c=0;for(let f of e.meshes){let x=f.vertexStart*3,S=f.vertexCount*3;i.set(r.subarray(x,x+S),l*3);let b=t.subarray(f.indexStart,f.indexStart+f.indexCount),g=l-f.vertexStart;if(g===0)s.set(b,c);else for(let R=0;R<b.length;R++)s[c+R]=b[R]+g;l+=f.vertexCount,c+=f.indexCount}let d=new B.BufferGeometry;d.setAttribute("position",new B.BufferAttribute(i,3)),d.setIndex(new B.BufferAttribute(s,1)),d.computeVertexNormals();let u=new B.Mesh(d,n[e.materialId]),m=e.meshes[0],E=e.meshes.map(f=>f.name).filter(f=>f&&f.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:m?.layer??"",originalIndex:m?.originalIndex??0,metadata:m?.metadata??{},mergedFrom:e.meshes.slice(1).map(f=>({name:f.name,layer:f.layer,originalIndex:f.originalIndex}))},u}function cn(e,r,t,n){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,s=a.vertexCount*3,l=r.slice(i,i+s),c=t.subarray(a.indexStart,a.indexStart+a.indexCount),d=new Uint32Array(c.length),u=a.vertexStart;for(let f=0;f<c.length;f++)d[f]=c[f]-u;let m=new B.BufferGeometry;m.setAttribute("position",new B.BufferAttribute(l,3)),m.setIndex(new B.BufferAttribute(d,1)),m.computeVertexNormals();let E=new B.Mesh(m,n[e.materialId]);E.name=a.name,E.userData={name:a.name,layer:a.layer??"",originalIndex:a.originalIndex,metadata:a.metadata??{}},E.castShadow=!0,E.receiveShadow=!0,o.push(E)}return o}function dn(e){return Math.floor(e.length*3/4)}var un={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},mn="Display";async function Hr(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:a=!0,rhino:i,debug:s=!1,parsing:l={}}=r??{};try{let c=o?En(e.modelunits):1;return await pn(e,n,c,l,i,s),a&&bn(n),n}catch(c){throw yn(c,n),c}finally{s&&Tn(t)}}function En(e){return un[e]??1}async function pn(e,r,t,n,o,a){for(let i of e.values){let s=i.InnerTree;for(let l in s){let c=s[l];c&&await fn(c,r,t,n,o,a)}}}async function fn(e,r,t,n,o,a){for(let i of e){if(!i.type.includes(mn))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await Se(i.data,s),c=we(hn(i.data),{rhino:o,applyTransforms:s.applyTransforms}),d=[...l,...c];if(t!==1)for(let u of d)u.scale.set(t,t,t);r.push(...d),a&&v().debug(`Extracted ${l.length} meshes and ${c.length} items from batch`)}}function hn(e){return(typeof e=="string"?gn(e):e)?.items}function gn(e){try{return JSON.parse(e)}catch{return}}function bn(e){if(e.length===0)return;let r=Y(e);ue(e,r.min.z,"z")}function yn(e,r){v().error("An unexpected error occurred:",e),Rn(r)}function Rn(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 Tn(e){let r=performance.now()-e;v().info("Time to process meshes:",`${r.toFixed(2)}ms`)}export{Hn as a,de as b,ue as c,Y as d,me as e,Ee as f,pe as g,X as h,he as i,qe as j,On as k,ge as l,ye as m,ct as n,Te as o,nr as p,It as q,we as r,ve as s,Me as t,ae as u,ie as v,Se as w,rn as x,gr as y,un as z,Hr as A};
|
|
55
|
-
//# sourceMappingURL=chunk-
|
|
53
|
+
`;function Ee(e={}){let{cellSize:r=1,majorEvery:t=10,cellColor:n=8947848,majorColor:o=4473924,fadeDistance:a=100,plane:i="y"}=e,s=i==="y"?new I.Vector2(0,2):i==="z"?new I.Vector2(0,1):new I.Vector2(1,2),l=a*2.5,c=new I.PlaneGeometry(l,l);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let u=new I.ShaderMaterial({vertexShader:_e,fragmentShader:Ue,transparent:!0,depthWrite:!1,side:I.DoubleSide,uniforms:{uAxes:{value:s},uCell:{value:r},uMajor:{value:t},uCellColor:{value:new I.Color(n)},uMajorColor:{value:new I.Color(o)},uCenter:{value:new I.Vector3},uFade:{value:a}}}),d=new I.Mesh(c,u);d.name="grid",d.userData.id="grid",d.renderOrder=-1;let m=new I.Vector3;return{object:d,update:E=>{i==="y"?(d.position.set(E.x,0,E.z),m.set(E.x,0,E.z)):i==="z"?(d.position.set(E.x,E.y,0),m.set(E.x,E.y,0)):(d.position.set(0,E.y,E.z),m.set(0,E.y,E.z)),u.uniforms.uCenter.value.copy(m)},setVisible:E=>{d.visible=E},dispose:()=>{c.dispose(),u.dispose()}}}import*as F from"three";import{ViewHelper as Ge}from"three/addons/helpers/ViewHelper.js";function pe(e){let{camera:r,domElement:t,controller:n}=e,o=new Ge(r,t);o.setLabels("X","Y","Z");let a=!0,i=128,s=new F.Raycaster,l=new F.OrthographicCamera(-2,2,2,-2,0,4);l.position.set(0,0,2);let c={posX:new F.Vector3(1,0,0),negX:new F.Vector3(-1,0,0),posY:new F.Vector3(0,1,0),negY:new F.Vector3(0,-1,0),posZ:new F.Vector3(0,0,1),negZ:new F.Vector3(0,0,-1)},u=m=>{let E=t.getBoundingClientRect(),f=E.left+t.offsetWidth-i-o.location.right,x=E.top+t.offsetHeight-i-o.location.bottom,S=new F.Vector2((m.clientX-f)/i*2-1,-((m.clientY-x)/i)*2+1);if(Math.abs(S.x)>1||Math.abs(S.y)>1)return null;o.quaternion.copy(r.quaternion).invert(),o.updateMatrixWorld(),s.setFromCamera(S,l);let b=s.intersectObjects(o.children,!1);for(let h of b){let T=h.object.userData?.type;if(typeof T=="string"&&T in c)return T}return null};return{render:m=>{if(!a)return;let E=m.autoClear;m.autoClear=!1,o.render(m),m.autoClear=E},update:m=>{o.animating&&o.update(m)},handleClick:m=>{if(!a)return!1;let E=u(m);return E?(n.getProjection()==="orthographic"&&n.setProjection("perspective"),n.setViewDirection(c[E],!1),!0):!1},get isAnimating(){return o.animating},setVisible:m=>{a=m},isVisible:()=>a,dispose:()=>o.dispose()}}import*as $ from"three";import{LineSegmentsGeometry as Ne}from"three/addons/lines/LineSegmentsGeometry.js";import{LineSegments2 as fe}from"three/addons/lines/LineSegments2.js";import{LineMaterial as We}from"three/addons/lines/LineMaterial.js";var X="edge-overlay",$e=2236962,Ye=1.5,Xe=30;function he(e,r={}){let t=new $.Color(r.color??$e),n=r.width??Ye,o=r.thresholdAngle??Xe,a=[];return e.traverse(i=>{if(!(i instanceof $.Mesh)||i.userData.id==="floor"||i.userData.id==="grid"||i.userData.kind===X||i.children.some(l=>l.userData?.kind===X)||!i.geometry)return;let s=qe(i.geometry,t,n,o);i.add(s),a.push(s)}),a}function qe(e,r,t,n){let o=new $.EdgesGeometry(e,n),a=new Ne;a.setPositions(Array.from(o.attributes.position.array)),o.dispose();let i=new We({color:r});i.linewidth=t,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-1;let s=new fe(a,i);return s.userData.kind=X,s.raycast=()=>{},s}function Ze(e){return e.userData?.kind===X}function jn(e){let r=[];e.traverse(t=>{t instanceof fe&&Ze(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 Ke}from"three/addons/postprocessing/RenderPass.js";import{GTAOPass as Qe}from"three/addons/postprocessing/GTAOPass.js";import{OutputPass as et}from"three/addons/postprocessing/OutputPass.js";function ge(e,r,t,n,o,a){let i=new Je(e),s=new Ke(r,t);i.addPass(s);let l=new Qe(r,t,n,o);l.blendIntensity=a.aoIntensity??1,l.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(l);let c=new et;return i.addPass(c),e.toneMapping=a.toneMapping,e.toneMappingExposure=a.toneMappingExposure,i.setSize(n,o),{render:u=>i.render(u),setSize:(u,d,m)=>{i.setPixelRatio(m),i.setSize(u,d),l.setSize(u,d)},setCamera:u=>{s.camera=u,l.camera=u},dispose:()=>i.dispose()}}import*as be from"three";import{CSS2DRenderer as tt,CSS2DObject as nt}from"three/addons/renderers/CSS2DRenderer.js";function ye(e,r){let t=new tt,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",n.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(n);let o={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(o.width,o.height);let a=new be.Group;a.name="label-layer",a.userData.id="label-layer",r.add(a);let i=new Set;return{addLabel:(l,c,u)=>{let d=document.createElement("div");d.textContent=l,u?d.className=u:Object.assign(d.style,{padding:"2px 6px",borderRadius:"4px",background:"rgba(20, 20, 20, 0.78)",color:"#fff",font:"12px/1.3 system-ui, sans-serif",whiteSpace:"pre",textAlign:"center",userSelect:"none"}),d.style.pointerEvents="none";let m=new nt(d);return m.position.copy(c),a.add(m),i.add(m),{object:m,setPosition:E=>m.position.copy(E),setText:E=>{d.textContent=E},remove:()=>{m.removeFromParent(),d.remove(),i.delete(m)}}},render:(l,c)=>t.render(l,c),setSize:(l,c)=>t.setSize(l,c),dispose:()=>{i.forEach(l=>{l.removeFromParent(),l.element.remove()}),i.clear(),a.removeFromParent(),n.remove()}}}import*as A from"three";import{Line2 as rt}from"three/addons/lines/Line2.js";import{LineGeometry as ot}from"three/addons/lines/LineGeometry.js";import{LineMaterial as at}from"three/addons/lines/LineMaterial.js";var it=12,st=16763904,Re=.015,q=e=>`${e.toPrecision(3)} m`,lt=(e,r)=>`${q(e)}
|
|
54
|
+
\u0394x ${q(r.x)} \u0394y ${q(r.y)} \u0394z ${q(r.z)}`;function ct(e){let r=e.object;return r instanceof A.Mesh?e.face?[e.face.a,e.face.b,e.face.c]:null:r instanceof A.Points?e.index!=null?[e.index]:null:r instanceof A.Line&&e.index!=null?[e.index,e.index+1]:null}function ut(e,r,t,n){let o=e.point.clone(),a=e.object,i=ct(e);if(!i||!a.geometry)return o;let s=a.geometry.attributes.position;if(!s)return o;let l=m=>{let E=m.clone().project(r);return new A.Vector2((E.x+1)/2*t.width,(1-E.y)/2*t.height)},c=l(o),u=o,d=n;for(let m of i){if(m>=s.count)continue;let f=new A.Vector3().fromBufferAttribute(s,m).applyMatrix4(a.matrixWorld),x=l(f).distanceTo(c);x<d&&(d=x,u=f)}return u}function Te(e){let{canvas:r,scene:t,getActiveCamera:n,labelLayer:o,options:a={}}=e,i=a.snapPixels??it,s=new A.Color(a.color??st),l=a.format??lt,c=new A.Raycaster,u=new A.Vector2,d=!1,m=[],E=[],f=null,x=null,S=new A.PointsMaterial({color:s,size:8,sizeAttenuation:!1,depthTest:!1}),b=new A.PointsMaterial({color:s,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),h=null,T=g=>{if(!g){h&&(h.visible=!1);return}if(!h){let R=new A.BufferGeometry;R.setAttribute("position",new A.Float32BufferAttribute([0,0,0],3)),h=new A.Points(R,b),h.renderOrder=1e3,h.userData.id="measure",h.raycast=()=>{},t.add(h)}h.position.copy(g),h.visible=!0},v=g=>{let R=new A.BufferGeometry;R.setAttribute("position",new A.Float32BufferAttribute([g.x,g.y,g.z],3));let H=new A.Points(R,S);return H.renderOrder=999,H.userData.id="measure",H.raycast=()=>{},t.add(H),H},P=()=>{m.length=0,E.forEach(g=>{g.geometry.dispose(),g.removeFromParent()}),E.length=0,f&&(f.geometry.dispose(),f.material.dispose(),f.removeFromParent(),f=null),x?.remove(),x=null},y=()=>{if(m.length!==2)return;let[g,R]=m,H=new ot;H.setPositions([g.x,g.y,g.z,R.x,R.y,R.z]);let k=new at({color:s});k.linewidth=2,k.depthTest=!1,f=new rt(H,k),f.renderOrder=998,f.userData.id="measure",f.raycast=()=>{},t.add(f);let N=g.clone().add(R).multiplyScalar(.5),W=new A.Vector3(Math.abs(R.x-g.x),Math.abs(R.y-g.y),Math.abs(R.z-g.z));x=o.addLabel(l(g.distanceTo(R),W),N,a.labelClassName)},w=g=>{let R=r.getBoundingClientRect();u.x=(g.clientX-R.left)/R.width*2-1,u.y=-((g.clientY-R.top)/R.height)*2+1;let H=n();c.setFromCamera(u,H);let k=H.position.length();c.params.Line={threshold:k*Re},c.params.Points={threshold:k*Re};let N=c.intersectObjects(t.children,!0).filter(W=>W.object.userData.id!=="measure"&&W.object.userData.id!=="grid");return N.length===0?null:ut(N[0],H,{width:R.width,height:R.height},i)};return{setEnabled:g=>{d=g,g||(P(),T(null))},isEnabled:()=>d,handleClick:g=>{if(!d)return!1;m.length===2&&P();let R=w(g);return R===null||(m.push(R),E.push(v(R)),m.length===2&&y()),!0},handleMove:g=>{d&&T(w(g))},clear:P,dispose:()=>{P(),h&&(h.geometry.dispose(),h.removeFromParent(),h=null),S.dispose(),b.dispose()}}}import*as p from"three";import{OrbitControls as dt}from"three/addons/controls/OrbitControls.js";import{HDRLoader as mt}from"three/addons/loaders/HDRLoader.js";var Z=new p.Vector3(0,0,1);function Et(e){let r=Math.abs(e.x),t=Math.abs(e.y),n=Math.abs(e.z);return n>=r&&n>=t?"z":t>=r&&t>=n?"y":"x"}var lr=function(e,r){let t=pt(r||{}),n=t.environment?.sceneUp||Z,o=bt(t),a=vt(t,e);a.up.copy(n);let i=Mt(e,t),s=xt(a,e,t),l=me({scene:o,perspective:a,controls:s,onActiveCameraChange:()=>{},up:n}),c=()=>l.getActiveCamera();Tt(o,t);let u=wt(o,t),d=()=>{u&>(u,ne(o))};t.floor?.enabled&&Ht(o,t);let m=t.grid.enabled?Ee({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;m&&o.add(m.object);let E=t.gizmo.enabled?pe({camera:a,domElement:e,controller:l}):null,f=e.parentElement??e,x=t.measure.enabled?ye(f,o):null,S=t.measure.enabled&&x?Te({canvas:e,scene:o,getActiveCamera:c,labelLayer:x,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,format:t.measure.format}}):null,b=t.events.enableEventHandlers!==!1?Ct(e,o,c,a,s,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},h=5,T=0,v=0,P=D=>{T=D.clientX,v=D.clientY},y=D=>Math.hypot(D.clientX-T,D.clientY-v)>h,w=D=>{if(!y(D)){if(S?.handleClick(D)){D.stopImmediatePropagation();return}E?.handleClick(D)&&D.stopImmediatePropagation()}};(E||S)&&(e.addEventListener("mousedown",P,{capture:!0}),e.addEventListener("click",w,{capture:!0}));let C=D=>S?.handleMove(D);S&&e.addEventListener("mousemove",C,{passive:!0});let O=D=>{he(D,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},g=e.parentElement,R=()=>g?{width:g.clientWidth,height:g.clientHeight}:{width:window.innerWidth,height:window.innerHeight},H=null,k=()=>{let{width:D,height:G}=R(),Q=Math.min(window.devicePixelRatio,2),le=ge(i,o,c(),Math.max(1,D),Math.max(1,G),{toneMapping:t.render.toneMapping??p.NeutralToneMapping,toneMappingExposure:t.render.toneMappingExposure??1,aoIntensity:t.render.aoIntensity});return le.setSize(Math.max(1,D),Math.max(1,G),Q),le},N=D=>{D&&!H?H=k():!D&&H&&(H.dispose(),H=null)};t.render.ambientOcclusion&&(H=k());let{animate:W,dispose:K}=Rt(i,o,a,c,l,s,R,t.events.onFrame,m,E,()=>H,x);return W(),o.up.set(n.x,n.y,n.z),d(),{scene:o,camera:a,controls:s,renderer:i,cameraController:l,grid:m,gizmo:E,measureTool:S,applyEdges:O,setAmbientOcclusion:N,updateShadowBounds:d,dispose:()=>{K(),b.dispose(),(E||S)&&(e.removeEventListener("mousedown",P,{capture:!0}),e.removeEventListener("click",w,{capture:!0})),S&&e.removeEventListener("mousemove",C),S?.dispose(),x?.dispose(),E?.dispose(),m?.dispose(),H?.dispose(),s.dispose(),i.dispose(),o.traverse(D=>{let G=D;!G.geometry&&!G.material||(G.geometry?.dispose(),Array.isArray(G.material)?G.material.forEach(Q=>Q.dispose()):G.material?.dispose())})},fitToView:b.fitToView,clearSelection:b.clearSelection}};function pt(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 p.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 p.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity||1,sunlightPosition:e.lighting?.sunlightPosition||new p.Vector3(n.lightDistance,n.lightDistance,n.lightHeight),ambientLightColor:e.lighting?.ambientLightColor||new p.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity||1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new p.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||Z,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||n.floorSize,color:e.floor?.color||new p.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||p.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??Et(e.environment?.sceneUp??Z)},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 ft=new Set(["grid","floor","label-layer","measure"]);function ht(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&ft.has(r.userData.id))return!0;r=r.parent}return!1}function ne(e){let r=new p.Box3;return e.traverse(t=>{let n=t;t.visible&&!ht(t)&&n.geometry&&r.expandByObject(t)}),r}function gt(e,r){if(r.isEmpty())return;let t=r.getCenter(new p.Vector3),n=r.getSize(new p.Vector3).length()*.5*1.2,o=e.shadow.camera;o.left=-n,o.right=n,o.top=n,o.bottom=-n,e.target.position.copy(t),e.target.updateMatrixWorld();let a=e.position.distanceTo(t);o.near=Math.max(n*.01,a-n),o.far=a+n,o.updateProjectionMatrix()}function bt(e){let r=new p.Scene,t=typeof e.environment.backgroundColor=="string"?new p.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function yt(e,r,t,n,o=200){let a=e.position.clone(),i=r.target.clone(),s=performance.now(),l=u=>1-Math.pow(1-u,3),c=()=>{let u=performance.now()-s,d=l(Math.min(u/o,1));e.position.lerpVectors(a,t,d),r.target.lerpVectors(i,n,d),r.update(),d<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}function Rt(e,r,t,n,o,a,i,s,l,c,u,d){let m=null,E=performance.now(),f=()=>{let{width:b,height:h}=i();if(b===0||h===0)return;let T=Math.min(window.devicePixelRatio,2),v=Math.round(b*T),P=Math.round(h*T);(e.domElement.width!==v||e.domElement.height!==P)&&(e.setPixelRatio(T),e.setSize(b,h,!1),t.aspect=b/h,t.updateProjectionMatrix(),o.updateAspect(b,h),u?.()?.setSize(b,h,T),d?.setSize(b,h))},x=function(){m=requestAnimationFrame(x);let b=performance.now(),h=(b-E)/1e3;E=b,f(),(a.enableDamping||a.autoRotate)&&a.update(),l&&l.update(n().position),c&&c.update(h),s?.(h);let T=n(),v=u?.();v?(v.setCamera(T),v.render(h)):e.render(r,T),d&&d.render(r,T),c&&c.render(e)};return{animate:x,dispose:()=>{m!==null&&(cancelAnimationFrame(m),m=null)}}}function Tt(e,r){r.environment.enableEnvironmentLighting?new mt().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){if(!t?.image){M().warn("HDR loaded without image data; skipping environment map."),r.events.onReady?.();return}t.mapping=p.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t),r.events.onReady?.()},void 0,function(t){M().warn("HDR texture could not be loaded, falling back to basic lighting:",t),r.events.onReady?.()}):r.events.onReady?.()}function wt(e,r){let t=new p.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),!r.lighting.enableSunlight)return null;let n=new p.DirectionalLight(r.lighting.sunlightColor??16777215,r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;return o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows?(n.castShadow=!0,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,n.shadow.radius=4,e.add(n),e.add(n.target),n):(e.add(n),null)}function Ht(e,r){let t=r.floor.size,n=new p.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new p.Color(r.floor.color):r.floor.color,a=new p.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:p.DoubleSide}),i=new p.Mesh(n,a);i.userData.id="floor",i.name="floor";let s=(r.environment?.sceneUp||Z).clone().normalize();i.quaternion.setFromUnitVectors(new p.Vector3(0,0,1),s),i.position.set(0,0,0),r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function vt(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,a=new p.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function Mt(e,r){let t=new p.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,a=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,a,!1),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=p.VSMShadowMap),t.toneMapping=r.render.toneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=p.SRGBColorSpace,t.sortObjects=!0,t}function Ct(e,r,t,n,o,a){let i=new Set,s=new Map,l=new p.Raycaster,c=new p.Vector2,u=new p.Vector2,d=y=>{let w=y;for(;w;){if(!w.visible)return!1;w=w.parent}return!0},m=()=>{let y=ne(r);if(y.isEmpty()){M().warn("No objects to fit to view");return}let w=y.getCenter(new p.Vector3),C=y.getSize(new p.Vector3),O=Math.max(C.x,C.y,C.z),g=n.fov*(Math.PI/180),R=O/(2*Math.tan(g/2));R*=1.5;let H=n.position.clone().sub(o.target);H.lengthSq()<1e-12&&H.set(.8,1,1.2),H.normalize(),n.position.copy(w.clone().add(H.multiplyScalar(R))),o.target.copy(w),o.update()},E=typeof a.events.selectionColor=="string"?new p.Color(a.events.selectionColor):a.events.selectionColor instanceof p.Color?a.events.selectionColor:new p.Color("#ff0000"),f=()=>{i.forEach(y=>{let w=y;if(s.has(y)){let C=s.get(y),O=w.material;O instanceof p.Material?O.dispose():Array.isArray(O)&&O.forEach(g=>g.dispose()),w.material=C,s.delete(y)}}),i.clear()},x=y=>{let w=y;if(!(w.material instanceof p.Material))return!1;s.set(y,w.material);let C=w.material.clone();return y instanceof p.Mesh&&"emissive"in C?C.emissive=E.clone():"color"in C&&(C.color=E.clone()),w.material=C,!0},S=()=>{let y=ne(r),w=y.isEmpty()?1:y.getSize(new p.Vector3).length();l.params.Points.threshold=w*.01},b=y=>{u.set(y.clientX,y.clientY)},h=y=>{let w=new p.Vector2(y.clientX,y.clientY);if(u.distanceTo(w)>5)return;let C=e.getBoundingClientRect();c.x=(y.clientX-C.left)/C.width*2-1,c.y=-((y.clientY-C.top)/C.height)*2+1,S(),l.setFromCamera(c,t());let O=l.intersectObjects(r.children,!0).filter(g=>d(g.object));if(O.length>0){let g=O[0].object;i.has(g)||(f(),i.add(g),x(g),a.events?.onObjectSelected?.(g),g instanceof p.Mesh&&Object.keys(g.userData).length>0&&a.events?.onMeshMetadataClicked?.(g.userData))}else f(),a.events?.onBackgroundClicked?.({x:c.x,y:c.y})},T=y=>{let w=e.getBoundingClientRect();c.x=(y.clientX-w.left)/w.width*2-1,c.y=-((y.clientY-w.top)/w.height)*2+1,S(),l.setFromCamera(c,t());let C=l.intersectObjects(r.children,!0).filter(D=>d(D.object));if(C.length===0)return;let O=C[0].object;if(a.events?.onMeshDoubleClicked?.(O),!a.events?.enableDoubleClickZoom)return;let g=new p.Box3().setFromObject(O);if(g.isEmpty())return;let R=g.getCenter(new p.Vector3),H=g.getSize(new p.Vector3),k=Math.max(H.x,H.y,H.z),N=n.fov*(Math.PI/180),W=k/(2*Math.tan(N/2))*1.5,K=n.position.clone().sub(o.target).normalize(),se=R.clone().add(K.multiplyScalar(W));yt(n,o,se,R)},v=y=>{if(a.events?.enableKeyboardControls)switch(y.key.toLowerCase()){case"f":y.preventDefault(),m();break;case"escape":y.preventDefault(),f();break;case" ":y.preventDefault(),m();break}};return a.events?.enableClickToFocus&&(e.addEventListener("mousedown",b),e.addEventListener("click",h),e.addEventListener("dblclick",T)),a.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",v)),{dispose:()=>{e.removeEventListener("mousedown",b),e.removeEventListener("click",h),e.removeEventListener("dblclick",T),e.removeEventListener("keydown",v),f()},fitToView:m,clearSelection:f}}function xt(e,r,t){let n=new dt(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.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 Vt={};Le(Vt,{CONCRETE_MATERIAL:()=>Dt,EMISSIVE_MATERIAL:()=>St,GLASS_MATERIAL:()=>Pt,METAL_MATERIAL:()=>At,PLASTIC_MATERIAL:()=>Lt,RUBBER_MATERIAL:()=>Ot,WOOD_MATERIAL:()=>It});import*as L from"three";var St=new L.MeshPhysicalMaterial({color:0,emissive:new L.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),At=new L.MeshPhysicalMaterial({color:new L.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:L.FrontSide,dithering:!0}),Dt=new L.MeshPhysicalMaterial({color:new L.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:L.FrontSide,dithering:!0}),Lt=new L.MeshPhysicalMaterial({color:new L.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Pt=new L.MeshPhysicalMaterial({color:new L.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:L.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ot=new L.MeshPhysicalMaterial({color:new L.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),It=new L.MeshPhysicalMaterial({color:new L.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});import*as j from"three";import{Line2 as Bt}from"three/addons/lines/Line2.js";import{LineGeometry as zt}from"three/addons/lines/LineGeometry.js";import{LineMaterial as Ft}from"three/addons/lines/LineMaterial.js";function J(e,r,t,n=!0){return{x:e,y:r,z:t}}var jt="#ffffff",re=12,kt=4e-4,_t=12,Ut=.05;function we(e,r={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:n=!0}=r,o=[];for(let a of e)switch(a.kind){case"curve":{let i=Nt(a,t,n);i&&o.push(i);break}case"point":{o.push(Wt(a,n));break}default:{let i=a;M().warn(`Skipping unknown display item kind: ${String(i.kind)}`);break}}return o}var Gt=2;function Nt(e,r,t){if(!r)return M().warn("No rhino3dm instance provided; skipping curve display item."),null;let n=$t(e.json,r);if(!n)return null;let o=Yt(n,t);if(o.length<2)return null;let a=[];for(let d of o)a.push(d.x,d.y,d.z);let i=new zt;i.setPositions(a);let s=He(e.color,e.opacity),l=new Ft({color:s.color}),c=l;c.linewidth=e.width??Gt,c.transparent=s.transparent,c.opacity=s.opacity;let u=new Bt(i,l);return u.computeLineDistances(),u.name=e.name,u.userData={id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},u}function Wt(e,r){let{x:t,y:n,z:o}=J(e.position.X,e.position.Y,e.position.Z,r),a=new j.BufferGeometry;a.setAttribute("position",new j.Float32BufferAttribute([t,n,o],3));let i=new j.PointsMaterial({...He(e.color,e.opacity),size:6,sizeAttenuation:!1}),s=new j.Points(a,i);return s.name=e.name,s.userData={id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},s}function $t(e,r){try{let t=JSON.parse(e),n=r.CommonObject.decode(t);return n&&typeof n.pointAt=="function"?n:(M().warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return M().warn("Failed to decode curve display item JSON:",t),null}}function Yt(e,r){let t=Xt(e,r);return t||qt(e,r)}function Xt(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 o=[];for(let a=0;a<n.count;a++){let i=n.get(a),{x:s,y:l,z:c}=J(i[0],i[1],i[2],r);o.push(new j.Vector3(s,l,c))}return o}function qt(e,r){let t=e.domain,n=t[0],a=t[1]-n,i=c=>{let u=e.pointAt(c),{x:d,y:m,z:E}=J(u[0],u[1],u[2],r);return new j.Vector3(d,m,E)},s=Zt(e),l=[i(n)];for(let c=0;c<re;c++){let u=n+a*c/re,d=n+a*(c+1)/re;oe(u,i(u),d,i(d),i,s,_t,l),l.push(i(d))}return l}function oe(e,r,t,n,o,a,i,s){if(i<=0)return;let l=(e+t)/2,c=o(l),u=Kt(c,r,n),d=Jt(r,c,n);u<=a&&d<=Ut||(oe(e,r,l,c,o,a,i-1,s),s.push(c),oe(l,c,t,n,o,a,i-1,s))}function Zt(e){let r=e.getBoundingBox(),t=r.min,n=r.max,o=Math.hypot(n[0]-t[0],n[1]-t[1],n[2]-t[2]);return Math.max(o*kt,1e-6)}function Jt(e,r,t){let n=r.clone().sub(e),o=t.clone().sub(r),a=n.length(),i=o.length();if(a===0||i===0)return 0;let s=Math.max(-1,Math.min(1,n.dot(o)/(a*i)));return Math.acos(s)}function Kt(e,r,t){let n=t.clone().sub(r),o=n.lengthSq();if(o===0)return e.distanceTo(r);let a=Math.max(0,Math.min(1,e.clone().sub(r).dot(n)/o)),i=r.clone().addScaledVector(n,a);return e.distanceTo(i)}function He(e,r){let t=r??1;return{color:new j.Color(e??jt),transparent:t<1,opacity:t}}import{inflateSync as Qt}from"fflate";var ve=1096174675,en=1515605075,Me=2,Ce=1,ae=1,tn=2,xe=12,Se=56;function ie(e){let r=rn(nn(e)),t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<xe)throw U("Blob too small to contain SLVA header.",{expectedBytes:xe,availableBytes:r.byteLength});let n=0,o=t.getUint32(n,!0);if(n+=4,o!==ve)throw U(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${ve.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=t.getUint32(n,!0);if(n+=4,a<Ce||a>Me)throw U(`Unsupported SLVA version: ${a}`,{minSupportedVersion:Ce,maxSupportedVersion:Me,actualVersion:a});let i=t.getUint32(n,!0);if(n+=4,n+i>r.byteLength)throw U("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-n,offset:n});let s=r.subarray(n,n+i);n+=i;let l;try{l=JSON.parse(on(s))}catch(H){throw U(`Failed to parse metadata JSON: ${H instanceof Error?H.message:String(H)}`,{metadataLen:i})}if(n+Se>r.byteLength)throw U("Insufficient data to read geometry header.",{expectedBytes:Se,availableBytes:r.byteLength-n,offset:n});let c=t.getUint32(n,!0);n+=4;let u=t.getFloat64(n,!0);n+=8;let d=t.getFloat64(n,!0);n+=8;let m=t.getFloat64(n,!0);n+=8;let E=t.getFloat64(n,!0);n+=8;let f=t.getFloat64(n,!0);n+=8;let x=t.getFloat64(n,!0);n+=8;let S=t.getUint32(n,!0);n+=4;let b=(c&ae)!==0,h=S*3,v=h*(b?4:2);if(n+v>r.byteLength)throw U("Insufficient data to read vertices.",{expectedBytes:v,availableBytes:r.byteLength-n,offset:n,useFloat32:b,vertexCount:S});let P=r.byteOffset+n,y=b?sn(r.buffer,P,h):an(r.buffer,P,h);if(n+=v,n+4>r.byteLength)throw U("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-n,offset:n});let w=t.getUint32(n,!0);n+=4;let C=(c&tn)!==0,g=w*(C?2:4);if(n+g>r.byteLength)throw U("Insufficient data to read indices.",{expectedBytes:g,availableBytes:r.byteLength-n,offset:n,indexCount:w,useUint16Indices:C});let R=C?ln(r.buffer,r.byteOffset+n,w):cn(r.buffer,r.byteOffset+n,w);return{metadata:l,flags:c,vertices:y,indices:R,origin:[u,d,m],scale:[E,f,x]}}function nn(e){return typeof e=="string"?ce(e):e instanceof Uint8Array?e:new Uint8Array(e)}function rn(e){if(e.byteLength<8)return e;let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(r.getUint32(0,!0)!==en)return e;let t=r.getUint32(4,!0),n=e.subarray(8);try{return Qt(n,{out:new Uint8Array(t)})}catch(o){throw U(`Failed to inflate SLVZ blob: ${o instanceof Error?o.message:String(o)}`,{uncompressedLen:t,deflatedBytes:n.byteLength})}}function on(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 te("No UTF-8 decoder available in this environment.",ee.INVALID_STATE)}function an(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 sn(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 ln(e,r,t){if(t===0)return new Uint16Array(0);if(r%2===0)return new Uint16Array(e,r,t);let n=new Uint8Array(t*2);return n.set(new Uint8Array(e,r,t*2)),new Uint16Array(n.buffer)}function cn(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 U(e,r){return new te(e,ee.VALIDATION_ERROR,{context:r})}import*as B from"three";async function Ae(e,r){let{debug:t=!1}=r??{},n=t?performance.now():0;try{let o=performance.now(),a=JSON.parse(e),i=performance.now()-o;return await un(a,r,{parseTime:i,perfStart:n})}catch(o){return M().error("Error parsing mesh batch:",o),[]}}async function un(e,r,t){let{mergeByMaterial:n=!0,applyTransforms:o=!0,scaleFactor:a=1,debug:i=!1}=r??{},{parseTime:s=0,perfStart:l=i?performance.now():0}=t??{};try{let c=performance.now(),u=ie(e.compressedData),d=performance.now()-c,m=i?hn(e.compressedData):0;return De(u,{mergeByMaterial:n,applyTransforms:o,scaleFactor:a,debug:i,parseTime:s,decodeTime:d,perfStart:l,blobBytes:m,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(c){return M().error("Error parsing mesh batch object:",c),[]}}async function vr(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:a=!1}=r??{},i=a?performance.now():0;try{let s=performance.now(),l=ie(e),c=performance.now()-s,u=e.byteLength;return De(l,{mergeByMaterial:t,applyTransforms:n,scaleFactor:o,debug:a,parseTime:0,decodeTime:c,perfStart:i,blobBytes:u})}catch(s){return M().error("Error parsing mesh batch blob:",s),[]}}function De(e,r){let{mergeByMaterial:t,applyTransforms:n,scaleFactor:o,debug:a,parseTime:i,decodeTime:s,perfStart:l,blobBytes:c,fallback:u}=r,d=e.metadata.materials??u?.materials??[],m=e.metadata.groups??u?.groups??[],E=e.metadata.sourceComponentId??u?.sourceComponentId,f=(e.flags&ae)!==0,x=f?mn(e.vertices,n):dn(e.vertices,e.origin,e.scale,n);if(a){let v=e.vertices.byteLength+e.indices.byteLength;M().debug("Mesh Batch Stats:"),M().debug(` Materials: ${d.length} | Groups: ${m.length}`),M().debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),M().debug(` Format: ${f?"float32":"int16 quantized"}`),M().debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(v/1024/1024).toFixed(2)} MB`)}let S=performance.now(),b=d.map(En),h=[];for(let v of m)if(t&&v.meshes.length>1){let P=pn(v,x,e.indices,b);P.userData.sourceComponentId=E??null,h.push(P)}else{let P=fn(v,x,e.indices,b);for(let y of P)y.userData.sourceComponentId=E??null;h.push(...P)}if(o!==1)for(let v of h)v.scale.set(o,o,o);let T=performance.now()-S;if(a){let v=performance.now()-l;M().debug("Performance:"),i>0&&M().debug(` Parse JSON: ${i.toFixed(2)}ms`),M().debug(` Decode binary: ${s.toFixed(2)}ms`),M().debug(` Create Meshes: ${T.toFixed(2)}ms`),M().debug(` Total: ${v.toFixed(2)}ms`)}return Promise.resolve(h)}function dn(e,r,t,n){let o=new Float32Array(e.length),a=r[0],i=r[1],s=r[2],l=t[0],c=t[1],u=t[2];for(let d=0;d<e.length;d+=3)o[d]=a+(e[d]+32767)*l,o[d+1]=i+(e[d+1]+32767)*c,o[d+2]=s+(e[d+2]+32767)*u;return o}function mn(e,r){return e}function En(e){let r=ue(e.color);return new B.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:B.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function pn(e,r,t,n){let o=0,a=0;for(let f of e.meshes)o+=f.vertexCount,a+=f.indexCount;let i=new Float32Array(o*3),s=new Uint32Array(a),l=0,c=0;for(let f of e.meshes){let x=f.vertexStart*3,S=f.vertexCount*3;i.set(r.subarray(x,x+S),l*3);let b=t.subarray(f.indexStart,f.indexStart+f.indexCount),h=l-f.vertexStart;if(h===0)s.set(b,c);else for(let T=0;T<b.length;T++)s[c+T]=b[T]+h;l+=f.vertexCount,c+=f.indexCount}let u=new B.BufferGeometry;u.setAttribute("position",new B.BufferAttribute(i,3)),u.setIndex(new B.BufferAttribute(s,1)),u.computeVertexNormals();let d=new B.Mesh(u,n[e.materialId]),m=e.meshes[0],E=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);return d.name=E.length>0?E[0]:`merged_material_${e.materialId}`,d.castShadow=!0,d.receiveShadow=!0,d.userData={name:d.name,layer:m?.layer??"",originalIndex:m?.originalIndex??0,metadata:m?.metadata??{},mergedFrom:e.meshes.slice(1).map(f=>({name:f.name,layer:f.layer,originalIndex:f.originalIndex}))},d}function fn(e,r,t,n){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,s=a.vertexCount*3,l=r.slice(i,i+s),c=t.subarray(a.indexStart,a.indexStart+a.indexCount),u=new Uint32Array(c.length),d=a.vertexStart;for(let f=0;f<c.length;f++)u[f]=c[f]-d;let m=new B.BufferGeometry;m.setAttribute("position",new B.BufferAttribute(l,3)),m.setIndex(new B.BufferAttribute(u,1)),m.computeVertexNormals();let E=new B.Mesh(m,n[e.materialId]);E.name=a.name,E.userData={name:a.name,layer:a.layer??"",originalIndex:a.originalIndex,metadata:a.metadata??{}},E.castShadow=!0,E.receiveShadow=!0,o.push(E)}return o}function hn(e){return Math.floor(e.length*3/4)}var gn={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},bn="Display";async function Dr(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:a=!0,rhino:i,debug:s=!1,parsing:l={}}=r??{};try{let c=o?yn(e.modelunits):1;return await Rn(e,n,c,l,i,s),a&&vn(n),n}catch(c){throw Mn(c,n),c}finally{s&&xn(t)}}function yn(e){return gn[e]??1}async function Rn(e,r,t,n,o,a){for(let i of e.values){let s=i.InnerTree;for(let l in s){let c=s[l];c&&await Tn(c,r,t,n,o,a)}}}async function Tn(e,r,t,n,o,a){for(let i of e){if(!i.type.includes(bn))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await Ae(i.data,s),c=we(wn(i.data),{rhino:o,applyTransforms:s.applyTransforms}),u=[...l,...c];if(t!==1)for(let d of u)d.scale.set(t,t,t);r.push(...u),a&&M().debug(`Extracted ${l.length} meshes and ${c.length} items from batch`)}}function wn(e){return(typeof e=="string"?Hn(e):e)?.items}function Hn(e){try{return JSON.parse(e)}catch{return}}function vn(e){if(e.length===0)return;let r=Y(e);de(e,r.min.z,"z")}function Mn(e,r){M().error("An unexpected error occurred:",e),Cn(r)}function Cn(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 xn(e){let r=performance.now()-e;M().info("Time to process meshes:",`${r.toFixed(2)}ms`)}export{An as a,ue as b,de as c,Y as d,me as e,Ee as f,pe as g,X as h,he as i,Ze as j,jn as k,ge as l,ye as m,ut as n,Te as o,lr as p,Vt as q,we as r,ve as s,Me as t,ae as u,ie as v,Ae as w,un as x,vr as y,gn as z,Dr as A};
|
|
55
|
+
//# sourceMappingURL=chunk-XULKNW75.js.map
|