@selvajs/compute 3.1.0-beta.11 → 3.1.0-beta.13
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-6R4EL3ZJ.cjs +2 -0
- package/dist/chunk-6R4EL3ZJ.cjs.map +1 -0
- package/dist/chunk-6TMSTNHN.js +2 -0
- package/dist/chunk-6TMSTNHN.js.map +1 -0
- package/dist/chunk-GLOTP5TC.cjs +120 -0
- package/dist/chunk-GLOTP5TC.cjs.map +1 -0
- package/dist/chunk-H3FZW6OX.cjs +4 -0
- package/dist/chunk-H3FZW6OX.cjs.map +1 -0
- package/dist/chunk-NVMSD4CC.js +120 -0
- package/dist/chunk-NVMSD4CC.js.map +1 -0
- package/dist/chunk-Y3M7P3BW.js +4 -0
- package/dist/chunk-Y3M7P3BW.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +22 -1
- package/dist/core.d.ts +22 -1
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.d.cts +20 -0
- package/dist/grasshopper.d.ts +20 -0
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/visualization-BIHTM2KJ.js +2 -0
- package/dist/visualization-FLDYIZ3F.cjs +2 -0
- package/dist/visualization-FLDYIZ3F.cjs.map +1 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.cjs.map +1 -1
- package/dist/visualization.d.cts +193 -21
- package/dist/visualization.d.ts +193 -21
- package/dist/visualization.js +1 -1
- package/package.json +55 -34
- package/dist/chunk-7XMD5YXP.cjs +0 -62
- package/dist/chunk-7XMD5YXP.cjs.map +0 -1
- package/dist/chunk-C7P43VZF.js +0 -2
- package/dist/chunk-C7P43VZF.js.map +0 -1
- package/dist/chunk-CUQQ3ZBV.cjs +0 -4
- package/dist/chunk-CUQQ3ZBV.cjs.map +0 -1
- package/dist/chunk-PX2YTSHJ.js +0 -62
- package/dist/chunk-PX2YTSHJ.js.map +0 -1
- package/dist/chunk-QZECCPT3.cjs +0 -2
- package/dist/chunk-QZECCPT3.cjs.map +0 -1
- package/dist/chunk-WPB2LKCD.js +0 -4
- package/dist/chunk-WPB2LKCD.js.map +0 -1
- package/dist/visualization-4RSUYQG2.cjs +0 -2
- package/dist/visualization-4RSUYQG2.cjs.map +0 -1
- package/dist/visualization-MOYO6MDN.js +0 -2
- /package/dist/{visualization-MOYO6MDN.js.map → visualization-BIHTM2KJ.js.map} +0 -0
|
@@ -0,0 +1,4 @@
|
|
|
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 F=Object.defineProperty;var X=(t,e,r)=>e in t?F(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var _e=(t,e)=>{for(var r in e)F(t,r,{get:e[r],enumerable:!0})};var h=(t,e,r)=>X(t,typeof e!="symbol"?e+"":e,r);var l={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",NOT_FOUND:"NOT_FOUND",RATE_LIMIT:"RATE_LIMIT",INVALID_RESPONSE:"INVALID_RESPONSE",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",QUEUE_FULL:"QUEUE_FULL",QUEUE_TIMEOUT:"QUEUE_TIMEOUT",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},p= exports.d =class t extends Error{constructor(r,n=l.UNKNOWN_ERROR,o){super(r);h(this,"code");h(this,"statusCode");h(this,"context");h(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=_optionalChain([o, 'optionalAccess', _2 => _2.statusCode]),this.context=_optionalChain([o, 'optionalAccess', _3 => _3.context]),this.originalError=_optionalChain([o, 'optionalAccess', _4 => _4.originalError]),_optionalChain([o, 'optionalAccess', _5 => _5.originalError])&&(this.cause=o.originalError)}static missingValues(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,l.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,l.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};var O=class{debug(){}info(){}warn(){}error(){}},_=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},U=new O;function m(){return U}function k(t){if(t===null){U=new O;return}let e=["debug","info","warn","error"].filter(r=>typeof t[r]!="function");if(e.length>0)throw new p(`Logger is missing required method(s): ${e.join(", ")}. A logger must implement debug, info, warn and error.`,l.INVALID_CONFIG,{context:{missingMethods:e}});U=t}function ee(){k(new _)}function I(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function xe(t){let e=I();return e?e.from(t,"utf-8").toString("base64"):ne(new TextEncoder().encode(t))}var te=64,re="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Pe(t){if(!t)return null;let e=t.replace(/[\t\n\f\r ]/g,"");e.length%4===0&&(e=e.replace(/={1,2}$/,""));let r=e.length%4;if(r===1||e.length<te||!/^[A-Za-z0-9+/]*$/.test(e))return null;let n=re.indexOf(e.charAt(e.length-1));return r===2&&(n&15)!==0||r===3&&(n&3)!==0?null:r===0?e:e+"==".slice(0,4-r)}function x(t){let e=t.replace(/[\t\n\f\r ]/g,"");if(e.length%4===0&&(e=e.replace(/={1,2}$/,"")),e.length%4===1||!/^[A-Za-z0-9+/]*$/.test(e))throw new p("Invalid base64 input.",l.ENCODING_ERROR,{context:{inputLength:t.length}});let r=I();if(r)return new Uint8Array(r.from(e,"base64"));if(typeof globalThis.atob=="function"){let n=globalThis.atob(e),o=new Uint8Array(n.length);for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s)&255;return o}throw new p("Base64 decoding not supported in this environment.",l.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function P(t){let e=I();if(e)return e.byteLength(t,"utf-8");let r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?r+=1:o<2048?r+=2:o>=55296&&o<=56319&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(r+=4,n++):r+=3}return r}function ne(t){let e=I();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n=[];for(let o=0;o<t.length;o+=32766)n.push(globalThis.btoa(String.fromCharCode.apply(null,t.subarray(o,o+32766))));return n.join("")}throw new p("Base64 encoding not supported in this environment.",l.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}var B=new WeakMap;function N(t,e){typeof t!="object"||t===null||B.set(t,e)}function oe(t){if(!(typeof t!="object"||t===null))return B.get(t)}function se(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...s]=n.trim().split(";"),c=s.find(d=>d.trim().toLowerCase().startsWith("dur"));if(!c)continue;let i=Number(c.split("=")[1]);if(!Number.isFinite(i))continue;let a=o.trim().toLowerCase();(a==="decode"||a==="solve"||a==="encode")&&(e[a]=i,r=!0)}return r?e:null}var v={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},q=new Set([502,503,504]),ie=6e4,L=4096;function ae(t){return t?{attempts:_nullishCoalesce(t.attempts, () => (v.attempts)),baseDelayMs:_nullishCoalesce(t.baseDelayMs, () => (v.baseDelayMs)),maxDelayMs:_nullishCoalesce(t.maxDelayMs, () => (v.maxDelayMs)),retryOn429:_nullishCoalesce(t.retryOn429, () => (v.retryOn429))}:v}function ue(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e)&&e>=0)return e*1e3;let r=Date.parse(t);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return null}function C(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function le(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",s)]),r()},t),s=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",s,{once:!0})])})}function ce(t){return t.length<=L?t:`${t.slice(0,L)}\u2026 [truncated ${t.length-L} chars]`}function de(t,e,r,n,o,s,c,i){let{status:a,statusText:d}=t,u={};t.headers.forEach((Z,Q)=>{u[Q]=Z});let g=s.trim(),f=g?` \u2014 ${g.slice(0,200)}${g.length>200?"\u2026":""}`:"",E=_nullishCoalesce(i, () => (s)),T={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:E?ce(E):void 0,responseHeaders:u},b={401:{message:`HTTP ${a}: ${d}${f}`,code:l.AUTH_ERROR},403:{message:`HTTP ${a}: ${d}${f}`,code:l.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:l.NOT_FOUND},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:l.VALIDATION_ERROR},429:{message:`Rate limit exceeded${f}`,code:l.RATE_LIMIT},500:{message:`Server error: ${d}${f}`,code:l.COMPUTATION_ERROR},502:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR},503:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR},504:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR}}[a]||{message:`HTTP ${a}: ${d}${f}`,code:l.UNKNOWN_ERROR},M=_nullishCoalesce(fe(c), () => (b.code));throw new p(b.message,M,{statusCode:a,context:T})}function fe(t){if(t==="definition_not_cached")return l.DEFINITION_NOT_CACHED}function pe(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function me(t){try{let e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch (e2){return/(localhost|127\.0\.0\.1|\[::1\])/i.test(t)}}var W=new Set;function ge(t,e){let r={...e.headers,"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!W.has(e.serverUrl)&&!me(e.serverUrl)&&(W.add(e.serverUrl),m().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`)),r}function he(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function R(t,e){e&&m().debug(t)}function Re(t,e){let r=()=>{},n=typeof e=="number"&&e>0;if(!t&&!n)return{signal:void 0,cleanup:r};if(t&&!n)return{signal:t,cleanup:r};let o=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function";if(!t){if(o)return{signal:AbortSignal.timeout(e),cleanup:r};let u=new AbortController,g=setTimeout(()=>u.abort(),e);return{signal:u.signal,cleanup:()=>clearTimeout(g)}}let s=new AbortController,c,i;if(o)c=AbortSignal.timeout(e);else{let u=new AbortController;i=setTimeout(()=>u.abort(),e),c=u.signal}let a=[t,c],d=function(){s.abort(this.reason)};for(let u of a){if(u.aborted){s.abort(u.reason);break}u.addEventListener("abort",d,{once:!0})}return{signal:s.signal,cleanup:()=>{i!==void 0&&clearTimeout(i);for(let u of a)u.removeEventListener("abort",d)}}}function z(t,e,r,n){if(!r)return;let o=se(t.headers.get("Server-Timing"));if(o)try{r(o,e)}catch(s){n&&R(` onServerTiming callback threw: ${s}`,!0)}}async function ye(t,e,r,n,o,s,c,i){let a=Math.round(performance.now()-s);if(!t.ok){let d=await t.text(),u=d;c&&(R(`\u274C Request [${r}] failed with HTTP ${t.status} in ${a}ms`,!0),R(` URL: ${e}`,!0),R(` Status: ${t.status} ${t.statusText}`,!0),u&&R(` Response body: ${u.substring(0,500)}${u.length>500?"...":""}`,!0));let g;try{let f=JSON.parse(u);typeof _optionalChain([f, 'optionalAccess', _11 => _11.code])=="string"&&(g=f.code)}catch (e3){}if(t.status===500)try{let f=JSON.parse(u);if(_optionalChain([f, 'optionalAccess', _12 => _12.values])&&(f.errors||f.warnings))return N(f,u.length),c&&(R(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${a}ms`,!0),_optionalChain([f, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&R(` Errors: ${JSON.stringify(f.errors,null,2)}`,!0),_optionalChain([f, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&R(` Warnings: ${JSON.stringify(f.warnings,null,2)}`,!0)),z(t,r,i,c),f;let E=typeof _optionalChain([f, 'optionalAccess', _17 => _17.message])=="string"&&f.message||typeof _optionalChain([f, 'optionalAccess', _18 => _18.Message])=="string"&&f.Message||"",T=typeof _optionalChain([f, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&f.ExceptionType||"",S=_nullishCoalesce(_optionalChain([f, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([f, 'optionalAccess', _21 => _21.StackTrace]))),b=Array.isArray(S)?S.join(`
|
|
2
|
+
`):S||"";E?u=`${T?`${T}: `:""}${E}${b?`
|
|
3
|
+
${b}`:""}`:_optionalChain([f, 'optionalAccess', _22 => _22.error])&&(u=typeof f.error=="string"?f.error:JSON.stringify(f.error,null,2))}catch(f){c&&R(` Failed to parse error body as JSON: ${f}`,!0)}de(t,e,r,n,o,u,g,d)}R(`\u2705 Request [${r}] completed in ${a}ms`,c),z(t,r,i,c);try{let d=await t.text(),u=JSON.parse(d);return N(u,d.length),u}catch(d){let u=(_nullishCoalesce(t.headers.get("Content-Type"), () => (""))).toLowerCase();throw u!==""&&!u.includes("json")?new p(`Server returned a non-JSON response (Content-Type: ${u}) \u2014 check the server URL / proxy configuration`,l.INVALID_RESPONSE,{statusCode:t.status,context:{url:e,requestId:r,contentType:u},originalError:d instanceof Error?d:new Error(String(d))}):new p("Failed to parse JSON response",l.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:d instanceof Error?d:new Error(String(d))})}}async function we(t,e,r,n){let{signal:o,cleanup:s}=Re(t.config.signal,t.config.timeoutMs),c=performance.now();try{let i=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((q.has(i.status)||e.retryOn429&&i.status===429)&&r<n-1){let u=ue(i.headers.get("Retry-After")),g=u!==null?Math.min(u,Math.max(e.maxDelayMs,ie)):C(r,e);return await i.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:g,cause:new p(`HTTP ${i.status} ${i.statusText} (will retry)`,i.status===429?l.RATE_LIMIT:l.NETWORK_ERROR,{statusCode:i.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await ye(i,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,c,t.config.debug,t.config.onServerTiming)}}catch(i){if(i instanceof Error&&(i.name==="AbortError"||i.name==="TimeoutError")){if(_optionalChain([t, 'access', _23 => _23.config, 'access', _24 => _24.signal, 'optionalAccess', _25 => _25.aborted])===!0)return{ok:!1,retry:!1,cause:new p("Request aborted by caller",l.ABORTED,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:i})};let u=typeof t.config.timeoutMs=="number"&&t.config.timeoutMs>0?new p(`Request timed out after ${t.config.timeoutMs}ms`,l.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i}):new p(`Request aborted by the runtime (${i.name}): ${i.message}`,l.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:u}:{ok:!1,retry:!1,cause:u}}if(i instanceof TypeError){let a=typeof window<"u"&&typeof window.document<"u",d={serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},u=a?new p(`Request failed: ${i.message} \u2014 in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,l.CORS_ERROR,{context:d,originalError:i}):new p(`Network error: ${i.message}`,l.NETWORK_ERROR,{context:d,originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:u}:{ok:!1,retry:!1,cause:u}}if(i instanceof p){let a=i.statusCode;return(i.code===l.NETWORK_ERROR&&a!==void 0&&a>=200&&a<300||a!==void 0&&(q.has(a)||e.retryOn429&&a===429))&&r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:i}:{ok:!1,retry:!1,cause:i}}return{ok:!1,retry:!1,cause:new p(i instanceof Error?i.message:String(i),l.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:i instanceof Error?i:new Error(String(i))})}}finally{s()}}async function Ee(t,e,r){let n=he(),o=JSON.stringify(e),s=P(o),c=pe(t,r.serverUrl),i=ge(n,r),a=ae(r.retry),d=a.attempts+1;if(r.debug){let g=(s/1024).toFixed(2),f=s>1e5?"\u26A0\uFE0F":"\u{1F680}";R(`${f} Starting compute request [${n}]: ${t} (${g}KB)`,!0)}let u={endpoint:t,body:o,requestSize:s,fullUrl:c,requestId:n,headers:i,config:r};for(let g=0;;g++){let f=await we(u,a,g,d);if(f.ok)return f.value;if(!f.retry)throw f.cause;r.debug&&R(`\u{1F501} Request [${n}] retrying after ${f.delayMs}ms (attempt ${g+2}/${d}): ${f.cause.message}`,!0);try{await le(f.delayMs,r.signal)}catch (e4){throw new p("Request aborted by caller",l.ABORTED,{context:{endpoint:t,requestId:n,requestSize:s},originalError:f.cause})}}}var be="compute.rhino3d.com";function K(t){let e=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]), () => (""));if(!e)throw new p("serverUrl is required",l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!/^https?:\/\//i.test(e))throw new p(`Invalid serverUrl: "${e}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});let r;try{r=new URL(e)}catch(o){throw new p(`Invalid serverUrl: "${e}". Must be a valid URL. Received error: ${o instanceof Error?o.message:String(o)}`,l.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:o instanceof Error?o:void 0})}if(r.username!==""||r.password!=="")throw new p(`Invalid serverUrl: "${e}". Must not embed credentials (user:pass@host) \u2014 fetch rejects credentialed URLs at request time. Pass the API key separately.`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(e.includes("?")||e.includes("#"))throw new p(`Invalid serverUrl: "${e}". Must not contain a query string or fragment \u2014 endpoint paths are appended to this URL (e.g. "\${serverUrl}/version"), and a "?" or "#" suffix would corrupt every request path.`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(r.hostname.toLowerCase().replace(/\.+$/,"")===be)throw new p("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",l.INVALID_CONFIG,{context:{receivedServerUrl:t}});return e.replace(/\/+$/,"")}var y=class y{constructor(e,r){h(this,"serverUrl");h(this,"apiKey");h(this,"disposed",!1);h(this,"activeMonitors",new Set);h(this,"activeTimeouts",new Set);this.serverUrl=K(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=y.DEFAULT_TIMEOUT_MS){let o=new Headers(this.buildHeaders());r.headers&&new Headers(r.headers).forEach((i,a)=>{o.set(a,i)});let s={};o.forEach((i,a)=>{s[a]=i});let c={...r,headers:s};return n>0&&!c.signal&&(c.signal=AbortSignal.timeout(n)),fetch(e,c)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return m().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=r?y.LIFECYCLE_TIMEOUT_MS:y.DEFAULT_TIMEOUT_MS;try{let s=await this.fetchWithTimeout(n,{},o);if(!s.ok)return m().warn("[ComputeServerStats] Failed to fetch active children:",s.status),null;let c=(await s.text()).trim();return/^\d+$/.test(c)?parseInt(c,10):(m().warn("[ComputeServerStats] Invalid active children response:",c),null)}catch(s){return m().warn("[ComputeServerStats] Error fetching active children:",s),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e5){return{rhino:r,compute:"",git_sha:null}}}catch(e){return m().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return m().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch (e6){return null}}catch(r){return m().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return m().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch (e7){return null}}catch(e){return m().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return m().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let r=e*2,n=0;for(let o=0;o<r;o++){let s=await this.purgeCache();s!==null&&(n+=s)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let r=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(r);return isNaN(n.getTime())?null:n}catch(e){return m().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let r=parseFloat((await e.text()).trim());return isNaN(r)?null:r}catch(e){return m().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},y.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return m().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch (e8){return null}}catch(r){return m().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<y.MIN_MONITOR_INTERVAL_MS)throw new RangeError(`monitor() intervalMs must be a finite number >= ${y.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${y.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let n=!0,o=null;m().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let s=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let i=await this.getServerStats();if(!n||this.disposed)return;try{e(i)}catch(a){m().error("[ComputeServerStats] Monitor callback threw:",a)}}catch(i){!n||this.disposed?m().debug("[ComputeServerStats] Monitor poll cancelled during shutdown:",i):m().error("[ComputeServerStats] Failed to fetch stats during monitor:",i)}n&&!this.disposed&&(o=setTimeout(()=>{s()},r),this.activeTimeouts.add(o))}},c=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(c)};return this.activeMonitors.add(c),s(),c}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new p("ComputeServerStats has been disposed and cannot be used",l.INVALID_STATE,{context:{disposed:this.disposed}})}};h(y,"DEFAULT_TIMEOUT_MS",5e3),h(y,"LIFECYCLE_TIMEOUT_MS",6e4),h(y,"MIN_MONITOR_INTERVAL_MS",100);var A=y;function V(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s\-_]+(.)?/g,o=t.trim().replace(n,(s,c)=>c?c.toUpperCase():"");return o=o.replace(/^[A-Z]+(?=[A-Z][a-z]|[^A-Za-z]|$)/,s=>s.toLowerCase()),o.charAt(0).toLowerCase()+o.slice(1)}function ve(t){if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function D(t,e={}){if(!t||typeof t!="object")return t;if(Array.isArray(t))return e.deep?t.map(n=>D(n,e)):t;if(!ve(t))return t;let r={};for(let n of Object.keys(t)){let o=V(n,{preserveSpaces:e.preserveSpaces});Object.prototype.hasOwnProperty.call(r,o)&&m().warn(`camelcaseKeys: key '${n}' collides with an earlier key on '${o}' \u2014 the earlier value is overwritten (last key wins).`);let s=t[n];r[o]=e.deep?D(s,e):s}return r}function w(t,e){if(!t||typeof t!="object")return;let r=t;if(J(r,e))return r[e];let n=j(r).get(e.toLowerCase());return n===void 0?void 0:r[n]}var J=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function rt(t,e){if(!t||typeof t!="object")return!1;let r=t;return J(r,e)?!0:j(r).has(e.toLowerCase())}var H=new WeakMap;function j(t){let e=Object.keys(t),r=H.get(t);if(r&&r.keyCount===e.length)return r.map;let n=new Map;for(let o of e){let s=o.toLowerCase();n.has(s)||n.set(s,o)}return H.set(t,{keyCount:e.length,map:n}),n}var Te=async(t,e=null)=>{try{return await G(t,e)}catch(r){throw new p("Failed to extract files from compute response",l.INVALID_STATE,{context:{originalError:r instanceof Error?r.message:String(r)},originalError:r instanceof Error?r:void 0})}},Se= exports.v =async(t,e,r=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new p("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",l.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await G(t,r);await Ae(n,e)}catch(n){throw n instanceof p?n:new p("Failed to download files from compute response",l.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},$=t=>t.replace(/\\/g,"/").split("/").map(e=>e.trim()).filter(e=>e!==""&&e!=="."&&e!==".."&&!/^[a-zA-Z]:$/.test(e)).join("/"),Oe=t=>t===!0||typeof t=="string"&&t.trim().toLowerCase()==="true",Ie=t=>{let e=[];return t.forEach(r=>{let n=_nullishCoalesce(w(r,"fileName"), () => ("")),o=_nullishCoalesce(w(r,"fileType"), () => ("")),s=$(`${n}${o}`);if(s===""){m().warn(`Skipping file with unusable name "${n}${o}": no safe archive path remains after sanitization.`);return}let c=w(r,"subFolder"),i=c?$(c):"",a=i!==""?`${i}/${s}`:s,d=w(r,"data");if(typeof d!="string"||d===""){m().warn(`Skipping file "${a}": item carries no usable data.`);return}if(Oe(w(r,"isBase64Encoded")))try{e.push({fileName:s,content:x(d),path:a})}catch(u){m().warn(`Skipping file "${a}": base64 decode failed.`,u)}else e.push({fileName:s,content:d,path:a})}),e},Ne=3e4,Ce=async t=>(await Promise.all(t.map(async r=>{try{let n=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function"?AbortSignal.timeout(Ne):void 0,o=await fetch(r.filePath,{signal:n});if(!o.ok)return m().warn(`Failed to fetch additional file from URL: ${r.filePath}`),null;let s=await o.arrayBuffer(),c=$(r.fileName);if(c==="")return m().warn(`Skipping fetched file with unusable name: ${r.fileName}`),null;let i=r.subFolder?$(r.subFolder):"";return{fileName:c,content:new Uint8Array(s),path:i!==""?`${i}/${c}`:c}}catch(n){return m().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),G=async(t,e)=>{let r=Ie(t);if(e){let o=Array.isArray(e)?e:[e];r.push(...await Ce(o))}let n=new Set;return r.map(o=>{let s=Y(o.path,n);return n.add(s),s===o.path?o:(m().warn(`Duplicate archive path "${o.path}" \u2014 storing as "${s}".`),{...o,path:s,fileName:s.slice(s.lastIndexOf("/")+1)})})};async function Ae(t,e){let{zip:r,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),o={},s=new Set;t.forEach(a=>{let d=Y(a.path,s);s.add(d),d!==a.path&&m().warn(`Duplicate archive path "${a.path}" \u2014 storing as "${d}".`),o[d]=typeof a.content=="string"?n(a.content):a.content});let c=await new Promise((a,d)=>{r(o,{level:6},(u,g)=>u?d(u):a(g))}),i=new Blob([c],{type:"application/zip"});$e(i,`${e}.zip`)}function Y(t,e){if(!e.has(t))return t;let r=t.lastIndexOf("/"),n=t.lastIndexOf("."),o=n>r?n:t.length,s=t.slice(0,o),c=t.slice(o);for(let i=2;;i++){let a=`${s}-${i}${c}`;if(!e.has(a))return a}}function $e(t,e){if(typeof document>"u")throw new p("saveFile requires a browser environment with DOM API access.",l.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e4)}exports.a = _e; exports.b = h; exports.c = l; exports.d = p; exports.e = m; exports.f = k; exports.g = ee; exports.h = xe; exports.i = Pe; exports.j = x; exports.k = ne; exports.l = N; exports.m = oe; exports.n = Ee; exports.o = K; exports.p = A; exports.q = V; exports.r = D; exports.s = w; exports.t = rt; exports.u = Te; exports.v = Se;
|
|
4
|
+
//# sourceMappingURL=chunk-H3FZW6OX.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/chunk-H3FZW6OX.cjs","../src/core/errors.ts","../src/core/compute-fetch/compute-fetch.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,u8BAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CCA3N,IAAMA,CAAAA,CAAa,CACzB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,gBAAA,CAAkB,kBAAA,CAClB,iBAAA,CAAmB,mBAAA,CACnB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CAEZ,SAAA,CAAW,WAAA,CAEX,UAAA,CAAY,YAAA,CAOZ,gBAAA,CAAkB,kBAAA,CAClB,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,cAAA,CAAgB,gBAAA,CAChB,YAAA,CAAc,cAAA,CACd,iBAAA,CAAmB,mBAAA,CACnB,cAAA,CAAgB,gBAAA,CAEhB,iBAAA,CAAmB,mBAAA,CAEnB,UAAA,CAAY,YAAA,CAEZ,OAAA,CAAS,SAAA,CAOT,UAAA,CAAY,YAAA,CAMZ,aAAA,CAAe,eAAA,CAQf,qBAAA,CAAuB,uBACxB,CAAA,CASaC,CAAAA,aAAN,MAAMC,EAAAA,QAA0B,KAAM,CAM5C,WAAA,CACCC,CAAAA,CACAC,CAAAA,CAAkBJ,CAAAA,CAAW,aAAA,CAC7BK,CAAAA,CACC,CACD,KAAA,CAAMF,CAAO,CAAA,CAVdG,CAAAA,CAAA,IAAA,CAAgB,MAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,YAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,SAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,eAAA,CAAA,CAQf,IAAA,CAAK,IAAA,CAAO,mBAAA,CACZ,IAAA,CAAK,IAAA,CAAOF,CAAAA,CACZ,IAAA,CAAK,UAAA,iBAAaC,CAAAA,6BAAS,YAAA,CAC3B,IAAA,CAAK,OAAA,iBAAUA,CAAAA,6BAAS,SAAA,CACxB,IAAA,CAAK,aAAA,iBAAgBA,CAAAA,6BAAS,eAAA,iBAC1BA,CAAAA,6BAAS,eAAA,EAAA,CACX,IAAA,CAA6B,KAAA,CAAQA,CAAAA,CAAQ,aAAA,CAEhD,CAKA,OAAO,aAAA,CACNE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAO,IAAIP,CAAAA,CACV,CAAA,OAAA,EAAUK,CAAS,CAAA,uBAAA,EAA0BC,CAAAA,CAAe,CAAA,WAAA,EAAcA,CAAY,CAAA,CAAA,CAAA,CAAM,EAAE,CAAA,CAAA;AC4VzC;AA2IU","file":"/home/runner/work/selva/selva/packages/compute/dist/chunk-H3FZW6OX.cjs","sourcesContent":[null,"export const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\t/** HTTP 404 — the endpoint path does not exist on the server (usually a typo'd route or wrong server). Never retried. */\n\tNOT_FOUND: 'NOT_FOUND',\n\t/** HTTP 429 — the server is rate-limiting requests. Retried by default (honors `Retry-After`); see `RetryPolicy.retryOn429`. */\n\tRATE_LIMIT: 'RATE_LIMIT',\n\t/**\n\t * The server answered 2xx but the body is deterministically not JSON (the\n\t * response declared a non-JSON `Content-Type`, e.g. an HTML captive-portal or\n\t * proxy login page, or a misconfigured endpoint). Never retried — refetching\n\t * returns the same page.\n\t */\n\tINVALID_RESPONSE: 'INVALID_RESPONSE',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */\n\tMALFORMED_DEFAULT: 'MALFORMED_DEFAULT',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED',\n\t/**\n\t * Scheduler backpressure: the queue was already at `maxQueueDepth` when this\n\t * call arrived, so it was shed immediately rather than queued. Retryable — the\n\t * caller (or an HTTP layer, as 503 + Retry-After) should back off and retry.\n\t * The error `context` carries `{ queueDepth, maxQueueDepth }`.\n\t */\n\tQUEUE_FULL: 'QUEUE_FULL',\n\t/**\n\t * Scheduler backpressure: this call sat queued longer than `queueWaitMs`\n\t * without starting, so it was shed before wasting compute on a stale request.\n\t * Retryable. The error `context` carries `{ waitedMs, queueWaitMs }`.\n\t */\n\tQUEUE_TIMEOUT: 'QUEUE_TIMEOUT',\n\t/**\n\t * A solve referenced a definition by `pointer` (server-side cache key), but the\n\t * server no longer holds that definition (evicted / GC'd / a different child in\n\t * the pool / server restarted). The caller should retry with the full\n\t * definition. Surfaced when the server tags its error body with\n\t * `code: \"definition_not_cached\"`, so it survives production message-scrubbing.\n\t */\n\tDEFINITION_NOT_CACHED: 'DEFINITION_NOT_CACHED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: ErrorCode;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: ErrorCode = ErrorCodes.UNKNOWN_ERROR,\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","import { RhinoComputeError, ErrorCodes, type ErrorCode } from '../errors';\nimport { getLogger } from '../utils/logger';\nimport { utf8ByteLength } from '../utils/encoding';\nimport { setResponseWireSize } from './wire-size';\n\nimport type { ComputeConfig, RetryPolicy, ServerTiming } from '../types';\n\n/**\n * Parse a `Server-Timing` header value into typed durations (ms).\n *\n * Header grammar (RFC 9110 §10.1.10), as emitted by the solve endpoint:\n * `decode;dur=3, solve;dur=120, encode;dur=8`\n *\n * Returns null when the header is absent or carries no recognizable metric, so\n * the caller can skip the callback entirely.\n *\n * @internal exported for tests\n */\nexport function parseServerTiming(headerValue: string | null): ServerTiming | null {\n\tif (!headerValue) return null;\n\tconst timing: ServerTiming = { raw: headerValue };\n\tlet sawMetric = false;\n\tfor (const part of headerValue.split(',')) {\n\t\tconst [name, ...params] = part.trim().split(';');\n\t\tconst durParam = params.find((p) => p.trim().toLowerCase().startsWith('dur'));\n\t\tif (!durParam) continue;\n\t\tconst dur = Number(durParam.split('=')[1]);\n\t\tif (!Number.isFinite(dur)) continue;\n\t\tconst key = name.trim().toLowerCase();\n\t\tif (key === 'decode' || key === 'solve' || key === 'encode') {\n\t\t\ttiming[key] = dur;\n\t\t\tsawMetric = true;\n\t\t}\n\t}\n\treturn sawMetric ? timing : null;\n}\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\n/**\n * Absolute ceiling for a server-supplied `Retry-After` wait. The server's\n * stated window wins over `retryPolicy.maxDelayMs` (retrying earlier all but\n * guarantees another 429), but a bad/hostile header must not park the client\n * for minutes — anything above this cap is clamped.\n */\nconst RETRY_AFTER_CAP_MS = 60_000;\n\n/** Upper bound for the raw server body stored on error `context.responseBody`. */\nconst MAX_CONTEXT_BODY_CHARS = 4096;\n\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n/** Truncate a server body for storage on error context — bounded, with an honest marker. */\nfunction truncateBody(body: string): string {\n\tif (body.length <= MAX_CONTEXT_BODY_CHARS) return body;\n\treturn `${body.slice(0, MAX_CONTEXT_BODY_CHARS)}… [truncated ${body.length - MAX_CONTEXT_BODY_CHARS} chars]`;\n}\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string,\n\tserverCode?: string,\n\trawBody?: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed ? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` : '';\n\n\t// context.responseBody holds the RAW server body (what actually came over the\n\t// wire), bounded to MAX_CONTEXT_BODY_CHARS so a huge body isn't pinned for the\n\t// error's lifetime. `errorBody` may have been rewritten into a synthesized\n\t// message (500 exception shape) — that goes in the message, not the context.\n\tconst storedBody = rawBody ?? errorBody;\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: storedBody ? truncateBody(storedBody) : undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: ErrorCode }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NOT_FOUND },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.RATE_LIMIT },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t503: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t504: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t}\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\t// A machine code in the server's error body (e.g. \"definition_not_cached\")\n\t// outranks the status-based mapping: it's stable across the server's\n\t// production message-scrubbing, where the human message is replaced with a\n\t// generic string. Keep the status-derived message for context.\n\tconst code = mapServerErrorCode(serverCode) ?? error.code;\n\n\tthrow new RhinoComputeError(error.message, code, { statusCode: status, context });\n}\n\n/**\n * Map a server-supplied error code (from the JSON error body's `code` field) to\n * one of our {@link ErrorCodes}. Returns `undefined` for an absent or unknown\n * code so the caller falls back to its status-based mapping.\n */\nfunction mapServerErrorCode(serverCode?: string): ErrorCode | undefined {\n\tswitch (serverCode) {\n\t\tcase 'definition_not_cached':\n\t\t\treturn ErrorCodes.DEFINITION_NOT_CACHED;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\t// `hostname` (not `host`) strips the port; IPv6 hostnames keep their\n\t\t// brackets, so `http://[::1]:6500` yields `[::1]`.\n\t\tconst hostname = new URL(serverUrl).hostname.toLowerCase();\n\t\treturn hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1|\\[::1\\])/i.test(serverUrl);\n\t}\n}\n\n/** Server URLs already warned about missing auth — warn once per server, not per request. */\nconst warnedNoAuth = new Set<string>();\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t// Caller headers first so the transport's own headers below OVERWRITE them —\n\t\t// a caller can never clobber the request id, content type, or auth.\n\t\t...config.headers,\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (\n\t\t!config.apiKey &&\n\t\t!config.authToken &&\n\t\t!warnedNoAuth.has(config.serverUrl) &&\n\t\t!isLocalhost(config.serverUrl)\n\t) {\n\t\twarnedNoAuth.add(config.serverUrl);\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst noCleanup = () => {};\n\tconst wantsTimeout = typeof timeoutMs === 'number' && timeoutMs > 0;\n\n\tif (!callerSignal && !wantsTimeout) return { signal: undefined, cleanup: noCleanup };\n\tif (callerSignal && !wantsTimeout) return { signal: callerSignal, cleanup: noCleanup };\n\n\tconst supportsTimeout =\n\t\ttypeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function';\n\n\t// Timeout only: nothing is registered on a caller signal, so there is nothing to clean up on\n\t// the modern path (the pending timer is small and self-expires at timeoutMs).\n\tif (!callerSignal) {\n\t\tif (supportsTimeout) return { signal: AbortSignal.timeout(timeoutMs!), cleanup: noCleanup };\n\t\tconst ctrl = new AbortController();\n\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\treturn { signal: ctrl.signal, cleanup: () => clearTimeout(id) };\n\t}\n\n\t// Caller signal + timeout: composed manually rather than with AbortSignal.any — `any` offers no\n\t// way to unregister its dependent link on the caller's signal, so an app reusing one long-lived\n\t// signal across many solves accumulates a registration per attempt for the full timeoutMs after\n\t// each response (and forever on Node versions with the known AbortSignal.any leak).\n\tconst ctrl = new AbortController();\n\n\tlet timeoutSignal: AbortSignal;\n\tlet timerId: ReturnType<typeof setTimeout> | undefined;\n\tif (supportsTimeout) {\n\t\ttimeoutSignal = AbortSignal.timeout(timeoutMs!);\n\t} else {\n\t\tconst timeoutCtrl = new AbortController();\n\t\ttimerId = setTimeout(() => timeoutCtrl.abort(), timeoutMs);\n\t\ttimeoutSignal = timeoutCtrl.signal;\n\t}\n\n\tconst sources = [callerSignal, timeoutSignal];\n\t// Forward the source's reason so fetch rejects with the right error name\n\t// ('TimeoutError' vs 'AbortError'), matching AbortSignal.any semantics.\n\tconst onAbort = function (this: AbortSignal) {\n\t\tctrl.abort(this.reason);\n\t};\n\n\tfor (const s of sources) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort(s.reason);\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\n\treturn {\n\t\tsignal: ctrl.signal,\n\t\tcleanup: () => {\n\t\t\tif (timerId !== undefined) clearTimeout(timerId);\n\t\t\tfor (const s of sources) s.removeEventListener('abort', onAbort);\n\t\t}\n\t};\n}\n\n/**\n * Surface the server's per-request timing breakdown (if it sent one and a\n * caller is listening). Best-effort: a throwing callback must not fail the\n * request. Called on the success path AND the 500-with-values partial-success\n * path — solves that completed with Grasshopper errors carry real timings too.\n */\nfunction fireServerTiming(\n\tresponse: Response,\n\trequestId: string,\n\tonServerTiming: ((timing: ServerTiming, requestId: string) => void) | undefined,\n\tdebug?: boolean\n): void {\n\tif (!onServerTiming) return;\n\tconst timing = parseServerTiming(response.headers.get('Server-Timing'));\n\tif (!timing) return;\n\ttry {\n\t\tonServerTiming(timing, requestId);\n\t} catch (err) {\n\t\tif (debug) log(` onServerTiming callback threw: ${err}`, true);\n\t}\n}\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean,\n\tonServerTiming?: (timing: ServerTiming, requestId: string) => void\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse. `rawBody` stays what came over the wire (stored\n\t\t// on error context); `errorBody` may be rewritten into a friendlier message.\n\t\tconst rawBody = await response.text();\n\t\tlet errorBody = rawBody;\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// A machine-readable code the server may tag onto its error body (e.g.\n\t\t// \"definition_not_cached\"). Unlike the human `message`, it isn't scrubbed in\n\t\t// the server's production (non-debug) mode, so it's the reliable signal for\n\t\t// classifying the error (see throwHttpError → mapServerErrorCode). It can\n\t\t// ride any error status, not just 500, so read it here.\n\t\tlet serverCode: string | undefined;\n\n\t\ttry {\n\t\t\tconst parsedForCode = JSON.parse(errorBody);\n\t\t\tif (typeof parsedForCode?.code === 'string') serverCode = parsedForCode.code;\n\t\t} catch {\n\t\t\t// Non-JSON body — nothing to extract.\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tsetResponseWireSize(parsed, errorBody.length);\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfireServerTiming(response, requestId, onServerTiming, debug);\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// Raw server-side exception. The Compute8 server's exception handler\n\t\t\t\t// (compute.geometry Startup.cs) emits:\n\t\t\t\t// { error: \"Internal Server Error\", message: \"<category>: <detail>\",\n\t\t\t\t// stackTrace?: string[] } // stackTrace only when Config.Debug\n\t\t\t\t// The actionable part is `message` — surface it, with the optional\n\t\t\t\t// stack appended for debugging. We prefer `message`/`error` (current\n\t\t\t\t// server) and keep `Message`/`ExceptionType`/`StackTrace` (old\n\t\t\t\t// PascalCase .NET shape) as a back-compat fallback so an older server\n\t\t\t\t// still produces a useful message.\n\t\t\t\tconst serverMessage =\n\t\t\t\t\t(typeof parsed?.message === 'string' && parsed.message) ||\n\t\t\t\t\t(typeof parsed?.Message === 'string' && parsed.Message) ||\n\t\t\t\t\t'';\n\t\t\t\tconst exceptionType =\n\t\t\t\t\t(typeof parsed?.ExceptionType === 'string' && parsed.ExceptionType) || '';\n\t\t\t\tconst stack = parsed?.stackTrace ?? parsed?.StackTrace;\n\t\t\t\tconst stackStr = Array.isArray(stack) ? stack.join('\\n') : stack || '';\n\n\t\t\t\tif (serverMessage) {\n\t\t\t\t\t// Don't repeat the generic \"Internal Server Error\" label when the\n\t\t\t\t\t// message already carries the real detail.\n\t\t\t\t\tconst prefix = exceptionType ? `${exceptionType}: ` : '';\n\t\t\t\t\terrorBody = `${prefix}${serverMessage}${stackStr ? `\\n${stackStr}` : ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(\n\t\t\tresponse,\n\t\t\tfullUrl,\n\t\t\trequestId,\n\t\t\trequestSize,\n\t\t\tserverUrl,\n\t\t\terrorBody,\n\t\t\tserverCode,\n\t\t\trawBody\n\t\t);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\tfireServerTiming(response, requestId, onServerTiming, debug);\n\n\ttry {\n\t\t// text-then-parse (what `response.json()` does internally) so the body's\n\t\t// wire size rides along with the parsed object — downstream byte-budgeted\n\t\t// caches read it instead of re-serializing a potentially huge tree.\n\t\tconst rawBody = await response.text();\n\t\tconst parsed = JSON.parse(rawBody);\n\t\tsetResponseWireSize(parsed, rawBody.length);\n\t\treturn parsed;\n\t} catch (error) {\n\t\t// Classify by the declared Content-Type (issue 87). A 2xx that DECLARES a\n\t\t// non-JSON body (HTML from a captive portal, a reverse-proxy login page, a\n\t\t// misconfigured endpoint) is deterministic — refetching returns the same\n\t\t// page — so fail immediately with INVALID_RESPONSE (never retried). A body\n\t\t// that fails to parse under a JSON (or absent) Content-Type means the\n\t\t// stream was likely cut mid-body — as transient as any network error — and\n\t\t// keeps the retryable NETWORK_ERROR classification.\n\t\tconst contentType = (response.headers.get('Content-Type') ?? '').toLowerCase();\n\t\tconst declaredNonJson = contentType !== '' && !contentType.includes('json');\n\t\tif (declaredNonJson) {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t`Server returned a non-JSON response (Content-Type: ${contentType}) — check the server URL / proxy configuration`,\n\t\t\t\tErrorCodes.INVALID_RESPONSE,\n\t\t\t\t{\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\tcontext: { url: fullUrl, requestId, contentType },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\t// The server's stated Retry-After window wins over maxDelayMs — retrying\n\t\t\t// before it all but guarantees another 429 and burns an attempt. It is\n\t\t\t// only clamped by the absolute RETRY_AFTER_CAP_MS safety cap (or by a\n\t\t\t// caller-configured maxDelayMs that is even larger), so a bad header\n\t\t\t// can't force a pathological sleep. backoffDelay already clamps itself.\n\t\t\tconst delayMs =\n\t\t\t\tretryAfterMs !== null\n\t\t\t\t\t? Math.min(retryAfterMs, Math.max(retryPolicy.maxDelayMs, RETRY_AFTER_CAP_MS))\n\t\t\t\t\t: backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tresponse.status === 429 ? ErrorCodes.RATE_LIMIT : ErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug,\n\t\t\tctx.config.onServerTiming\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t},\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Only claim a timeout when we actually armed one (issue 88). Without a\n\t\t\t// configured timeoutMs, a non-caller abort came from the runtime itself\n\t\t\t// (e.g. an undici socket teardown) — as transient as any network drop, so\n\t\t\t// it stays retryable, but it is NOT a timeout: report it truthfully\n\t\t\t// instead of \"timed out after undefinedms\" / TIMEOUT_ERROR.\n\t\t\tconst timeoutArmed = typeof ctx.config.timeoutMs === 'number' && ctx.config.timeoutMs > 0;\n\t\t\tconst fatal = timeoutArmed\n\t\t\t\t? new RhinoComputeError(\n\t\t\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t: new RhinoComputeError(\n\t\t\t\t\t\t`Request aborted by the runtime (${error.name}): ${error.message}`,\n\t\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable (issue 90).\n\t\t//\n\t\t// Duplicate-POST caveat: a connection reset can strike after the body was\n\t\t// sent, in which case the server may already have executed this POST and a\n\t\t// retry runs it again. Compute solves are deterministic, so a duplicate is\n\t\t// wasted work rather than corruption; RetryPolicy documents the risk and\n\t\t// defaults to attempts: 0.\n\t\t//\n\t\t// In a real browser, a fetch TypeError with no response is most often a\n\t\t// CORS misconfiguration (the browser hides the details by design), so it is\n\t\t// classified CORS_ERROR there to stop callers chasing phantom network\n\t\t// failures. Retries are kept in both environments: the same TypeError is\n\t\t// also what a flaky/offline network produces, and there is no way to tell\n\t\t// them apart.\n\t\tif (error instanceof TypeError) {\n\t\t\tconst inBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\t\t\tconst errorContext = {\n\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\turl: ctx.fullUrl,\n\t\t\t\trequestId: ctx.requestId,\n\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\trequestSize: ctx.requestSize\n\t\t\t};\n\t\t\tconst fatal = inBrowser\n\t\t\t\t? new RhinoComputeError(\n\t\t\t\t\t\t`Request failed: ${error.message} — in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,\n\t\t\t\t\t\tErrorCodes.CORS_ERROR,\n\t\t\t\t\t\t{ context: errorContext, originalError: error }\n\t\t\t\t\t)\n\t\t\t\t: new RhinoComputeError(`Network error: ${error.message}`, ErrorCodes.NETWORK_ERROR, {\n\t\t\t\t\t\tcontext: errorContext,\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t});\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\t// A 2xx whose body failed to parse UNDER A JSON CONTENT-TYPE\n\t\t\t// (NETWORK_ERROR from handleResponse) means the stream was cut mid-body —\n\t\t\t// as transient as any network error. A 2xx that declared a non-JSON body\n\t\t\t// arrives here as INVALID_RESPONSE (deterministic — captive portal /\n\t\t\t// login page) and deliberately does NOT match: it is never retried.\n\t\t\tconst isTruncatedSuccess =\n\t\t\t\terror.code === ErrorCodes.NETWORK_ERROR &&\n\t\t\t\tstatus !== undefined &&\n\t\t\t\tstatus >= 200 &&\n\t\t\t\tstatus < 300;\n\t\t\tconst retryable =\n\t\t\t\tisTruncatedSuccess ||\n\t\t\t\t(status !== undefined &&\n\t\t\t\t\t(RETRYABLE_STATUS.has(status) || (retryPolicy.retryOn429 && status === 429)));\n\t\t\tif (retryable && attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: error };\n\t\t}\n\n\t\t// Unknown — wrap and don't retry\n\t\treturn {\n\t\t\tok: false,\n\t\t\tretry: false,\n\t\t\tcause: new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.UNKNOWN_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: { endpoint: ctx.endpoint, requestId: ctx.requestId },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t)\n\t\t};\n\t} finally {\n\t\tcleanup();\n\t}\n}\n\n/**\n * Generic Rhino Compute fetch function.\n * Sends a POST request to any Compute endpoint with pre-prepared arguments.\n *\n * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs.\n *\n * The transport is response-type-agnostic: it does not know which response a\n * given endpoint returns. Callers supply the response type via `R` (defaulting\n * to `unknown`, which forces an explicit narrowing before use).\n *\n * Timeout semantics: `config.timeoutMs` is a PER-ATTEMPT timeout, re-armed for\n * every retry. With `retry: { attempts: N }` the worst-case wall clock is\n * `(N + 1) × timeoutMs` plus backoff sleeps (and a server `Retry-After` can\n * stretch a single sleep up to 60s). For a hard overall deadline, pass\n * `config.signal` (e.g. `AbortSignal.timeout(totalMs)`) — a caller abort wins\n * immediately, including during backoff.\n *\n * Retry caveats: requests are POSTs, so a retry after a mid-flight connection\n * loss may re-execute a request the server already ran (see {@link RetryPolicy}).\n * A 2xx response that declares a non-JSON `Content-Type` (captive portal,\n * proxy login page) fails immediately with `INVALID_RESPONSE` and is never\n * retried; a body that fails to parse under a JSON content-type is treated as\n * a truncated stream and is retried.\n *\n * @typeParam R - The expected response shape. The caller names it at the call site.\n * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh').\n * @param args - Pre-prepared arguments for the request body.\n * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal).\n * @returns The parsed JSON response from the server, typed as `R`.\n *\n * @example\n * // Basic usage for the Grasshopper endpoint:\n * const response = await fetchRhinoCompute(\n * 'grasshopper',\n * { ... },\n * {\n * serverUrl: 'https://my-server.com',\n * debug: true,\n * timeoutMs: 30_000,\n * retry: { attempts: 2 },\n * signal: controller.signal,\n * }\n * );\n */\nexport async function fetchRhinoCompute<R = unknown>(\n\tendpoint: string,\n\targs: Record<string, any>,\n\tconfig: ComputeConfig\n): Promise<R> {\n\tconst requestId = generateRequestId();\n\tconst body = JSON.stringify(args);\n\t// Wire size in UTF-8 bytes — `body.length` counts UTF-16 code units and\n\t// undercounts non-ASCII payloads (matters for the 413 message and size logs).\n\tconst requestSize = utf8ByteLength(body);\n\tconst fullUrl = buildUrl(endpoint, config.serverUrl);\n\tconst headers = buildHeaders(requestId, config);\n\tconst retryPolicy = resolveRetryPolicy(config.retry);\n\tconst totalAttempts = retryPolicy.attempts + 1;\n\n\tif (config.debug) {\n\t\tconst sizeKb = (requestSize / 1024).toFixed(2);\n\t\tconst emoji = requestSize > 100000 ? '⚠️' : '🚀';\n\t\tlog(`${emoji} Starting compute request [${requestId}]: ${endpoint} (${sizeKb}KB)`, true);\n\t}\n\n\tconst ctx: AttemptContext = {\n\t\tendpoint,\n\t\tbody,\n\t\trequestSize,\n\t\tfullUrl,\n\t\trequestId,\n\t\theaders,\n\t\tconfig\n\t};\n\n\t// Every iteration ends in `return` or `throw` (issue 105): attemptFetch never\n\t// asks to retry on the final attempt (all its retry branches are gated on\n\t// `attempt < totalAttempts - 1`), so the exhausted-retries error is the final\n\t// attempt's own `result.cause` — there is no post-loop fallback to reach.\n\tfor (let attempt = 0; ; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as R;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: result.cause\n\t\t\t});\n\t\t}\n\t}\n}\n"]}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import{a as Dn,b as re,c as ye,d as be,e as F,j as ft}from"./chunk-Y3M7P3BW.js";var Ln={};Dn(Ln,{CONCRETE_MATERIAL:()=>ht,EMISSIVE_MATERIAL:()=>pt,GLASS_MATERIAL:()=>yt,METAL_MATERIAL:()=>Et,PLASTIC_MATERIAL:()=>gt,RUBBER_MATERIAL:()=>bt,SHARED_MATERIALS:()=>We,WOOD_MATERIAL:()=>Tt});import*as z from"three";var pt=new z.MeshPhysicalMaterial({color:0,emissive:new z.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:z.FrontSide,dithering:!0}),Et=new z.MeshPhysicalMaterial({color:new z.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,polygonOffsetFactor:1,polygonOffsetUnits:1,side:z.FrontSide,dithering:!0}),ht=new z.MeshPhysicalMaterial({color:new z.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:0,depthTest:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:z.FrontSide,dithering:!0}),gt=new z.MeshPhysicalMaterial({color:new z.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:z.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),yt=new z.MeshPhysicalMaterial({color:new z.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,depthWrite:!1,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:z.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),bt=new z.MeshPhysicalMaterial({color:new z.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:z.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Tt=new z.MeshPhysicalMaterial({color:new z.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:z.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),We=new Set([pt,Et,ht,gt,yt,bt,Tt]);import*as q from"three";var ae={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 ba(e,n,t,r,a){if(Fn(e),n.length===0)return;n.forEach(u=>{e.add(u)});let o=$e(n),i=o.getCenter(new q.Vector3),l=o.getSize(new q.Vector3),s=Math.max(l.x,l.y,l.z);if(s/Math.min(l.x||1,l.y||1,l.z||1)>ae.SCALE_RATIO_THRESHOLD||s>ae.HUGE_THRESHOLD?(t.near=s*ae.NEAR_PLANE_FACTOR.TINY,t.far=s*ae.FAR_PLANE_FACTOR.HUGE):s>ae.LARGE_THRESHOLD?(t.near=s*ae.NEAR_PLANE_FACTOR.SMALL,t.far=s*ae.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,s*ae.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,s*ae.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),!a){let u=s*ae.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+u*.8,i.y+u,i.z+u*1.2),r.target.copy(i),r.update()}}function Rt(e){if(!e||typeof e!="string")return F().warn(`Invalid color input: ${e}, using white`),new q.Color(16777215);let n=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(n))try{let r=n.startsWith("#")?n:`#${n}`;return new q.Color(r)}catch{return F().warn(`Invalid hex color: ${e}, using white`),new q.Color(16777215)}if(n.includes(",")){let r=n.split(",").map(a=>parseInt(a.trim(),10));if(r.length===3&&r.every(a=>!isNaN(a)&&a>=0&&a<=255))return new q.Color(r[0]/255,r[1]/255,r[2]/255)}let t=n.toLowerCase();return t in q.Color.NAMES?new q.Color(q.Color.NAMES[t]):(F().warn(`Invalid color string: ${e}, using white`),new q.Color(16777215))}function xt(e,n,t="z"){e.forEach(r=>{r.position[t]-=n})}function $e(e){let n=new q.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let r=new q.Box3().setFromObject(t);n.union(r)}),n}var On=new Set(["grid","floor","label-layer","measure"]);function In(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&On.has(n.userData.id))return!0;n=n.parent}return!1}function le(e){e.updateMatrixWorld(!0);let n=new q.Box3;return e.traverse(t=>{let r=t;t.visible&&!In(t)&&r.geometry&&n.expandByObject(t)}),n}var Pn=new Set(["floor","grid","label-layer"]),Se="selvaGeometryCache";function Fn(e){[...e.children].forEach(t=>{Pn.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(r=>{let a=r;if(!a.geometry&&!a.material)return;a.geometry?.userData?.[Se]||a.geometry?.dispose();let o=a.material;if(!o)return;(Array.isArray(o)?o:[o]).forEach(l=>{if(!We.has(l)){for(let s of Object.values(l))s instanceof q.Texture&&s.dispose();l.dispose()}})}),t.removeFromParent())})}import*as Y from"three";function Bn(e){let n=e.clone().normalize(),t=new Y.Vector3(0,0,1),r=new Y.Vector3(0,1,0),a=Math.abs(n.dot(t))>.9?r:t,o=new Y.Vector3().crossVectors(n,a).normalize(),i=new Y.Vector3().crossVectors(o,n).normalize();return{top:n.clone(),bottom:n.clone().negate(),front:i.clone(),back:i.clone().negate(),right:o.clone(),left:o.clone().negate(),iso:i.clone().multiplyScalar(1.2).add(o.clone()).add(n.clone()).normalize()}}function vt(e){let{scene:n,perspective:t,controls:r,onActiveCameraChange:a}=e,o=(e.up??t.up).clone().normalize(),i=Bn(o),l=new Y.OrthographicCamera(-1,1,1,-1,t.near,t.far);l.up.copy(o);let s="perspective",c=t.aspect,u=()=>s==="perspective"?t:l,d=null,E=()=>{d?.cancel(),d=null},T=()=>{let h=(s==="orthographic"?l:t).position.distanceTo(r.target)*Math.tan(t.fov*Math.PI/360),b=h*c;l.left=-b,l.right=b,l.top=h,l.bottom=-h,l.near=t.near,l.far=t.far,l.updateProjectionMatrix()},v=p=>{if(p!==s){if(E(),p==="orthographic")l.position.copy(t.position),l.up.copy(t.up),l.lookAt(r.target),l.zoom=1,T();else{let h=(l.top-l.bottom)/(2*l.zoom)/Math.tan(t.fov*Math.PI/360),b=l.position.clone().sub(r.target);b.lengthSq()<1e-12&&b.copy(o),b.normalize(),t.position.copy(r.target).add(b.multiplyScalar(h))}s=p,r.object=u(),r.update(),a(u())}},y=(p,f,h,b)=>{let C=t.fov*(Math.PI/180),H=f/(2*Math.tan(C/2))*1.5,L=kn(h,o),P=p.clone().add(L.clone().multiplyScalar(H)),k=u();s==="orthographic"&&(l.zoom=1),E(),b?d=_n(k,r,P,p,()=>{s==="orthographic"&&T()}):(k.position.copy(P),r.target.copy(p),s==="orthographic"&&T(),r.update())},m=(p,f=!0)=>{let h=le(n),b=h.isEmpty()?r.target.clone():h.getCenter(new Y.Vector3),C=h.isEmpty()?new Y.Vector3(1,1,1):h.getSize(new Y.Vector3),H=Math.max(C.x,C.y,C.z)||1;y(b,H,p,f)};return{getActiveCamera:u,getProjection:()=>s,setProjection:v,toggleProjection:()=>(v(s==="perspective"?"orthographic":"perspective"),s),setView:(p,f=!0)=>{m(i[p],f)},setViewDirection:m,frameBounds:(p,f=!0)=>{if(p.isEmpty())return;let h=p.getCenter(new Y.Vector3),b=p.getSize(new Y.Vector3),C=Math.max(b.x,b.y,b.z)||1,H=u().position.clone().sub(r.target);H.lengthSq()<1e-12&&H.copy(i.iso),y(h,C,H.normalize(),f)},setRotateEnabled:p=>{r.enableRotate=p},isRotateEnabled:()=>r.enableRotate,updateAspect:(p,f)=>{c=f===0?c:p/f,s==="orthographic"&&T()},dispose:E}}function kn(e,n){let t=n.clone().normalize(),r=e.clone().normalize();if(Math.abs(r.dot(t))<.9999)return e;let a=Math.abs(t.dot(new Y.Vector3(0,0,1)))>.9?new Y.Vector3(0,1,0):new Y.Vector3(0,0,1),o=new Y.Vector3().crossVectors(t,a).normalize(),i=.5*Math.PI/180;return r.multiplyScalar(Math.cos(i)).add(o.multiplyScalar(Math.sin(i))).normalize()}var Un=e=>1-Math.pow(1-e,3);function _n(e,n,t,r,a,o=250){let i=e.position.clone(),l=n.target.clone(),s=performance.now(),c=null,u=()=>{c=null;let d=Un(Math.min((performance.now()-s)/o,1));e.position.lerpVectors(i,t,d),n.target.lerpVectors(l,r,d),a(),n.update(),d<1&&(c=requestAnimationFrame(u))};return c=requestAnimationFrame(u),{cancel:()=>{c!==null&&(cancelAnimationFrame(c),c=null)}}}import*as W from"three";function Vn(e){if(!(e>0)||!Number.isFinite(e))return 1;let n=Math.floor(Math.log10(e)),t=Math.pow(10,n),r=e/t;return(r>=5?5:r>=2?2:1)*t}var zn=`
|
|
2
|
+
varying vec3 vWorldPos;
|
|
3
|
+
void main() {
|
|
4
|
+
vec4 world = modelMatrix * vec4(position, 1.0);
|
|
5
|
+
vWorldPos = world.xyz;
|
|
6
|
+
gl_Position = projectionMatrix * viewMatrix * world;
|
|
7
|
+
}
|
|
8
|
+
`,Gn=`
|
|
9
|
+
precision highp float;
|
|
10
|
+
varying vec3 vWorldPos;
|
|
11
|
+
|
|
12
|
+
uniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes
|
|
13
|
+
uniform float uCell;
|
|
14
|
+
uniform float uMajor;
|
|
15
|
+
uniform vec3 uCellColor;
|
|
16
|
+
uniform vec3 uMajorColor;
|
|
17
|
+
uniform vec3 uCenter; // fade center (camera position), projected onto plane
|
|
18
|
+
uniform float uFade;
|
|
19
|
+
|
|
20
|
+
// Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines
|
|
21
|
+
// stay ~1px regardless of zoom (the standard "pristine grid" technique).
|
|
22
|
+
float gridLine(vec2 coord, float spacing) {
|
|
23
|
+
vec2 c = coord / spacing;
|
|
24
|
+
vec2 d = fwidth(c);
|
|
25
|
+
vec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);
|
|
26
|
+
float line = min(g.x, g.y);
|
|
27
|
+
return 1.0 - clamp(line, 0.0, 1.0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).
|
|
31
|
+
float axis(vec3 v, float i) {
|
|
32
|
+
return i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
void main() {
|
|
36
|
+
// Pick the two in-plane world coordinates.
|
|
37
|
+
vec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));
|
|
38
|
+
|
|
39
|
+
float minor = gridLine(coord, uCell);
|
|
40
|
+
float major = gridLine(coord, uCell * uMajor);
|
|
41
|
+
|
|
42
|
+
vec3 color = mix(uCellColor, uMajorColor, major);
|
|
43
|
+
float alpha = max(minor, major);
|
|
44
|
+
|
|
45
|
+
// Radial fade from the camera-projected center.
|
|
46
|
+
float dist = distance(vWorldPos, uCenter);
|
|
47
|
+
float fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);
|
|
48
|
+
alpha *= fade * fade;
|
|
49
|
+
|
|
50
|
+
if (alpha < 0.001) discard;
|
|
51
|
+
gl_FragColor = vec4(color, alpha);
|
|
52
|
+
}
|
|
53
|
+
`;function wt(e={}){let{cellSize:n=1,majorEvery:t=10,cellColor:r=8947848,majorColor:a=4473924,fadeDistance:o=100,plane:i="y"}=e,l=i==="y"?new W.Vector2(0,2):i==="z"?new W.Vector2(0,1):new W.Vector2(1,2),s=2.5,c=new W.PlaneGeometry(1,1);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let u=new W.ShaderMaterial({vertexShader:zn,fragmentShader:Gn,transparent:!0,depthWrite:!1,side:W.DoubleSide,uniforms:{uAxes:{value:l},uCell:{value:n},uMajor:{value:t},uCellColor:{value:new W.Color(r)},uMajorColor:{value:new W.Color(a)},uCenter:{value:new W.Vector3},uFade:{value:o}}}),d=new W.Mesh(c,u);d.name="grid",d.userData.id="grid",d.renderOrder=-1;let E=o,T=o*s,v=new W.Vector3;return{object:d,update:y=>{i==="y"?(d.position.set(y.x,0,y.z),v.set(y.x,0,y.z)):i==="z"?(d.position.set(y.x,y.y,0),v.set(y.x,y.y,0)):(d.position.set(0,y.y,y.z),v.set(0,y.y,y.z)),u.uniforms.uCenter.value.copy(v),d.scale.setScalar(T)},fitToContent:y=>{if(y.isEmpty())return;let m=y.getSize(new W.Vector3),g=(M,p)=>p===0?M.x:p===1?M.y:M.z,R=Math.max(g(m,l.x),g(m,l.y));if(!(R>0)||!Number.isFinite(R))return;let x=20;u.uniforms.uCell.value=Vn(R/x),E=R*2,u.uniforms.uFade.value=E,T=E*s},setVisible:y=>{d.visible=y},dispose:()=>{d.removeFromParent(),c.dispose(),u.dispose()}}}import*as ee from"three";import{ViewHelper as Nn}from"three/addons/helpers/ViewHelper.js";function Mt(e){let{camera:n,domElement:t,controller:r}=e,a=new Nn(n,t);a.setLabels("X","Y","Z");let o=!0,i=128,l=new ee.Raycaster,s=new ee.OrthographicCamera(-2,2,2,-2,0,4);s.position.set(0,0,2),s.updateMatrixWorld();let c={posX:new ee.Vector3(1,0,0),negX:new ee.Vector3(-1,0,0),posY:new ee.Vector3(0,1,0),negY:new ee.Vector3(0,-1,0),posZ:new ee.Vector3(0,0,1),negZ:new ee.Vector3(0,0,-1)},u=E=>{let T=t.getBoundingClientRect(),v=T.left+t.offsetWidth-i-a.location.right,y=T.top+t.offsetHeight-i-a.location.bottom,m=new ee.Vector2((E.clientX-v)/i*2-1,-((E.clientY-y)/i)*2+1);if(Math.abs(m.x)>1||Math.abs(m.y)>1)return null;a.quaternion.copy(n.quaternion).invert(),a.updateMatrixWorld(),l.setFromCamera(m,s);let g=l.intersectObjects(a.children,!1);for(let R of g){let x=R.object.userData?.type;if(typeof x=="string"&&x in c)return x}return null};return{render:E=>{if(!o)return;let T=E.autoClear;E.autoClear=!1,a.render(E),E.autoClear=T},update:()=>{},handleClick:E=>{if(!o)return!1;let T=u(E);return T?(r.getProjection()==="orthographic"&&r.setProjection("perspective"),r.setViewDirection(c[T],!1),!0):!1},isAnimating:!1,setVisible:E=>{o=E},isVisible:()=>o,dispose:()=>a.dispose()}}import*as J from"three";import{LineSegmentsGeometry as Wn}from"three/addons/lines/LineSegmentsGeometry.js";import{LineSegments2 as Je}from"three/addons/lines/LineSegments2.js";import{LineMaterial as $n}from"three/addons/lines/LineMaterial.js";function De(e,n,t){let o=Math.cos(Math.PI/180*t),i=e.length/3;if(i>=67108864)throw new Error(`extractEdgeSegments: ${i} vertices exceeds 2^26 limit`);let l=new Float64Array(i),s=new Float64Array(i),c=new Float64Array(i);for(let f=0;f<i;f++)l[f]=Math.round(e[3*f]*1e4),s[f]=Math.round(e[3*f+1]*1e4),c[f]=Math.round(e[3*f+2]*1e4);let u=16;for(;u<i*2;)u<<=1;let d=u-1,E=new Int32Array(u).fill(-1),T=new Int32Array(i);for(let f=0;f<i;f++){let h=(Math.imul(l[f]|0,73856093)^Math.imul(s[f]|0,19349663)^Math.imul(c[f]|0,83492791))&d;for(;;){let b=E[h];if(b===-1){E[h]=f,T[f]=f;break}if(l[b]===l[f]&&s[b]===s[f]&&c[b]===c[f]){T[f]=b;break}h=h+1&d}}let v=new Float32Array(4096),y=0,m=(f,h)=>{if(y+6>v.length){let b=new Float32Array(v.length*2);b.set(v),v=b}v[y++]=e[3*f],v[y++]=e[3*f+1],v[y++]=e[3*f+2],v[y++]=e[3*h],v[y++]=e[3*h+1],v[y++]=e[3*h+2]},g=new Map,R=[],x=[],M=[],p=(n?n.length:i)/3;for(let f=0;f<p;f++){let h=n?n[3*f]:3*f,b=n?n[3*f+1]:3*f+1,C=n?n[3*f+2]:3*f+2,H=T[h],L=T[b],P=T[C];if(H===L||L===P||P===H)continue;let k=e[3*C]-e[3*b],O=e[3*C+1]-e[3*b+1],I=e[3*C+2]-e[3*b+2],S=e[3*h]-e[3*b],D=e[3*h+1]-e[3*b+1],G=e[3*h+2]-e[3*b+2],j=O*G-I*D,$=I*S-k*G,U=k*D-O*S,Q=j*j+$*$+U*U;if(Q>0){let K=1/Math.sqrt(Q);j*=K,$*=K,U*=K}else j=0,$=0,U=0;for(let K=0;K<3;K++){let de,fe,ne,se;K===0?(de=h,fe=b,ne=H,se=L):K===1?(de=b,fe=C,ne=L,se=P):(de=C,fe=h,ne=P,se=H);let Ae=se*67108864+ne,me=g.get(Ae);if(me!==void 0&&me!==-1)j*M[3*me]+$*M[3*me+1]+U*M[3*me+2]<=o&&m(de,fe),g.set(Ae,-1);else{let ge=ne*67108864+se;if(!g.has(ge)){let je=R.length;g.set(ge,je),R.push(de),x.push(fe),M.push(j,$,U)}}}}for(let f of g.values())f!==-1&&m(R[f],x[f]);return v.slice(0,y)}function Ct(){return[`const extract = ${De.toString()};`,"self.onmessage = (event) => {"," const { id, positions, index, thresholdAngle } = event.data;"," try {"," const segments = extract(positions, index, thresholdAngle);"," self.postMessage({ id, segments }, [segments.buffer]);"," } catch (error) {"," self.postMessage({ id, error: String((error && error.message) || error) });"," }","};"].join(`
|
|
54
|
+
`)}var xe="edge-overlay",Qe="triangle-cap",qn=2236962,Yn=1.5,Xn=44,Kn=.75,Zn=4e6,Jn=2e6,Qn=25e3,Ht=128*1024*1024,er=80,At=20,tr=1,nr=2;function Dt(e,n){let t=Array.isArray(e.material)?e.material:[e.material];for(let r of t)r&&(r.polygonOffset=n,r.polygonOffsetFactor=n?tr:0,r.polygonOffsetUnits=n?nr:0)}function Ye(e){let n=e.getAttribute("position");return n?(e.index?e.index.count:n.count)/3:0}function Lt(e){let n=e.getAttribute("position");if(!n||n.isInterleavedBufferAttribute||n.itemSize!==3||!(n.array instanceof Float32Array)||n.count>=67108864)return null;let t=e.index;return t&&!(t.array instanceof Uint32Array)&&!(t.array instanceof Uint16Array)?null:{positions:n.array,index:t?t.array:null}}function Ot(e,n){let r=2166136261,a=s=>{r^=s,r=Math.imul(r,16777619)},o=new Uint32Array(e.positions.buffer,e.positions.byteOffset,e.positions.length),i=Math.min(4096,o.length);for(let s=0;s<i;s++)a(o[s]);for(let s=Math.max(i,o.length-4096);s<o.length;s++)a(o[s]);let l=0;if(e.index){l=e.index.length;let s=Math.min(4096,l);for(let c=0;c<s;c++)a(e.index[c]);for(let c=Math.max(s,l-4096);c<l;c++)a(e.index[c])}return`${n}:${e.positions.length}:${l}:${r>>>0}`}var ce=new Map,Le=0;function It(e){let n=ce.get(e);return n&&(ce.delete(e),ce.set(e,n)),n}function Pt(e,n){if(n.byteLength>Ht)return;let t=ce.get(e);for(t&&(Le-=t.byteLength,ce.delete(e)),ce.set(e,n),Le+=n.byteLength;Le>Ht;){let r=ce.keys().next().value;Le-=ce.get(r).byteLength,ce.delete(r)}}function rr(e,n){let t=new J.EdgesGeometry(e,n),r=t.attributes.position?t.attributes.position.array:new Float32Array(0);return t.dispose(),r}function Xe(e,n){let t=Lt(e);if(!t)return rr(e,n);let r=Ot(t,n),a=It(r);if(a)return a;let o=De(t.positions,t.index,n);return Pt(r,o),o}var Ee,Re=new Map,or=1;function ar(){if(Ee!==void 0)return Ee;if(typeof Worker>"u"||typeof Blob>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return Ee=null,null;try{let e=URL.createObjectURL(new Blob([Ct()],{type:"text/javascript"})),n=new Worker(e);n.onmessage=t=>{let{id:r,segments:a,error:o}=t.data,i=Re.get(r);i&&(Re.delete(r),a?i.resolve(a):i.reject(new Error(o??"edge extraction failed in worker")))},n.onerror=()=>{for(let t of Re.values())t.reject(new Error("edge extraction worker crashed"));Re.clear(),n.terminate(),Ee=null},Ee=n}catch{Ee=null}return Ee}function ir(e,n,t){return new Promise((r,a)=>{let o=or++;Re.set(o,{resolve:r,reject:a});let i=n.positions.slice(),l=n.index?n.index.slice():null,s=[i.buffer];l&&s.push(l.buffer),e.postMessage({id:o,positions:i,index:l,thresholdAngle:t},s)})}var qe=new Map;function sr(e,n){let t=Lt(e);if(!t||Ye(e)<Qn)return Promise.resolve(Xe(e,n));let r=Ot(t,n),a=It(r);if(a)return Promise.resolve(a);let o=qe.get(r);if(o)return o;let i=ar();if(!i)return Promise.resolve(Xe(e,n));let l=ir(i,t,n).catch(()=>De(t.positions,t.index,n)).then(s=>(Pt(r,s),s)).finally(()=>{qe.delete(r)});return qe.set(r,l),l}var Oe=new WeakMap;function Ke(e,n){return Oe.get(e)?.get(n)}function Ft(e,n,t){let r=Oe.get(e);r||(r=new Map,Oe.set(e,r));let a=new Wn;a.setPositions(t);let o={geometry:a,refCount:0,segmentCount:t.length/6};return r.set(n,o),o}function lr(e){let n=e.userData,t=n.edgeSource&&Oe.get(n.edgeSource),r=n.edgeThresholdAngle!=null?t?.get(n.edgeThresholdAngle):void 0;if(!r||r.geometry!==e.geometry){e.geometry.dispose();return}r.refCount-=1,r.refCount<=0&&(r.geometry.dispose(),t.delete(n.edgeThresholdAngle))}function Bt(e){return{forcedColor:e.color!=null?new J.Color(e.color):null,darken:J.MathUtils.clamp(e.darken??Kn,0,1),width:e.width??Yn,thresholdAngle:e.thresholdAngle??Xn,distanceFade:e.distanceFade??!0,maxTriangles:e.maxTriangles??Zn,maxSegments:e.maxSegments??Jn}}function cr(e,n){let r=(Array.isArray(e.material)?e.material[0]:e.material)?.color;return r?r.clone().multiplyScalar(1-n):new J.Color(qn)}var Ie=class{constructor(n){re(this,"options",n);re(this,"byKey",new Map)}for(n,t){let r=this.options.forcedColor??cr(n,this.options.darken),a=r.getHex()*2+(t?1:0),o=this.byKey.get(a);return o||(o=ur(r,this.options.width,t),this.byKey.set(a,o)),o}disposeUnused(n){let t=new Set(n.map(r=>r.material));for(let r of this.byKey.values())t.has(r)||r.dispose()}};function ur(e,n,t){let r=new $n({color:e});return r.linewidth=n,t&&(r.transparent=!0),r}function dr(e,n,t,r,a){n.refCount+=1;let o=new Je(n.geometry,t);return o.userData.kind=xe,o.userData.edgeSource=e,o.userData.edgeThresholdAngle=r,o.raycast=()=>{},a&&pr(o),o}var St=new J.Vector3,mr=new J.Vector3;function fr(e,n,t){e.geometry.boundingSphere||e.geometry.computeBoundingSphere();let r=e.geometry.boundingSphere;if(!r||r.radius<=0)return 1/0;let a=r.radius*e.matrixWorld.getMaxScaleOnAxis();if(St.copy(r.center).applyMatrix4(e.matrixWorld),n.isPerspectiveCamera){let o=n,i=mr.setFromMatrixPosition(n.matrixWorld).distanceTo(St);if(i<=a)return 1/0;let l=Math.tan(J.MathUtils.degToRad(o.fov)*.5);return a/(i*l)*t}if(n.isOrthographicCamera){let o=n,i=(o.top-o.bottom)/o.zoom;return i>0?2*a/i*t:1/0}return 1/0}function pr(e){e.onBeforeRender=(n,t,r)=>{Je.prototype.onBeforeRender.call(e,n);let a=e.material,o=fr(e,r,a.resolution.y);a.opacity=J.MathUtils.clamp((o-At)/(er-At),0,1)}}function Er(e){return e.userData?.kind===xe}function kt(e,n){let t=[];return e.traverse(r=>{if(r instanceof J.Mesh&&!(r.userData.id==="floor"||r.userData.id==="grid")&&r.userData.kind!==xe&&!r.children.some(a=>a.userData?.kind===xe)&&r.geometry){if(Ye(r.geometry)>n){r.userData.edgesSkipped=Qe,console.debug(`[edges] skipping mesh over triangle cap (${Ye(r.geometry)} > ${n})`);return}delete r.userData.edgesSkipped,t.push(r)}}),t}function Ut(e,n,t,r){let a=r.distanceFade&&n.segmentCount<=r.maxSegments,o=dr(e.geometry,n,t.for(e,a),r.thresholdAngle,a);return e.add(o),Dt(e,!0),o}function La(e,n={}){let t=Bt(n),r=new Ie(t),a=[];for(let o of kt(e,t.maxTriangles)){let i=Ke(o.geometry,t.thresholdAngle)??Ft(o.geometry,t.thresholdAngle,Xe(o.geometry,t.thresholdAngle));a.push(Ut(o,i,r,t))}return r.disposeUnused(a),a}var _t=new WeakMap;function Ze(e){return _t.get(e)??0}function hr(e,n){for(let t=e;t;t=t.parent)if(t===n)return!0;return!1}async function Vt(e,n={}){let t=Bt(n),r=new Ie(t),a=Ze(e),o=[],i=kt(e,t.maxTriangles).map(async l=>{let s=Ke(l.geometry,t.thresholdAngle);if(!s){let c=await sr(l.geometry,t.thresholdAngle);if(Ze(e)!==a||!hr(l,e)||l.children.some(u=>u.userData?.kind===xe))return;s=Ke(l.geometry,t.thresholdAngle),s||(s=Ft(l.geometry,t.thresholdAngle,c))}o.push(Ut(l,s,r,t))});return await Promise.all(i),r.disposeUnused(o),o}function zt(e){_t.set(e,Ze(e)+1);let n=[];e.traverse(r=>{r instanceof Je&&Er(r)&&n.push(r)});let t=new Set;for(let r of n)lr(r),t.add(r.material),r.parent instanceof J.Mesh&&Dt(r.parent,!1),r.removeFromParent();return t.forEach(r=>r.dispose()),n.length}import*as N from"three";import{Pass as gr,FullScreenQuad as yr}from"three/addons/postprocessing/Pass.js";var et={uniforms:{tDiffuse:{value:null},tNormal:{value:null},tDepth:{value:null},uResolution:{value:new N.Vector2(1,1)},uColor:{value:new N.Color(2236962)},uOpacity:{value:1},uNormalThreshold:{value:.4},uDepthThreshold:{value:.02},uThickness:{value:1},uNear:{value:.1},uFar:{value:1e3},uPerspective:{value:1}},vertexShader:`
|
|
55
|
+
varying vec2 vUv;
|
|
56
|
+
void main() {
|
|
57
|
+
vUv = uv;
|
|
58
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
59
|
+
}
|
|
60
|
+
`,fragmentShader:`
|
|
61
|
+
uniform sampler2D tDiffuse;
|
|
62
|
+
uniform sampler2D tNormal;
|
|
63
|
+
uniform sampler2D tDepth;
|
|
64
|
+
uniform vec2 uResolution;
|
|
65
|
+
uniform vec3 uColor;
|
|
66
|
+
uniform float uOpacity;
|
|
67
|
+
uniform float uNormalThreshold;
|
|
68
|
+
uniform float uDepthThreshold;
|
|
69
|
+
uniform float uThickness;
|
|
70
|
+
uniform float uNear;
|
|
71
|
+
uniform float uFar;
|
|
72
|
+
uniform float uPerspective;
|
|
73
|
+
varying vec2 vUv;
|
|
74
|
+
|
|
75
|
+
float viewZOf(const in float depth) {
|
|
76
|
+
float perspective = (uNear * uFar) / ((uFar - uNear) * depth - uFar);
|
|
77
|
+
float orthographic = -(depth * (uFar - uNear) + uNear);
|
|
78
|
+
return mix(orthographic, perspective, uPerspective);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
void main() {
|
|
82
|
+
vec4 color = texture2D(tDiffuse, vUv);
|
|
83
|
+
vec2 texel = uThickness / uResolution;
|
|
84
|
+
|
|
85
|
+
// Roberts cross over the two diagonal pairs.
|
|
86
|
+
vec2 offsetA = vec2(texel.x, texel.y);
|
|
87
|
+
vec2 offsetB = vec2(texel.x, -texel.y);
|
|
88
|
+
|
|
89
|
+
float z0 = viewZOf(texture2D(tDepth, vUv + offsetA).x);
|
|
90
|
+
float z1 = viewZOf(texture2D(tDepth, vUv - offsetA).x);
|
|
91
|
+
float z2 = viewZOf(texture2D(tDepth, vUv + offsetB).x);
|
|
92
|
+
float z3 = viewZOf(texture2D(tDepth, vUv - offsetB).x);
|
|
93
|
+
float zCenter = viewZOf(texture2D(tDepth, vUv).x);
|
|
94
|
+
// Relative difference: a constant threshold in absolute Z turns distant geometry into
|
|
95
|
+
// noise (depth precision) and near geometry blind; normalizing by the center depth keeps
|
|
96
|
+
// the response scale-invariant across the viewer's mm\u2192m scenes.
|
|
97
|
+
float depthDelta = (abs(z0 - z1) + abs(z2 - z3)) / max(abs(zCenter), 1e-6);
|
|
98
|
+
float depthEdge = step(uDepthThreshold, depthDelta);
|
|
99
|
+
|
|
100
|
+
vec3 n0 = texture2D(tNormal, vUv + offsetA).rgb * 2.0 - 1.0;
|
|
101
|
+
vec3 n1 = texture2D(tNormal, vUv - offsetA).rgb * 2.0 - 1.0;
|
|
102
|
+
vec3 n2 = texture2D(tNormal, vUv + offsetB).rgb * 2.0 - 1.0;
|
|
103
|
+
vec3 n3 = texture2D(tNormal, vUv - offsetB).rgb * 2.0 - 1.0;
|
|
104
|
+
float normalDelta = (1.0 - dot(n0, n1)) + (1.0 - dot(n2, n3));
|
|
105
|
+
float normalEdge = step(uNormalThreshold, normalDelta);
|
|
106
|
+
|
|
107
|
+
float edge = max(depthEdge, normalEdge) * uOpacity;
|
|
108
|
+
gl_FragColor = vec4(mix(color.rgb, uColor, edge), color.a);
|
|
109
|
+
}
|
|
110
|
+
`},Pe=class extends gr{constructor(t,r,a,o,i={}){super();re(this,"camera");re(this,"scene");re(this,"normalMaterial");re(this,"edgeMaterial");re(this,"fsQuad");re(this,"normalTarget",null);re(this,"width");re(this,"height");this.scene=t,this.camera=r,this.width=Math.max(1,a),this.height=Math.max(1,o),this.normalMaterial=new N.MeshNormalMaterial,this.normalMaterial.blending=N.NoBlending,this.edgeMaterial=new N.ShaderMaterial({uniforms:N.UniformsUtils.clone(et.uniforms),vertexShader:et.vertexShader,fragmentShader:et.fragmentShader});let l=this.edgeMaterial.uniforms;l.uColor.value=new N.Color(i.color??2236962),l.uOpacity.value=i.opacity??1,l.uNormalThreshold.value=i.normalThreshold??.4,l.uDepthThreshold.value=i.depthThreshold??.02,l.uThickness.value=i.thickness??1,this.fsQuad=new yr(this.edgeMaterial),this.needsSwap=!0}acquireNormalTarget(){if(!this.normalTarget){let t=new N.DepthTexture(this.width,this.height);this.normalTarget=new N.WebGLRenderTarget(this.width,this.height,{minFilter:N.NearestFilter,magFilter:N.NearestFilter,depthTexture:t})}return this.normalTarget}setSize(t,r){this.width=Math.max(1,t),this.height=Math.max(1,r),this.normalTarget?.setSize(this.width,this.height)}render(t,r,a){let o=this.acquireNormalTarget(),i=t.getRenderTarget(),l=t.autoClear,s=t.getClearColor(new N.Color),c=t.getClearAlpha(),u=this.scene.overrideMaterial;t.setRenderTarget(o),t.setClearColor(7829503,1),t.autoClear=!0,this.scene.overrideMaterial=this.normalMaterial,t.render(this.scene,this.camera),this.scene.overrideMaterial=u,t.setClearColor(s,c),t.autoClear=l;let d=this.edgeMaterial.uniforms;d.tDiffuse.value=a.texture,d.tNormal.value=o.texture,d.tDepth.value=o.depthTexture,d.uResolution.value.set(this.width,this.height);let E=this.camera;d.uPerspective.value=E.isPerspectiveCamera?1:0,d.uNear.value=this.camera.near??.1,d.uFar.value=this.camera.far??1e3,t.setRenderTarget(this.renderToScreen?null:r),this.fsQuad.render(t),t.setRenderTarget(i)}dispose(){this.normalTarget?.dispose(),this.normalMaterial.dispose(),this.edgeMaterial.dispose(),this.fsQuad.dispose()}};import{EffectComposer as br}from"three/addons/postprocessing/EffectComposer.js";import{RenderPass as Tr}from"three/addons/postprocessing/RenderPass.js";import{GTAOPass as Rr}from"three/addons/postprocessing/GTAOPass.js";import{SMAAPass as xr}from"three/addons/postprocessing/SMAAPass.js";import{OutputPass as vr}from"three/addons/postprocessing/OutputPass.js";function Gt(e,n,t,r,a,o){let i=new br(e),l=new Tr(n,t);i.addPass(l);let s=null;(o.ambientOcclusion??!0)&&(s=new Rr(n,t,r,a),s.blendIntensity=o.aoIntensity??1,s.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(s));let c=typeof o.edgeDetection=="object"?o.edgeDetection:{},u=new Pe(n,t,r,a,c);u.enabled=!!o.edgeDetection,i.addPass(u);let d=new xr;i.addPass(d);let E=new vr;i.addPass(E),e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure;let T=o.aoPixelRatio??1;return i.setSize(r,a),{render:v=>i.render(v),setSize:(v,y,m)=>{i.setPixelRatio(Math.min(m,T)),i.setSize(v,y)},setCamera:v=>{if(l.camera=v,u.camera=v,!s)return;s.camera=v;let y=v.isPerspectiveCamera?1:0;s.gtaoMaterial.defines.PERSPECTIVE_CAMERA!==y&&(s.gtaoMaterial.defines.PERSPECTIVE_CAMERA=y,s.gtaoMaterial.needsUpdate=!0)},setEdgeDetection:v=>{u.enabled=v},edgeDetectionEnabled:()=>u.enabled,dispose:()=>{i.dispose(),s?.dispose(),u.dispose(),d.dispose(),E.dispose()}}}import*as Nt from"three";import{CSS2DRenderer as wr,CSS2DObject as Mr}from"three/addons/renderers/CSS2DRenderer.js";function jt(e,n){let t=new wr,r=t.domElement;r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.overflow="hidden",r.style.pointerEvents="none",r.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(r);let a={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(a.width,a.height);let o=new Nt.Group;o.name="label-layer",o.userData.id="label-layer",n.add(o);let i=new Set;return{addLabel:(s,c,u)=>{let d=document.createElement("div");d.textContent=s,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 E=new Mr(d);return E.position.copy(c),o.add(E),i.add(E),{object:E,setPosition:T=>E.position.copy(T),setText:T=>{d.textContent=T},remove:()=>{E.removeFromParent(),d.remove(),i.delete(E)}}},render:(s,c)=>t.render(s,c),setSize:(s,c)=>t.setSize(s,c),dispose:()=>{i.forEach(s=>{s.removeFromParent(),s.element.remove()}),i.clear(),o.removeFromParent(),r.remove()}}}import*as _ from"three";import{Line2 as Cr}from"three/addons/lines/Line2.js";import{LineGeometry as Hr}from"three/addons/lines/LineGeometry.js";import{LineMaterial as Ar}from"three/addons/lines/LineMaterial.js";var Sr=12,Dr=16763904,Wt=.015,$t={Millimeters:{metersPerUnit:1/1e3,suffix:"mm"},Centimeters:{metersPerUnit:1/100,suffix:"cm"},Meters:{metersPerUnit:1,suffix:"m"},Inches:{metersPerUnit:1/39.37,suffix:"in"},Feet:{metersPerUnit:1/3.28084,suffix:"ft"}};function Lr(e){let n=e&&$t[e]||$t.Meters;return t=>`${(t/n.metersPerUnit).toPrecision(3)} ${n.suffix}`}function Or(e,n){if(e.isOrthographicCamera){let r=e;return Math.abs(r.top-r.bottom)/(r.zoom||1)*Wt}return((n?e.position.distanceTo(n):e.position.length())||1)*Wt}function Ir(e){let n=e.object;if(n instanceof _.Mesh)return e.face?[e.face.a,e.face.b,e.face.c]:null;if(n instanceof _.Points)return e.index!=null?[e.index]:null;if(n instanceof _.Line){if(e.index==null)return null;let t=n.geometry.index;return t?e.index+1>=t.count?null:[t.getX(e.index),t.getX(e.index+1)]:[e.index,e.index+1]}return null}function Pr(e,n,t,r){let a=e.point.clone(),o=e.object,i=Ir(e);if(!i||!o.geometry)return a;let l=o.geometry.attributes.position;if(!l)return a;let s=E=>{let T=E.clone().project(n);return new _.Vector2((T.x+1)/2*t.width,(1-T.y)/2*t.height)},c=s(a),u=a,d=r;for(let E of i){if(E>=l.count)continue;let v=new _.Vector3().fromBufferAttribute(l,E).applyMatrix4(o.matrixWorld),y=s(v).distanceTo(c);y<d&&(d=y,u=v)}return u}function qt(e){let{canvas:n,scene:t,getActiveCamera:r,getViewTarget:a,labelLayer:o,options:i={}}=e,l=i.snapPixels??Sr,s=new _.Color(i.color??Dr),c=Lr(i.displayUnit),u=(S,D)=>`${c(S)}
|
|
111
|
+
\u0394x ${c(D.x)} \u0394y ${c(D.y)} \u0394z ${c(D.z)}`,d=i.format??u,E=new _.Raycaster,T=new _.Vector2,v=!1,y=[],m=[],g=null,R=null,x=new _.PointsMaterial({color:s,size:8,sizeAttenuation:!1,depthTest:!1}),M=new _.PointsMaterial({color:s,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),p=null,f=S=>{if(!S){p&&(p.visible=!1);return}if(!p){let D=new _.BufferGeometry;D.setAttribute("position",new _.Float32BufferAttribute([0,0,0],3)),p=new _.Points(D,M),p.renderOrder=1e3,p.userData.id="measure",p.raycast=()=>{},t.add(p)}p.position.copy(S),p.visible=!0},h=S=>{let D=new _.BufferGeometry;D.setAttribute("position",new _.Float32BufferAttribute([S.x,S.y,S.z],3));let G=new _.Points(D,x);return G.renderOrder=999,G.userData.id="measure",G.raycast=()=>{},t.add(G),G},b=()=>{y.length=0,m.forEach(S=>{S.geometry.dispose(),S.removeFromParent()}),m.length=0,g&&(g.geometry.dispose(),g.material.dispose(),g.removeFromParent(),g=null),R?.remove(),R=null},C=()=>{if(y.length!==2)return;let[S,D]=y,G=new Hr;G.setPositions([S.x,S.y,S.z,D.x,D.y,D.z]);let j=new Ar({color:s});j.linewidth=2,j.depthTest=!1,g=new Cr(G,j),g.renderOrder=998,g.userData.id="measure",g.raycast=()=>{},t.add(g);let $=S.clone().add(D).multiplyScalar(.5),U=new _.Vector3(Math.abs(D.x-S.x),Math.abs(D.y-S.y),Math.abs(D.z-S.z));R=o.addLabel(d(S.distanceTo(D),U),$,i.labelClassName)},H=S=>{let D=n.getBoundingClientRect();T.x=(S.clientX-D.left)/D.width*2-1,T.y=-((S.clientY-D.top)/D.height)*2+1;let G=r();E.setFromCamera(T,G);let j=Or(G,a?.());E.params.Line.threshold=j,E.params.Points.threshold=j;let $=E.intersectObjects(t.children,!0).filter(U=>U.object.userData.id!=="measure"&&U.object.userData.id!=="grid");return $.length===0?null:Pr($[0],G,{width:D.width,height:D.height},l)},L=null,P=0,k=()=>{P&&(cancelAnimationFrame(P),P=0),L=null};return{setEnabled:S=>{v=S,S||(k(),b(),f(null))},isEnabled:()=>v,handleClick:S=>{if(!v)return!1;y.length===2&&b();let D=H(S);return D===null||(y.push(D),m.push(h(D)),y.length===2&&C()),!0},handleMove:S=>{v&&(L=S,!P&&(P=requestAnimationFrame(()=>{P=0;let D=L;L=null,!(!v||!D)&&f(H(D))})))},clear:b,dispose:()=>{k(),b(),p&&(p.geometry.dispose(),p.removeFromParent(),p=null),x.dispose(),M.dispose()}}}import*as Ue from"three";var Fr=64,Br=256,oe=new Map,ve=new Map,Fe=0,ke=class extends Error{constructor(n){super(`Texture load for ${n} resolved after clearTextureCache(); texture disposed.`),this.name="StaleTextureLoadError"}},Be=1;function Yt(e){Be=Math.max(1,e);for(let n of oe.values())n.anisotropy!==Be&&(n.anisotropy=Be,n.needsUpdate=!0)}function Xt(e,n){let t=kr(n),r=oe.get(t);if(r){oe.delete(t),oe.set(t,r),e.map=r,e.needsUpdate=!0;return}typeof document>"u"||Vr(n,t).then(a=>{e.map=a,e.needsUpdate=!0}).catch(a=>{a instanceof ke||F().warn(`Failed to load material texture ${n}:`,a)})}function Za(){Fe++;for(let e of oe.values())e.dispose();oe.clear(),ve.clear()}function kr(e){return e.length<=Br?e:`data-uri:${Ur(e).toString(16)}:${e.length}`}function Ur(e){let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0}function _r(e,n){for(oe.set(e,n);oe.size>Fr;){let t=oe.keys().next().value,r=oe.get(t);oe.delete(t),r.dispose()}}function Vr(e,n){let t=ve.get(n);if(!t){let r=Fe;t=new Promise((a,o)=>{new Ue.TextureLoader().load(e,i=>{if(r!==Fe){i.dispose(),o(new ke(e));return}i.colorSpace=Ue.SRGBColorSpace,i.anisotropy=Be,_r(n,i),ve.delete(n),a(i)},void 0,i=>{r===Fe&&ve.delete(n),o(i)})}),ve.set(n,t)}return t}import*as w from"three";import{OrbitControls as jr}from"three/addons/controls/OrbitControls.js";import{HDRLoader as Wr}from"three/addons/loaders/HDRLoader.js";import*as we from"three";var zr=.5,Gr=.01,Nr=.05;function Kt({camera:e,scene:n,groundNormals:t=[]}){let r=e.near,a=e.near,o=new we.Vector3,i=new we.Vector3;return{update:()=>{e.near!==a&&(r=e.near);let s=le(n),c=r;if(!s.isEmpty()){let u=s.getSize(i).length()*.5,d=e.position.distanceTo(s.getCenter(o))-u;for(let E of t)d=Math.min(d,Math.abs(e.position.dot(E)));c=we.MathUtils.clamp(d*zr,r,e.far*Gr)}Math.abs(c-a)>a*Nr&&(e.near=c,e.updateProjectionMatrix(),a=c)}}}var Te=new w.Vector3(0,0,1),$r="technical",tt={studio:{toneMapping:w.ACESFilmicToneMapping,toneMappingExposure:1,envMapIntensity:1,environmentIntensity:1,hemisphereIntensity:.75,ambientIntensity:.4,cullBackfaces:!1,ambientOcclusion:!1},technical:{toneMapping:w.NeutralToneMapping,toneMappingExposure:1,envMapIntensity:.9,environmentIntensity:1,hemisphereIntensity:.35,ambientIntensity:.25,cullBackfaces:!1,ambientOcclusion:!1},showcase:{toneMapping:w.ACESFilmicToneMapping,toneMappingExposure:1.15,envMapIntensity:1.4,environmentIntensity:1.25,hemisphereIntensity:.35,ambientIntensity:.15,cullBackfaces:!1,ambientOcclusion:!1}};function qr(e){let n=tt[e];return{envMapIntensity:n.envMapIntensity,cullBackfaces:n.cullBackfaces}}function Yr(e){let n=Math.abs(e.x),t=Math.abs(e.y),r=Math.abs(e.z);return r>=n&&r>=t?"z":t>=n&&t>=r?"y":"x"}var pi=function(e,n){let t=Xr(n||{}),r=t.environment?.sceneUp||Te,a=t.render.pixelRatio??Math.min(window.devicePixelRatio,2),o=Zr(t),i=no(t,e);i.up.copy(r);let l=ro(e,t,a);Yt(l.capabilities.getMaxAnisotropy());let s=ao(i,e,t),c=vt({scene:o,perspective:i,controls:s,onActiveCameraChange:()=>{},up:r}),u=()=>c.getActiveCamera(),d=!1;Qr(o,l,t,()=>d);let E=eo(o,t),T=E.sun,v=()=>{T&&Kr(T,le(o))};t.floor?.enabled&&to(o,t);let y=t.grid.enabled?wt({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;y&&o.add(y.object);let m=()=>{y&&y.fitToContent(le(o))},g=t.gizmo.enabled?Mt({camera:i,domElement:e,controller:c}):null,R=[];if(y){let A=t.grid.plane??"z";R.push(new w.Vector3(A==="x"?1:0,A==="y"?1:0,A==="z"?1:0))}t.floor.enabled&&R.push(r.clone().normalize());let x=t.camera.dynamicNear?Kt({camera:i,scene:o,groundNormals:R}):null,M=e.parentElement??e,p=t.measure.enabled?jt(M,o):null,f=t.measure.enabled&&p?qt({canvas:e,scene:o,getActiveCamera:u,labelLayer:p,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,displayUnit:t.measure.displayUnit,format:t.measure.format}}):null,h=t.events.enableEventHandlers!==!1?oo(e,o,c,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},b=5,C=0,H=0,L=A=>{C=A.clientX,H=A.clientY},P=A=>Math.hypot(A.clientX-C,A.clientY-H)>b,k=A=>{if(!P(A)){if(f?.handleClick(A)){A.stopImmediatePropagation();return}g?.handleClick(A)&&A.stopImmediatePropagation()}};(g||f)&&(e.addEventListener("mousedown",L,{capture:!0}),e.addEventListener("click",k,{capture:!0}));let O=A=>f?.handleMove(A);f&&e.addEventListener("mousemove",O,{passive:!0});let I=()=>{},S=A=>{Vt(A,{color:t.edges.color,darken:t.edges.darken,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle,distanceFade:t.edges.distanceFade,maxTriangles:t.edges.maxTriangles,maxSegments:t.edges.maxSegments}).then(()=>{D(A),I()})},D=A=>{if(t.edges.screenSpaceFallback===!1)return;let B=!1;A.traverse(Z=>{Z.userData?.edgesSkipped===Qe&&(B=!0)}),B!==K&&(K=B,ne())},G=A=>{zt(A),K&&(K=!1,ne()),I()},j=e.parentElement,$=()=>j?{width:j.clientWidth,height:j.clientHeight}:{width:window.innerWidth,height:window.innerHeight},U=null,Q=!!t.render.ambientOcclusion,K=!1,de=!1,fe=A=>{let{width:B,height:Z}=$(),pe=Gt(l,o,u(),Math.max(1,B),Math.max(1,Z),{toneMapping:t.render.toneMapping??w.NeutralToneMapping,toneMappingExposure:t.render.toneMappingExposure??1,ambientOcclusion:A,aoIntensity:t.render.aoIntensity,aoPixelRatio:t.render.aoPixelRatio,edgeDetection:!1});return pe.setSize(Math.max(1,B),Math.max(1,Z),a),pe},ne=()=>{if(!(Q||K)){U?.dispose(),U=null,I();return}(!U||de!==Q)&&(U?.dispose(),U=fe(Q),de=Q),U.setEdgeDetection(K),I()},se=()=>{U?.dispose(),U=null,ne()},Ae=A=>{Q=A,ne()};ne();let me=A=>{A.ambientIntensity!==void 0&&(E.ambient.intensity=A.ambientIntensity),A.hemisphereIntensity!==void 0&&!E.hemisphere&&A.hemisphereIntensity>0&&(E.hemisphere=new w.HemisphereLight(A.hemisphereSkyColor??t.lighting.hemisphereSkyColor,A.hemisphereGroundColor??t.lighting.hemisphereGroundColor,A.hemisphereIntensity),E.hemisphere.position.copy(t.environment.sceneUp??Te),o.add(E.hemisphere)),E.hemisphere&&(A.hemisphereIntensity!==void 0&&(E.hemisphere.intensity=A.hemisphereIntensity),A.hemisphereSkyColor!==void 0&&E.hemisphere.color.set(A.hemisphereSkyColor),A.hemisphereGroundColor!==void 0&&E.hemisphere.groundColor.set(A.hemisphereGroundColor)),I()},ge=A=>{t.environment.environmentIntensity=A,o.environmentIntensity=A,I()},je=A=>{t.render.toneMappingExposure=A,l.toneMappingExposure=A,U&&se()},Rn=A=>{t.render.aoIntensity=A,U&&se()},xn=A=>{let B=tt[A];ct=A,l.toneMapping=B.toneMapping,l.toneMappingExposure=B.toneMappingExposure,t.render.toneMapping=B.toneMapping,t.render.toneMappingExposure=B.toneMappingExposure,me({hemisphereIntensity:B.hemisphereIntensity,ambientIntensity:B.ambientIntensity}),ge(B.environmentIntensity),Q=B.ambientOcclusion,U?se():ne(),o.traverse(Z=>{if(Z.userData.source!=="compute")return;let pe=Z,Sn=Array.isArray(pe.material)?pe.material:pe.material?[pe.material]:[];for(let mt of Sn)"envMapIntensity"in mt&&(mt.envMapIntensity=B.envMapIntensity)}),I()},ct=t.look,vn=()=>qr(ct),{animate:wn,dispose:Mn,invalidate:ut}=Jr(l,o,i,u,c,s,$,a,t.events.onFrame,y,g,()=>U,p,x,t.render.onDemand??!0);I=ut,wn(),o.up.set(r.x,r.y,r.z),v(),m();let dt=A=>{A.traverse(B=>{let Z=B;!Z.geometry&&!Z.material||(Z.geometry?.dispose(),Array.isArray(Z.material)?Z.material.forEach(_e):Z.material&&_e(Z.material))})},Cn=A=>{A.userData.source="user",o.add(A)},Hn=A=>{A.removeFromParent(),dt(A)},An=()=>{o.children.filter(B=>B.userData.source==="user").forEach(B=>{B.removeFromParent(),dt(B)})};return{scene:o,camera:i,controls:s,renderer:l,cameraController:c,grid:y,gizmo:g,measureTool:f,applyEdges:S,clearEdges:G,invalidate:ut,setAmbientOcclusion:Ae,setLook:xn,setFillLights:me,setEnvironmentIntensity:ge,setToneMappingExposure:je,setAoIntensity:Rn,getMaterialAppearance:vn,updateShadowBounds:v,updateGridScale:m,dispose:()=>{d||(d=!0,Mn(),h.dispose(),(g||f)&&(e.removeEventListener("mousedown",L,{capture:!0}),e.removeEventListener("click",k,{capture:!0})),f&&e.removeEventListener("mousemove",O),f?.dispose(),p?.dispose(),g?.dispose(),y?.dispose(),U?.dispose(),c.dispose(),s.dispose(),l.dispose(),l.forceContextLoss(),o.traverse(A=>{let B=A;!B.geometry&&!B.material||(B.geometry?.dispose(),Array.isArray(B.material)?B.material.forEach(_e):B.material&&_e(B.material))}),o.environment?.dispose(),o.background instanceof w.Texture&&o.background.dispose())},fitToView:h.fitToView,clearSelection:h.clearSelection,addUserGeometry:Cn,removeUserGeometry:Hn,clearUserGeometry:An}};function Xr(e){let n=e.sceneScale||"m",r={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}}[n],a=e.look??$r,o=tt[a];return{sceneScale:n,look:a,camera:{position:e.camera?.position||new w.Vector3(-r.cameraDistance,-r.cameraDistance,r.cameraDistance),fov:e.camera?.fov||20,near:e.camera?.near||r.near,far:e.camera?.far||r.far,target:e.camera?.target||new w.Vector3(0,0,0),dynamicNear:e.camera?.dynamicNear??!0},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity??1,sunlightPosition:e.lighting?.sunlightPosition||new w.Vector3(r.lightDistance,r.lightDistance,r.lightHeight),ambientLightColor:e.lighting?.ambientLightColor||new w.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity??o.ambientIntensity,sunlightColor:e.lighting?.sunlightColor||16777215,enableHemisphereLight:e.lighting?.enableHemisphereLight??o.hemisphereIntensity>0,hemisphereSkyColor:e.lighting?.hemisphereSkyColor??14673663,hemisphereGroundColor:e.lighting?.hemisphereGroundColor??7036754,hemisphereIntensity:e.lighting?.hemisphereIntensity??o.hemisphereIntensity},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new w.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||Te,showEnvironment:e.environment?.showEnvironment??!1,environmentIntensity:e.environment?.environmentIntensity??o.environmentIntensity},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||r.floorSize,color:e.floor?.color||new w.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??o.toneMapping,toneMappingExposure:e.render?.toneMappingExposure??o.toneMappingExposure,preserveDrawingBuffer:e.render?.preserveDrawingBuffer??!1,ambientOcclusion:e.render?.ambientOcclusion??o.ambientOcclusion,aoIntensity:e.render?.aoIntensity??1,aoPixelRatio:e.render?.aoPixelRatio??1,onDemand:e.render?.onDemand??!0},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||r.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??Yr(e.environment?.sceneUp??Te)},gizmo:{enabled:e.gizmo?.enabled??!1},edges:{enabled:e.edges?.enabled??!1,color:e.edges?.color,darken:e.edges?.darken,width:e.edges?.width??1.5,thresholdAngle:e.edges?.thresholdAngle??44,distanceFade:e.edges?.distanceFade??!0},measure:{enabled:e.measure?.enabled??!1,snapPixels:e.measure?.snapPixels,color:e.measure?.color,labelClassName:e.measure?.labelClassName,displayUnit:e.measure?.displayUnit,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}}}function _e(e){for(let n of Object.values(e))n instanceof w.Texture&&n.dispose();e.dispose()}function Kr(e,n){if(n.isEmpty())return;let t=n.getCenter(new w.Vector3),r=n.getSize(new w.Vector3).length()*.5*1.2,a=e.shadow.camera;a.left=-r,a.right=r,a.top=r,a.bottom=-r,e.target.position.copy(t),e.target.updateMatrixWorld();let o=e.position.distanceTo(t);a.near=Math.max(r*.01,o-r),a.far=o+r,a.updateProjectionMatrix()}function Zr(e){let n=new w.Scene,t=typeof e.environment.backgroundColor=="string"?new w.Color(e.environment.backgroundColor):e.environment.backgroundColor;return n.background=t||null,n}function Jr(e,n,t,r,a,o,i,l,s,c,u,d,E,T,v=!0){let y=null,m=performance.now(),g=!0,R=0,x=500,M=new w.Matrix4,p=new w.Matrix4,f=null,h=()=>{g=!0},b=O=>{O.updateMatrixWorld();let I=f!==O||!M.equals(O.matrixWorld)||!p.equals(O.projectionMatrix);return I&&(f=O,M.copy(O.matrixWorld),p.copy(O.projectionMatrix)),I},C=e.domElement,H=["pointerdown","pointerup","wheel"];if(v)for(let O of H)C.addEventListener(O,h,{passive:!0});let L=()=>{let{width:O,height:I}=i();if(O===0||I===0)return;let S=Math.floor(O*l),D=Math.floor(I*l);(e.domElement.width!==S||e.domElement.height!==D)&&(e.setPixelRatio(l),e.setSize(O,I,!1),t.aspect=O/I,t.updateProjectionMatrix(),a.updateAspect(O,I),d?.()?.setSize(O,I,l),E?.setSize(O,I),h())},P=function(){y=requestAnimationFrame(P);let O=performance.now(),I=(O-m)/1e3;m=O,L(),(o.enableDamping||o.autoRotate)&&o.update(),c&&c.update(r().position),u&&u.update(I),T&&T.update(),s?.(I);let S=r();if(v){if(!(g||b(S)||O-R>=x))return;g=!1,R=O}let D=d?.();D?(D.setCamera(S),D.render(I)):e.render(n,S),E&&E.render(n,S),u&&u.render(e)};return{animate:P,dispose:()=>{if(y!==null&&(cancelAnimationFrame(y),y=null),v)for(let O of H)C.removeEventListener(O,h)},invalidate:h}}function Qr(e,n,t,r){t.environment.enableEnvironmentLighting?new Wr().load(t.environment.hdrPath||"/baseHDR.hdr",function(a){if(r()){a.dispose();return}if(!a?.image){F().warn("HDR loaded without image data; skipping environment map."),a?.dispose(),t.events.onReady?.();return}a.mapping=w.EquirectangularReflectionMapping;let o=new w.PMREMGenerator(n);o.compileEquirectangularShader();let i=o.fromEquirectangular(a).texture;o.dispose(),e.environment=i,e.environmentIntensity=t.environment.environmentIntensity??1,t.environment.showEnvironment?e.background=a:a.dispose(),t.events.onReady?.()},void 0,function(a){r()||(F().warn("HDR texture could not be loaded, falling back to basic lighting:",a),t.events.onReady?.())}):t.events.onReady?.()}function eo(e,n){let t=new w.AmbientLight(n.lighting.ambientLightColor,n.lighting.ambientLightIntensity);e.add(t);let r=null;if(n.lighting.enableHemisphereLight){r=new w.HemisphereLight(n.lighting.hemisphereSkyColor,n.lighting.hemisphereGroundColor,n.lighting.hemisphereIntensity);let i=n.environment.sceneUp??Te;r.position.copy(i),e.add(r)}if(!n.lighting.enableSunlight)return{ambient:t,hemisphere:r,sun:null};let a=new w.DirectionalLight(n.lighting.sunlightColor??16777215,n.lighting.sunlightIntensity),o=n.lighting.sunlightPosition;return o&&a.position.set(o.x,o.y,o.z),n.render.enableShadows?(a.castShadow=!0,a.shadow.mapSize.width=n.render.shadowMapSize||2048,a.shadow.mapSize.height=n.render.shadowMapSize||2048,a.shadow.bias=-1e-4,a.shadow.normalBias=.02,a.shadow.radius=4,e.add(a),e.add(a.target),{ambient:t,hemisphere:r,sun:a}):(e.add(a),{ambient:t,hemisphere:r,sun:null})}function to(e,n){let t=n.floor.size,r=new w.PlaneGeometry(t,t),a=typeof n.floor.color=="string"?new w.Color(n.floor.color):n.floor.color,o=new w.MeshStandardMaterial({color:a,roughness:n.floor.roughness,metalness:n.floor.metalness,side:w.DoubleSide}),i=new w.Mesh(r,o);i.userData.id="floor",i.name="floor";let l=(n.environment?.sceneUp||Te).clone().normalize();i.quaternion.setFromUnitVectors(new w.Vector3(0,0,1),l),i.position.set(0,0,0),n.floor.receiveShadow&&n.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function no(e,n){let t=n.parentElement,r=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight,o=new w.PerspectiveCamera(e.camera.fov,r/a,e.camera.near,e.camera.far),i=e.camera.position;return i&&o.position.set(i.x,i.y,i.z),o}function ro(e,n,t){let r=new w.WebGLRenderer({antialias:n.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:n.render.preserveDrawingBuffer,logarithmicDepthBuffer:!1}),a=e.parentElement,o=a?a.clientWidth:window.innerWidth,i=a?a.clientHeight:window.innerHeight;return a&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),r.setSize(o,i,!1),r.setPixelRatio(t),n.render.enableShadows&&(r.shadowMap.enabled=!0,r.shadowMap.type=w.VSMShadowMap),r.toneMapping=n.render.toneMapping,r.toneMappingExposure=n.render.toneMappingExposure??1,r.outputColorSpace=w.SRGBColorSpace,r.sortObjects=!0,r}function oo(e,n,t,r){let a=new Set,o=new Map,i=new w.Raycaster,l=new w.Vector2,s=new w.Vector2,c=()=>t.getActiveCamera(),u=p=>{let f=p;for(;f;){if(!f.visible)return!1;f=f.parent}return!0},d=()=>{let p=le(n);if(p.isEmpty()){F().warn("No objects to fit to view");return}t.frameBounds(p,!1)},E=typeof r.events.selectionColor=="string"?new w.Color(r.events.selectionColor):r.events.selectionColor instanceof w.Color?r.events.selectionColor:new w.Color("#ff0000"),T=()=>{a.forEach(p=>{let f=p;if(o.has(p)){let h=o.get(p),b=f.material;b instanceof w.Material?b.dispose():Array.isArray(b)&&b.forEach(H=>H.dispose()),f.material=h,o.delete(p);let C=p;for(;C.parent;)C=C.parent;C!==n&&(h instanceof w.Material?h.dispose():h.forEach(H=>H.dispose()))}}),a.clear()},v=p=>{let f=p;if(!(f.material instanceof w.Material))return!1;o.set(p,f.material);let h=f.material.clone();return p instanceof w.Mesh&&"emissive"in h?h.emissive=E.clone():"color"in h&&(h.color=E.clone()),f.material=h,!0},y=()=>{let p=le(n),f=p.isEmpty()?1:p.getSize(new w.Vector3).length();i.params.Points.threshold=f*.01},m=p=>{s.set(p.clientX,p.clientY)},g=p=>{let f=new w.Vector2(p.clientX,p.clientY);if(s.distanceTo(f)>5)return;let h=e.getBoundingClientRect();l.x=(p.clientX-h.left)/h.width*2-1,l.y=-((p.clientY-h.top)/h.height)*2+1,y(),i.setFromCamera(l,c());let b=i.intersectObjects(n.children,!0).filter(C=>u(C.object));if(b.length>0){let C=b[0].object;a.has(C)||(T(),a.add(C),v(C),r.events?.onObjectSelected?.(C),C instanceof w.Mesh&&Object.keys(C.userData).length>0&&r.events?.onMeshMetadataClicked?.(C.userData))}else T(),r.events?.onBackgroundClicked?.({x:l.x,y:l.y})},R=p=>{let f=e.getBoundingClientRect();l.x=(p.clientX-f.left)/f.width*2-1,l.y=-((p.clientY-f.top)/f.height)*2+1,y(),i.setFromCamera(l,c());let h=i.intersectObjects(n.children,!0).filter(H=>u(H.object));if(h.length===0)return;let b=h[0].object;if(r.events?.onMeshDoubleClicked?.(b),!r.events?.enableDoubleClickZoom)return;let C=new w.Box3().setFromObject(b);C.isEmpty()||t.frameBounds(C,!0)},x=p=>{if(r.events?.enableKeyboardControls)switch(p.key.toLowerCase()){case"f":p.preventDefault(),d();break;case"escape":p.preventDefault(),T();break;case" ":p.preventDefault(),d();break}};return r.events?.enableClickToFocus&&(e.addEventListener("mousedown",m),e.addEventListener("click",g),e.addEventListener("dblclick",R)),r.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",m),e.removeEventListener("click",g),e.removeEventListener("dblclick",R),e.removeEventListener("keydown",x),T()},fitToView:d,clearSelection:T}}function ao(e,n,t){let r=new jr(e,n),a=t.camera.target;return a&&r.target.set(a.x,a.y,a.z),r.enableDamping=t.controls.enableDamping||!1,r.dampingFactor=t.controls.dampingFactor||.05,r.autoRotate=t.controls.autoRotate||!1,r.autoRotateSpeed=t.controls.autoRotateSpeed||.5,r.enableZoom=t.controls.enableZoom??!0,r.enablePan=t.controls.enablePan??!0,r.minDistance=t.controls.minDistance||.001,r.maxDistance=t.controls.maxDistance||1/0,r.screenSpacePanning=!1,r.maxPolarAngle=Math.PI,r.update(),r}var hi=["technical","studio","showcase"];import*as te from"three";import{Line2 as io}from"three/addons/lines/Line2.js";import{LineGeometry as so}from"three/addons/lines/LineGeometry.js";import{LineMaterial as lo}from"three/addons/lines/LineMaterial.js";function Ve(e,n,t,r=!0){return{x:e,y:n,z:t}}var co="#ffffff",Zt=12,uo=4e-4,mo=12,fo=.05;function Jt(e,n={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:r=!0}=n,a=[];for(let o of e)switch(o.kind){case"curve":{let i=Eo(o,t,r);i&&a.push(i);break}case"point":{let i=ho(o,r);i&&a.push(i);break}default:{let l=o;F().warn(`Skipping unknown display item kind: ${String(l.kind)}`);break}}return a}var po=2;function Eo(e,n,t){if(!n)return F().warn("No rhino3dm instance provided; skipping curve display item."),null;let r=go(e.json,n);if(!r)return null;let a;try{a=yo(r,t)}catch(d){return F().warn("Failed to tessellate curve display item; skipping.",d),null}finally{Me(r)}if(a.length<2)return null;let o=[];for(let d of a)o.push(d.x,d.y,d.z);let i=new so;i.setPositions(o);let l=Qt(e.color,e.opacity),s=new lo({color:l.color}),c=s;c.linewidth=e.width??po,c.transparent=l.transparent,c.opacity=l.opacity;let u=new io(i,s);return u.computeLineDistances(),u.name=e.name,u.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},u}function ho(e,n){let{position:t}=e;if(!t||typeof t.X!="number"||!Number.isFinite(t.X)||typeof t.Y!="number"||!Number.isFinite(t.Y)||typeof t.Z!="number"||!Number.isFinite(t.Z))return F().warn(`Skipping point display item with missing or non-finite position (id: ${String(e.id)}).`),null;let{x:r,y:a,z:o}=Ve(t.X,t.Y,t.Z,n),i=new te.BufferGeometry;i.setAttribute("position",new te.Float32BufferAttribute([r,a,o],3));let l=new te.PointsMaterial({...Qt(e.color,e.opacity),size:6,sizeAttenuation:!1}),s=new te.Points(i,l);return s.name=e.name,s.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},s}function Me(e){e?.delete?.()}function go(e,n){try{let t=JSON.parse(e),r=n.CommonObject.decode(t);return r&&typeof r.pointAt=="function"?r:(Me(r),F().warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return F().warn("Failed to decode curve display item JSON:",t),null}}function yo(e,n){let t=bo(e,n);return t||To(e,n)}function bo(e,n){if(!e.isPolyline())return null;let t=e.tryGetPolyline(),r=Array.isArray(t)?t[1]:t;if(!r||typeof r.count!="number"||r.count<2)return Me(r),null;let a=[];for(let o=0;o<r.count;o++){let i=r.get(o),{x:l,y:s,z:c}=Ve(i[0],i[1],i[2],n);a.push(new te.Vector3(l,s,c))}return Me(r),a}function To(e,n){let t=e.domain,r=t[0],o=t[1]-r,i=d=>{let E=e.pointAt(d),{x:T,y:v,z:y}=Ve(E[0],E[1],E[2],n);return new te.Vector3(T,v,y)},l=Ro(e),s=r,c=i(r),u=[c];for(let d=0;d<Zt;d++){let E=r+o*(d+1)/Zt,T=i(E);nt(s,c,E,T,i,l,mo,u),u.push(T),s=E,c=T}return u}function nt(e,n,t,r,a,o,i,l){if(i<=0)return;let s=(e+t)/2,c=a(s),u=vo(c,n,r),d=xo(n,c,r);u<=o&&d<=fo||(nt(e,n,s,c,a,o,i-1,l),l.push(c),nt(s,c,t,r,a,o,i-1,l))}function Ro(e){let n=e.getBoundingBox(),t=n.min,r=n.max;Me(n);let a=Math.hypot(r[0]-t[0],r[1]-t[1],r[2]-t[2]);return Math.max(a*uo,1e-6)}function xo(e,n,t){let r=n.x-e.x,a=n.y-e.y,o=n.z-e.z,i=t.x-n.x,l=t.y-n.y,s=t.z-n.z,c=Math.sqrt(r*r+a*a+o*o),u=Math.sqrt(i*i+l*l+s*s);if(c===0||u===0)return 0;let d=r*i+a*l+o*s,E=Math.max(-1,Math.min(1,d/(c*u)));return Math.acos(E)}function vo(e,n,t){let r=t.x-n.x,a=t.y-n.y,o=t.z-n.z,i=r*r+a*a+o*o;if(i===0)return e.distanceTo(n);let l=e.x-n.x,s=e.y-n.y,c=e.z-n.z,u=Math.max(0,Math.min(1,(l*r+s*a+c*o)/i)),d=l-r*u,E=s-a*u,T=c-o*u;return Math.sqrt(d*d+E*E+T*T)}function Qt(e,n){let t=n??1;return{color:new te.Color(e??co),transparent:t<1,opacity:t}}import{inflateSync as wo}from"fflate";var en=1096174675,Mo=1515605075,tn=3,nn=1,ot=1,Co=2,Ho=4,Ao=8,So=16,Ai=0,Do=1,rn=12,on=56,Lo=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;function at(e){let n=it(e),t;n.isFloat32?t=n.vertexData:n.deltaEncoded?t=Vo(n.vertexData):t=n.vertexData;let r=n.indexData;return n.deltaEncoded&&(r=r instanceof Uint16Array?zo(r):Go(r)),_o(r,n.vertexCount),{metadata:n.metadata,flags:n.flags,vertices:t,indices:r,origin:n.origin,scale:n.scale,uvs:n.uvs,colors:n.colors}}function it(e){if(!Lo)throw new be("SLVA parsing requires a little-endian host: the zero-copy geometry readers view the wire bytes in host byte order.",ye.ENVIRONMENT_ERROR);let n=Fo(Po(e)),t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.byteLength<rn)throw X("Blob too small to contain SLVA header.",{expectedBytes:rn,availableBytes:n.byteLength});let r=0,a=t.getUint32(r,!0);if(r+=4,a!==en)throw X(`Invalid SLVA magic: 0x${a.toString(16)}`,{expectedMagic:`0x${en.toString(16)}`,actualMagic:`0x${a.toString(16)}`});let o=t.getUint32(r,!0);if(r+=4,o<nn||o>tn)throw X(`Unsupported SLVA version: ${o}`,{minSupportedVersion:nn,maxSupportedVersion:tn,actualVersion:o});let i=t.getUint32(r,!0);if(r+=4,r+i>n.byteLength)throw X("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:n.byteLength-r,offset:r});let l=n.subarray(r,r+i);r+=i;let s;try{s=JSON.parse(Bo(l))}catch(I){throw X(`Failed to parse metadata JSON: ${I instanceof Error?I.message:String(I)}`,{metadataLen:i})}if(r+on>n.byteLength)throw X("Insufficient data to read geometry header.",{expectedBytes:on,availableBytes:n.byteLength-r,offset:r});let c=t.getUint32(r,!0);r+=4;let u=t.getFloat64(r,!0);r+=8;let d=t.getFloat64(r,!0);r+=8;let E=t.getFloat64(r,!0);r+=8;let T=t.getFloat64(r,!0);r+=8;let v=t.getFloat64(r,!0);r+=8;let y=t.getFloat64(r,!0);r+=8;let m=t.getUint32(r,!0);r+=4;let g=(c&ot)!==0,R=(c&Ho)!==0,x=m*3,p=x*(g?4:2);if(r+p>n.byteLength)throw X("Insufficient data to read vertices.",{expectedBytes:p,availableBytes:n.byteLength-r,offset:r,useFloat32:g,vertexCount:m});let f=n.byteOffset+r,h;if(g?h=sn(n.buffer,f,x):R?h=rt(n.buffer,f,x):h=ko(n.buffer,f,x),r+=p,r+4>n.byteLength)throw X("Insufficient data to read index count.",{expectedBytes:4,availableBytes:n.byteLength-r,offset:r});let b=t.getUint32(r,!0);r+=4;let C=(c&Co)!==0,L=b*(C?2:4);if(r+L>n.byteLength)throw X("Insufficient data to read indices.",{expectedBytes:L,availableBytes:n.byteLength-r,offset:r,indexCount:b,useUint16Indices:C});let P=C?rt(n.buffer,n.byteOffset+r,b):Uo(n.buffer,n.byteOffset+r,b);r+=L;let k=null;if((c&Ao)!==0){let I=Oo(n,t,r,m,R);k=I.uvs,r=I.offset}let O=null;return(c&So)!==0&&(O=Io(n,r,m,R)),{metadata:s,flags:c,vertexData:h,indexData:P,isFloat32:g,deltaEncoded:R,vertexCount:m,origin:[u,d,E],scale:[T,v,y],uvs:k,colors:O}}var an=36;function Oo(e,n,t,r,a){if(t+an>e.byteLength)throw X("Insufficient data to read UV chunk header.",{expectedBytes:an,availableBytes:e.byteLength-t,offset:t});let o=n.getUint32(t,!0);t+=4;let i=n.getFloat64(t,!0);t+=8;let l=n.getFloat64(t,!0);t+=8;let s=n.getFloat64(t,!0);t+=8;let c=n.getFloat64(t,!0);t+=8;let u=r*2,d=o===Do,E=u*(d?4:2);if(t+E>e.byteLength)throw X("Insufficient data to read UV chunk.",{expectedBytes:E,availableBytes:e.byteLength-t,offset:t,uvFormat:o,vertexCount:r});let T=e.byteOffset+t,v;if(d)v=sn(e.buffer,T,u).slice();else{let y=rt(e.buffer,T,u);v=new Float32Array(u);let m=0,g=0;for(let R=0;R<u;R+=2)a?(m=m+ie(y[R])&65535,g=g+ie(y[R+1])&65535):(m=y[R],g=y[R+1]),v[R]=i+m*s,v[R+1]=l+g*c}return{uvs:v,offset:t+E}}function Io(e,n,t,r){let a=t*3;if(n+a>e.byteLength)throw X("Insufficient data to read vertex-color chunk.",{expectedBytes:a,availableBytes:e.byteLength-n,offset:n,vertexCount:t});let o=e.subarray(n,n+a);if(!r)return o.slice();let i=new Uint8Array(a),l=0,s=0,c=0;for(let u=0;u<a;u+=3)l=l+ie(o[u])&255,s=s+ie(o[u+1])&255,c=c+ie(o[u+2])&255,i[u]=l,i[u+1]=s,i[u+2]=c;return i}function Po(e){return typeof e=="string"?ft(e):e instanceof Uint8Array?e:new Uint8Array(e)}function Fo(e){if(e.byteLength<8)return e;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==Mo)return e;let t=n.getUint32(4,!0),r=e.subarray(8),a=Math.max(r.byteLength*1032+1024,1<<20);if(t>a)throw X("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:r.byteLength,maxPlausibleLen:a});let o;try{o=wo(r,{out:new Uint8Array(t+1)})}catch(i){throw X(`Failed to inflate SLVZ blob: ${i instanceof Error?i.message:String(i)}`,{uncompressedLen:t,deflatedBytes:r.byteLength})}if(o.byteLength!==t)throw X("SLVZ payload inflated to a different size than the header declares.",{declaredLen:t,actualLen:o.byteLength,deflatedBytes:r.byteLength});return o}function Bo(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 be("No UTF-8 decoder available in this environment.",ye.INVALID_STATE)}function ko(e,n,t){if(t===0)return new Int16Array(0);if(n%2===0)return new Int16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Int16Array(r.buffer)}function sn(e,n,t){if(t===0)return new Float32Array(0);if(n%4===0)return new Float32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Float32Array(r.buffer)}function rt(e,n,t){if(t===0)return new Uint16Array(0);if(n%2===0)return new Uint16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Uint16Array(r.buffer)}function Uo(e,n,t){if(t===0)return new Uint32Array(0);if(n%4===0)return new Uint32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Uint32Array(r.buffer)}function _o(e,n){if(e.length!==0&&!(e instanceof Uint16Array&&n>65535)){for(let t=0;t<e.length;t++)if(e[t]>=n)throw X("Index out of range of vertexCount.",{indexPosition:t,indexValue:e[t],vertexCount:n})}}function ie(e){return e>>>1^-(e&1)}function Vo(e){let n=new Int16Array(e.length),t=0,r=0,a=0;for(let o=0;o<e.length;o+=3)t=t+ie(e[o])<<16>>16,r=r+ie(e[o+1])<<16>>16,a=a+ie(e[o+2])<<16>>16,n[o]=t,n[o+1]=r,n[o+2]=a;return n}function zo(e){let n=new Uint16Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+ie(e[r])&65535,n[r]=t;return n}function Go(e){let n=new Uint32Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+ie(e[r])>>>0,n[r]=t;return n}function X(e,n){return new be(e,ye.VALIDATION_ERROR,{context:n})}import*as V from"three";var ln=256*1024*1024,ze=1024,ue=new Map,st=0;function cn(e,n){let t=2166136261,r=a=>{t^=a,t=Math.imul(t,16777619)};for(let a=0;a<n.length;a++)r(n.charCodeAt(a));for(let a of e){if(!a){r(57005);continue}let o=a.byteLength;if(r(o),(a.byteOffset&3)===0&&(o&3)===0){let i=new Uint32Array(a.buffer,a.byteOffset,o>>2),l=Math.min(ze,i.length);for(let s=0;s<l;s++)r(i[s]);for(let s=Math.max(l,i.length-ze);s<i.length;s++)r(i[s])}else{let i=new Uint8Array(a.buffer,a.byteOffset,o),l=Math.min(ze*4,i.length);for(let s=0;s<l;s++)r(i[s]);for(let s=Math.max(l,i.length-ze*4);s<i.length;s++)r(i[s])}}return`${(t>>>0).toString(36)}:${e.length}`}function No(e){let n=e.index?.array.byteLength??0;for(let t of Object.values(e.attributes))n+=t.array.byteLength;return n}function Ge(e){let n=ue.get(e);if(n)return ue.delete(e),ue.set(e,n),n.geometry}function Ne(e,n){let t=No(n);if(!(t>ln||(n.userData[Se]=!0,ue.get(e))))for(ue.set(e,{geometry:n,bytes:t}),st+=t;st>ln&&ue.size>1;){let a=ue.keys().next().value,o=ue.get(a);ue.delete(a),st-=o.bytes,delete o.geometry.userData[Se],o.geometry.dispose()}}function jo(e){let{isFloat32:n,deltaEncoded:t,origin:r,scale:a,uvs:o,colors:i,jobs:l}=e,s=m=>m>>>1^-(m&1),c;if(n)c=e.vertexData;else{let m;if(t){let h=e.vertexData;m=new Int16Array(h.length);let b=0,C=0,H=0;for(let L=0;L<h.length;L+=3)b=b+s(h[L])<<16>>16,C=C+s(h[L+1])<<16>>16,H=H+s(h[L+2])<<16>>16,m[L]=b,m[L+1]=C,m[L+2]=H}else m=e.vertexData;c=new Float32Array(m.length);let g=r[0],R=r[1],x=r[2],M=a[0],p=a[1],f=a[2];for(let h=0;h<m.length;h+=3)c[h]=g+(m[h]+32767)*M,c[h+1]=R+(m[h+1]+32767)*p,c[h+2]=x+(m[h+2]+32767)*f}let u;if(t){let m=e.indexData;if(m instanceof Uint16Array){let g=new Uint16Array(m.length),R=0;for(let x=0;x<m.length;x++)R=R+s(m[x])&65535,g[x]=R;u=g}else{let g=new Uint32Array(m.length),R=0;for(let x=0;x<m.length;x++)R=R+s(m[x])>>>0,g[x]=R;u=g}}else u=e.indexData;let d=c.length/3;for(let m=0;m<u.length;m++)if(u[m]>=d)throw new Error(`Index ${u[m]} out of range of vertexCount ${d}`);let E=1024,T=(m,g)=>{let R=2166136261,x=M=>{R^=M,R=Math.imul(R,16777619)};for(let M=0;M<g.length;M++)x(g.charCodeAt(M));for(let M of m){if(!M){x(57005);continue}let p=M.byteLength;if(x(p),(M.byteOffset&3)===0&&(p&3)===0){let f=new Uint32Array(M.buffer,M.byteOffset,p>>2),h=Math.min(E,f.length);for(let b=0;b<h;b++)x(f[b]);for(let b=Math.max(h,f.length-E);b<f.length;b++)x(f[b])}else{let f=new Uint8Array(M.buffer,M.byteOffset,p),h=Math.min(E*4,f.length);for(let b=0;b<h;b++)x(f[b]);for(let b=Math.max(h,f.length-E*4);b<f.length;b++)x(f[b])}}return`${(R>>>0).toString(36)}:${m.length}`},v=(m,g)=>{let R=[],x=m;for(let M of g){x+=`|${M.vertexStart},${M.vertexCount},${M.indexStart},${M.indexCount}`;let p=M.vertexStart*3,f=p+M.vertexCount*3;R.push(c.subarray(p,f)),R.push(u.subarray(M.indexStart,M.indexStart+M.indexCount)),R.push(o?o.subarray(M.vertexStart*2,(M.vertexStart+M.vertexCount)*2):null),R.push(i?i.subarray(p,f):null)}return T(R,x)},y=[];for(let m of l){let g=0,R=0;for(let H of m.windows)g+=H.vertexCount,R+=H.indexCount;let x=new Float32Array(g*3),M=new Uint32Array(R),p=o?new Float32Array(g*2):null,f=i?new Uint8Array(g*3):null,h=0,b=0;for(let H of m.windows){let L=H.vertexStart*3;x.set(c.subarray(L,L+H.vertexCount*3),h*3),p&&o&&p.set(o.subarray(H.vertexStart*2,(H.vertexStart+H.vertexCount)*2),h*2),f&&i&&f.set(i.subarray(L,L+H.vertexCount*3),h*3);let P=H.vertexStart,k=H.vertexStart+H.vertexCount,O=h-H.vertexStart;for(let I=0;I<H.indexCount;I++){let S=u[H.indexStart+I];if(S<P||S>=k)throw new Error(`Index ${S} outside vertex window [${P}, ${k})`);M[b+I]=S+O}h+=H.vertexCount,b+=H.indexCount}let C=new Float32Array(g*3);for(let H=0;H<M.length;H+=3){let L=M[H]*3,P=M[H+1]*3,k=M[H+2]*3,O=x[k]-x[P],I=x[k+1]-x[P+1],S=x[k+2]-x[P+2],D=x[L]-x[P],G=x[L+1]-x[P+1],j=x[L+2]-x[P+2],$=I*j-S*G,U=S*D-O*j,Q=O*G-I*D;C[L]+=$,C[L+1]+=U,C[L+2]+=Q,C[P]+=$,C[P+1]+=U,C[P+2]+=Q,C[k]+=$,C[k+1]+=U,C[k+2]+=Q}for(let H=0;H<C.length;H+=3){let L=C[H],P=C[H+1],k=C[H+2],O=Math.sqrt(L*L+P*P+k*k)||1;C[H]=L/O,C[H+1]=P/O,C[H+2]=k/O}y.push({key:v(m.kind,m.windows),positions:x,normals:C,indices:M,uvs:p,colors:f})}return y}function un(){return[`const assemble = ${jo.toString()};`,"self.onmessage = (event) => {"," const { id, input } = event.data;"," try {"," const geometries = assemble(input);"," const transfer = [];"," for (const g of geometries) {"," transfer.push(g.positions.buffer, g.normals.buffer, g.indices.buffer);"," if (g.uvs) transfer.push(g.uvs.buffer);"," if (g.colors) transfer.push(g.colors.buffer);"," }"," self.postMessage({ id, geometries }, transfer);"," } catch (error) {"," self.postMessage({ id, error: String((error && error.message) || error) });"," }","};"].join(`
|
|
112
|
+
`)}async function Vi(e,n){let{debug:t=!1}=n??{},r=t?performance.now():0,a,o=performance.now();try{a=JSON.parse(e)}catch(l){return F().error("Error parsing mesh batch envelope JSON:",l),[]}let i=performance.now()-o;return await lt(a,n,{parseTime:i,perfStart:r})}async function lt(e,n,t){let{mergeByMaterial:r=!0,applyTransforms:a=!0,debug:o=!1,material:i}=n??{},{parseTime:l=0,perfStart:s=o?performance.now():0}=t??{};if(!e.compressedData)return[];let c=await En(e.compressedData,{mergeByMaterial:r,applyTransforms:a,debug:o,material:i,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}});if(c)return c;let u=performance.now(),d=at(e.compressedData),E=performance.now()-u,T=o?ra(e.compressedData):0;return dn(d,{mergeByMaterial:r,applyTransforms:a,debug:o,material:i,parseTime:l,decodeTime:E,perfStart:s,blobBytes:T,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}async function zi(e,n){let{mergeByMaterial:t=!0,applyTransforms:r=!0,debug:a=!1,material:o}=n??{},i=a?performance.now():0,l=await En(e,{mergeByMaterial:t,applyTransforms:r,debug:a,material:o});if(l)return l;let s=performance.now(),c=at(e),u=performance.now()-s,d=e.byteLength;return dn(c,{mergeByMaterial:t,applyTransforms:r,debug:a,material:o,parseTime:0,decodeTime:u,perfStart:i,blobBytes:d})}function dn(e,n){let{mergeByMaterial:t,applyTransforms:r,debug:a,material:o,parseTime:i,decodeTime:l,perfStart:s,blobBytes:c,fallback:u}=n,d=e.metadata.materials??u?.materials??[],E=e.metadata.groups??u?.groups??[],T=u?.sourceComponentId??e.metadata.sourceComponentId,v=(e.flags&ot)!==0;mn(E,d.length,e.vertices.length/3,e.indices.length);let y=v?$o(e.vertices,r):Wo(e.vertices,e.origin,e.scale,r);if(a){let M=e.vertices.byteLength+e.indices.byteLength;F().debug("Mesh Batch Stats:"),F().debug(` Materials: ${d.length} | Groups: ${E.length}`),F().debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),F().debug(` Format: ${v?"float32":"int16 quantized"}`),F().debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(M/1024/1024).toFixed(2)} MB`)}let m=performance.now(),g=d.map(M=>hn(M,{vertexColors:e.colors!=null,appearance:o})),R=[];for(let M of E)if(t&&M.meshes.length>1){let p=ta(M,y,e.indices,g,e.uvs,e.colors);p.userData.sourceComponentId=T??null,R.push(p)}else{let p=na(M,y,e.indices,g,e.uvs,e.colors);for(let f of p)f.userData.sourceComponentId=T??null;R.push(...p)}let x=performance.now()-m;if(a){let M=performance.now()-s;F().debug("Performance:"),i>0&&F().debug(` Parse JSON: ${i.toFixed(2)}ms`),F().debug(` Decode binary: ${l.toFixed(2)}ms`),F().debug(` Create Meshes: ${x.toFixed(2)}ms`),F().debug(` Total: ${M.toFixed(2)}ms`)}return Promise.resolve(R)}function Ce(e,n){return new be(e,ye.VALIDATION_ERROR,{context:n})}function mn(e,n,t,r){for(let a of e){if(!Number.isInteger(a.materialId)||a.materialId<0||a.materialId>=n)throw Ce("Group materialId out of range of the materials array.",{materialId:a.materialId,materialCount:n});for(let o of a.meshes){let i={vertexStart:o.vertexStart,vertexCount:o.vertexCount,indexStart:o.indexStart,indexCount:o.indexCount};for(let[l,s]of Object.entries(i))if(!Number.isInteger(s)||s<0)throw Ce(`Mesh metadata field "${l}" must be a non-negative integer.`,{meshName:o.name,field:l,value:s});if(o.vertexStart+o.vertexCount>t)throw Ce("Mesh vertex window exceeds the batch vertex buffer.",{meshName:o.name,vertexStart:o.vertexStart,vertexCount:o.vertexCount,totalVertexCount:t});if(o.indexStart+o.indexCount>r)throw Ce("Mesh index window exceeds the batch index buffer.",{meshName:o.name,indexStart:o.indexStart,indexCount:o.indexCount,totalIndexCount:r})}}}function fn(e,n){return Ce("Index references a vertex outside its mesh's vertex window.",{meshName:n.name,indexValue:e,vertexStart:n.vertexStart,vertexCount:n.vertexCount})}function pn(e,n,t,r,a,o){let i=[],l=e;for(let s of n){l+=`|${s.vertexStart},${s.vertexCount},${s.indexStart},${s.indexCount}`;let c=s.vertexStart*3,u=c+s.vertexCount*3;i.push(t.subarray(c,u)),i.push(r.subarray(s.indexStart,s.indexStart+s.indexCount)),i.push(a?a.subarray(s.vertexStart*2,(s.vertexStart+s.vertexCount)*2):null),i.push(o?o.subarray(c,u):null)}return cn(i,l)}function Wo(e,n,t,r){let a=new Float32Array(e.length),o=n[0],i=n[1],l=n[2],s=t[0],c=t[1],u=t[2];for(let d=0;d<e.length;d+=3)a[d]=o+(e[d]+32767)*s,a[d+1]=i+(e[d+1]+32767)*c,a[d+2]=l+(e[d+2]+32767)*u;return a}function $o(e,n){return e}var qo=5e4,he,He=new Map,Yo=1;function Xo(){if(he!==void 0)return he;if(typeof Worker>"u"||typeof Blob>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return he=null,null;try{let e=URL.createObjectURL(new Blob([un()],{type:"text/javascript"})),n=new Worker(e);n.onmessage=t=>{let{id:r,geometries:a,error:o}=t.data,i=He.get(r);i&&(He.delete(r),a?i.resolve(a):i.reject(new Error(o??"mesh assembly failed in worker")))},n.onerror=()=>{for(let t of He.values())t.reject(new Error("mesh assembly worker crashed"));He.clear(),n.terminate(),he=null},he=n}catch{he=null}return he}function Ko(e,n,t){return new Promise((r,a)=>{let o=Yo++;He.set(o,{resolve:r,reject:a}),e.postMessage({id:o,input:n},t)})}async function En(e,n){if(typeof Worker>"u")return null;let t=it(e);if(t.indexData.length/3<qo)return null;let r=Xo();if(!r)return null;let a=t.metadata.materials??n.fallback?.materials??[],o=t.metadata.groups??n.fallback?.groups??[],i=n.fallback?.sourceComponentId??t.metadata.sourceComponentId;mn(o,a.length,t.vertexCount,t.indexData.length);let l=m=>({vertexStart:m.vertexStart,vertexCount:m.vertexCount,indexStart:m.indexStart,indexCount:m.indexCount}),s=[],c=[];for(let m of o)if(n.mergeByMaterial&&m.meshes.length>1)s.push({kind:"merged",windows:m.meshes.map(l)}),c.push({kind:"merged",group:m});else for(let g of m.meshes)s.push({kind:"single",windows:[l(g)]}),c.push({kind:"single",group:m,meshMeta:g});let u=t.vertexData.slice(),d=t.indexData.slice(),E=[u.buffer,d.buffer];t.uvs&&E.push(t.uvs.buffer),t.colors&&E.push(t.colors.buffer);let T;try{T=await Ko(r,{vertexData:u,isFloat32:t.isFloat32,deltaEncoded:t.deltaEncoded,origin:t.origin,scale:t.scale,indexData:d,uvs:t.uvs,colors:t.colors,jobs:s},E)}catch(m){return F().warn("Mesh assembly worker failed; falling back to main-thread parse.",m),null}if(T.length!==s.length)return null;let v=a.map(m=>hn(m,{vertexColors:t.colors!=null,appearance:n.material})),y=[];for(let m=0;m<T.length;m++){let g=T[m],R=c[m],x=Ge(g.key);x||(x=new V.BufferGeometry,x.setAttribute("position",new V.BufferAttribute(g.positions,3)),x.setAttribute("normal",new V.BufferAttribute(g.normals,3)),x.setIndex(new V.BufferAttribute(g.indices,1)),g.uvs&&x.setAttribute("uv",new V.BufferAttribute(g.uvs,2)),g.colors&&x.setAttribute("color",new V.BufferAttribute(g.colors,3,!0)),Ne(g.key,x));let M=R.kind==="merged"?gn(x,R.group,v):yn(x,R.meshMeta,R.group,v);M.userData.sourceComponentId=i??null,y.push(M)}return n.debug&&F().debug(`Mesh batch assembled off-thread: ${y.length} meshes, ${t.indexData.length/3} triangles`),y}var Zo=.5,Jo=.5,Qo=.3;function hn(e,n){let t=Rt(e.color),r=n?.vertexColors??!1,a=n?.appearance,o=new V.MeshPhysicalMaterial({color:t,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,vertexColors:r,side:a?.cullBackfaces?V.FrontSide:V.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0});return a?.envMapIntensity!=null&&(o.envMapIntensity=a.envMapIntensity),e.metalness>Zo&&(o.clearcoat=Jo,o.clearcoatRoughness=Qo),r&&ea(o),e.map&&Xt(o,e.map),o}function ea(e){e.onBeforeCompile=n=>{n.vertexShader=n.vertexShader.replace("#include <color_vertex>",`#include <color_vertex>
|
|
113
|
+
#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
|
|
114
|
+
vColor.rgb = mix(
|
|
115
|
+
vColor.rgb / 12.92,
|
|
116
|
+
pow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),
|
|
117
|
+
step( vec3( 0.04045 ), vColor.rgb )
|
|
118
|
+
);
|
|
119
|
+
#endif`)}}function ta(e,n,t,r,a=null,o=null){let i=pn("merged",e.meshes,n,t,a,o),l=Ge(i);if(!l){let s=0,c=0;for(let m of e.meshes)s+=m.vertexCount,c+=m.indexCount;let u=new Float32Array(s*3),d=new Uint32Array(c),E=a?new Float32Array(s*2):null,T=o?new Uint8Array(s*3):null,v=0,y=0;for(let m of e.meshes){let g=m.vertexStart*3,R=m.vertexCount*3;if(u.set(n.subarray(g,g+R),v*3),E&&a){let h=m.vertexStart*2;E.set(a.subarray(h,h+m.vertexCount*2),v*2)}T&&o&&T.set(o.subarray(g,g+R),v*3);let x=t.subarray(m.indexStart,m.indexStart+m.indexCount),M=v-m.vertexStart,p=m.vertexStart,f=m.vertexStart+m.vertexCount;for(let h=0;h<x.length;h++){let b=x[h];if(b<p||b>=f)throw fn(b,m);d[y+h]=b+M}v+=m.vertexCount,y+=m.indexCount}l=new V.BufferGeometry,l.setAttribute("position",new V.BufferAttribute(u,3)),l.setIndex(new V.BufferAttribute(d,1)),E&&l.setAttribute("uv",new V.BufferAttribute(E,2)),T&&l.setAttribute("color",new V.BufferAttribute(T,3,!0)),l.computeVertexNormals(),Ne(i,l)}return gn(l,e,r)}function gn(e,n,t){let r=new V.Mesh(e,t[n.materialId]),a=n.meshes[0],o=n.meshes.map(i=>i.name).filter(i=>i&&i.length>0);return r.name=o.length>0?o[0]:`merged_material_${n.materialId}`,r.castShadow=!0,r.receiveShadow=!0,r.userData={source:"compute",name:r.name,layer:a?.layer??"",originalIndex:a?.originalIndex??0,metadata:a?.metadata??{},mergedFrom:n.meshes.slice(1).map(i=>({name:i.name,layer:i.layer,originalIndex:i.originalIndex}))},r}function na(e,n,t,r,a=null,o=null){let i=[];for(let l of e.meshes){let s=l.vertexStart*3,c=l.vertexCount*3,u=pn("single",[l],n,t,a,o),d=Ge(u);if(!d){let E=n.slice(s,s+c),T=t.subarray(l.indexStart,l.indexStart+l.indexCount),v=new Uint32Array(T.length),y=l.vertexStart,m=l.vertexStart+l.vertexCount;for(let g=0;g<T.length;g++){let R=T[g];if(R<y||R>=m)throw fn(R,l);v[g]=R-y}if(d=new V.BufferGeometry,d.setAttribute("position",new V.BufferAttribute(E,3)),d.setIndex(new V.BufferAttribute(v,1)),a){let g=l.vertexStart*2,R=a.slice(g,g+l.vertexCount*2);d.setAttribute("uv",new V.BufferAttribute(R,2))}if(o){let g=o.slice(s,s+c);d.setAttribute("color",new V.BufferAttribute(g,3,!0))}d.computeVertexNormals(),Ne(u,d)}i.push(yn(d,l,e,r))}return i}function yn(e,n,t,r){let a=new V.Mesh(e,r[t.materialId]);return a.name=n.name,a.userData={source:"compute",name:n.name,layer:n.layer??"",originalIndex:n.originalIndex,metadata:n.metadata??{}},a.castShadow=!0,a.receiveShadow=!0,a}function ra(e){return Math.floor(e.length*3/4)}var bn={Angstroms:1e-10,Nanometers:1e-9,Microns:1e-6,Millimeters:.001,Centimeters:.01,Decimeters:.1,Meters:1,Dekameters:10,Hectometers:100,Kilometers:1e3,Megameters:1e6,Gigameters:1e9,Microinches:254e-10,Mils:254e-7,Inches:.0254,Feet:.3048,Yards:.9144,Miles:1609.344,NauticalMiles:1852},oa="Display",aa="DisplayBatch";function ia(e){let n=e.split(".");return n.includes(oa)||n.includes(aa)}var Tn=new Set;async function qi(e,n){let t=performance.now(),r=[],{allowScaling:a=!0,allowAutoPosition:o=!0,rhino:i,debug:l=!1,parsing:s={}}=n??{};try{let c=a?sa(e.modelunits):1;return await la(e,r,c,s,i,l),o&&ma(r),r}catch(c){throw fa(c,r),c}finally{l&&Ea(t)}}function sa(e){let n=bn[e];return n!==void 0?n:(Tn.has(e)||(Tn.add(e),F().warn(`Unknown Rhino model unit "${e}" \u2014 geometry will not be scaled (factor 1). Known units: ${Object.keys(bn).join(", ")}.`)),1)}async function la(e,n,t,r,a,o){for(let i of e.values){let l=i.InnerTree;for(let s in l){let c=l[s];c&&await ca(c,n,t,r,a,o)}}}async function ca(e,n,t,r,a,o){for(let i of e){if(!ia(i.type))continue;let l={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...r},s=ua(i.data);if(!s){F().error("Error parsing display batch envelope: invalid JSON");continue}let c=await lt(s,l),u=Jt(s.items,{rhino:a,applyTransforms:l.applyTransforms}),d=[...c,...u];if(t!==1)for(let E of d)E.scale.set(t,t,t);n.push(...d),o&&F().debug(`Extracted ${c.length} meshes and ${u.length} items from batch`)}}function ua(e){return typeof e=="string"?da(e):e}function da(e){try{return JSON.parse(e)}catch{return}}function ma(e){if(e.length===0)return;let n=$e(e);xt(e,n.min.z,"z")}function fa(e,n){F().error("An unexpected error occurred:",e),pa(n)}function pa(e){for(let n of e){let t=n;t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(r=>r.dispose()):t.material.dispose())}}function Ea(e){let n=performance.now()-e;F().info("Time to process meshes:",`${n.toFixed(2)}ms`)}export{Ln as a,ba as b,Rt as c,xt as d,$e as e,vt as f,wt as g,Mt as h,xe as i,Qe as j,Er as k,La as l,Vt as m,zt as n,Pe as o,Gt as p,jt as q,Pr as r,qt as s,Fr as t,Yt as u,Za as v,qr as w,pi as x,hi as y,Jt as z,en as A,Mo as B,tn as C,nn as D,ot as E,Co as F,Ho as G,Ao as H,So as I,Ai as J,Do as K,at as L,Vi as M,lt as N,zi as O,bn as P,qi as Q};
|
|
120
|
+
//# sourceMappingURL=chunk-NVMSD4CC.js.map
|