@flyfish-dev/cad-viewer 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +1 -1
- package/README.md +20 -6
- package/README.zh-CN.md +24 -6
- package/dist/cad-viewer.es.js +403 -392
- package/dist/cad-viewer.es.js.map +1 -1
- package/dist/cad-viewer.umd.cjs +4 -4
- package/dist/cad-viewer.umd.cjs.map +1 -1
- package/dist/types/core/types.d.ts +11 -0
- package/dist/types/core/types.d.ts.map +1 -1
- package/dist/types/loaders/dwf/DwfLoader.d.ts.map +1 -1
- package/package.json +5 -4
package/dist/cad-viewer.umd.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
(function(g,C){typeof exports=="object"&&typeof module<"u"?C(exports,require("dwf-viewer")):typeof define=="function"&&define.amd?define(["exports","dwf-viewer"],C):(g=typeof globalThis<"u"?globalThis:g||self,C(g.LightweightCadViewer={},g.DwfViewerPackage))})(this,function(g,C){"use strict";var fr=Object.defineProperty;var dr=(g,C,I)=>C in g?fr(g,C,{enumerable:!0,configurable:!0,writable:!0,value:I}):g[C]=I;var d=(g,C,I)=>dr(g,typeof C!="symbol"?C+"":C,I);var I=typeof document<"u"?document.currentScript:null;async function W(e){if(e.buffer instanceof Uint8Array)return e.buffer;if(e.buffer instanceof ArrayBuffer)return new Uint8Array(e.buffer);if(e.file)return new Uint8Array(await e.file.arrayBuffer());throw new Error("CadLoadInput requires a File, ArrayBuffer, or Uint8Array.")}function ne(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function R(e){var i;const t=e.fileName??((i=e.file)==null?void 0:i.name)??"",r=t.lastIndexOf(".");return r>=0?t.slice(r+1).toLowerCase():""}function L(e,t){const r=R(e);if(r==="dwg")return"dwg";if(r==="dxf")return"dxf";if(r==="dwfx")return"dwfx";if(r==="xps")return"xps";if(r==="dwf")return"dwf";if(t&&t.byteLength>=6){const i=Ct(t.slice(0,6));if(/^AC10/.test(i))return"dwg";if(t[0]===80&&t[1]===75)return"dwfx";const s=Ct(t.slice(0,Math.min(t.byteLength,2048))).toUpperCase();if(s.includes("SECTION")&&s.includes("ENTITIES"))return"dxf";if(s.includes("DWF"))return"dwf"}return"unknown"}function Ct(e){return Array.from(e,t=>t>=32&&t<=126?String.fromCharCode(t):" ").join("")}class kt{constructor(t=[]){d(this,"loaders",[]);for(const r of t)this.register(r)}register(t){const r=this.loaders.findIndex(i=>i.id===t.id);return r>=0?this.loaders.splice(r,1,t):this.loaders.push(t),this}unregister(t){const r=this.loaders.findIndex(i=>i.id===t);return r>=0&&this.loaders.splice(r,1),this}list(){return[...this.loaders]}async detect(t){const r=await W(t),i=L(t,r),s=this.loaders.find(o=>o.formats.includes(i)&&o.accepts(t,r));if(s)return{loader:s,bytes:r,format:i};const n=this.loaders.find(o=>o.accepts(t,r));if(n)return{loader:n,bytes:r,format:i};throw new Error(`No CAD loader registered for ${i==="unknown"?"this file":i.toUpperCase()}.`)}async load(t,r={}){const{loader:i,bytes:s}=await this.detect(t);return i.load({...t,buffer:s},r)}}class Pt{constructor(){d(this,"worker");d(this,"sequence",0);d(this,"pending",new Map)}load(t,r,i={}){var l,h;if(!Z())throw new Error("Web Worker is not available in this runtime.");const s=this.ensureWorker(i),n=++this.sequence,o=Math.max(0,Number(i.workerTimeoutMs??0)),a=i.fileName??r.fileName??((l=r.file)==null?void 0:l.name),c=ae(t,r,i);return(h=i.onProgress)==null||h.call(i,{phase:"worker-start",format:"dwg",message:"Dispatching DWG parse to worker…",total:t.byteLength}),new Promise((f,u)=>{var w;if((w=i.signal)!=null&&w.aborted){u(K());return}const p={resolve:f,reject:u,onProgress:i.onProgress,signal:i.signal};o>0&&(p.timer=setTimeout(()=>{this.pending.delete(n),this.resetWorker(),u(new Error(`DWG worker timed out after ${o} ms.`))},o)),i.signal&&(p.abortHandler=()=>{this.pending.delete(n),this.resetWorker(),u(K())},i.signal.addEventListener("abort",p.abortHandler,{once:!0})),this.pending.set(n,p);try{s.postMessage({type:"load",requestId:n,bytes:c,fileName:a,options:St(i)},[c])}catch(N){this.pending.delete(n),q(p),u(N instanceof Error?N:new Error(String(N)))}})}preload(t={}){var n;if(!Z())return Promise.reject(new Error("Web Worker is not available in this runtime."));const r=this.ensureWorker(t),i=++this.sequence,s=Math.max(0,Number(t.workerTimeoutMs??0));return(n=t.onProgress)==null||n.call(t,{phase:"worker-start",format:"dwg",message:"Starting DWG worker warmup…"}),new Promise((o,a)=>{var l;if((l=t.signal)!=null&&l.aborted){a(K());return}const c={resolve:()=>o(),reject:a,onProgress:t.onProgress,signal:t.signal};s>0&&(c.timer=setTimeout(()=>{this.pending.delete(i),this.resetWorker(),a(new Error(`DWG worker warmup timed out after ${s} ms.`))},s)),t.signal&&(c.abortHandler=()=>{this.pending.delete(i),this.resetWorker(),a(K())},t.signal.addEventListener("abort",c.abortHandler,{once:!0})),this.pending.set(i,c);try{r.postMessage({type:"warmup",requestId:i,options:St(t)})}catch(h){this.pending.delete(i),q(c),a(h instanceof Error?h:new Error(String(h)))}})}terminate(){this.resetWorker()}ensureWorker(t){return this.worker||(this.worker=oe(t),this.worker.onmessage=r=>this.handleMessage(r.data),this.worker.onerror=r=>{const i=r.message||"DWG worker failed.";this.rejectAll(new Error(i)),this.resetWorker(!1)},this.worker.onmessageerror=()=>{this.rejectAll(new Error("DWG worker returned a message that could not be cloned.")),this.resetWorker(!1)}),this.worker}handleMessage(t){var s,n;if(t.type==="ready")return;const r=this.pending.get(t.requestId);if(!r)return;if(t.type==="progress"){(s=r.onProgress)==null||s.call(r,t.progress);return}if(this.pending.delete(t.requestId),q(r),t.type==="result"){r.resolve(t.result);return}if(t.type==="warmup-result"){(n=r.onProgress)==null||n.call(r,{phase:"worker-ready",format:"dwg",message:"DWG worker warmup complete.",percent:100,elapsedMs:t.elapsedMs}),r.resolve(void 0);return}const i=new Error(t.error.message);i.name=t.error.name||"DwgWorkerError",t.error.stack&&(i.stack=t.error.stack),r.reject(i)}rejectAll(t){for(const[,r]of this.pending)q(r),r.reject(t);this.pending.clear()}resetWorker(t=!0){var r;t&&this.rejectAll(new Error("DWG worker was terminated.")),(r=this.worker)==null||r.terminate(),this.worker=void 0}}function Z(){return typeof Worker<"u"&&typeof URL<"u"}function oe(e){return e.workerFactory?e.workerFactory():e.workerUrl?new Worker(e.workerUrl,{type:"module",name:"lightweight-cad-dwg-loader"}):new Worker(new URL("/assets/DwgWorker-CuZJ5EUe.js",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:I&&I.tagName.toUpperCase()==="SCRIPT"&&I.src||new URL("cad-viewer.umd.cjs",document.baseURI).href),{type:"module",name:"lightweight-cad-dwg-loader"})}function St(e){return{wasmPath:ce(e.wasmPath),includePaperSpace:e.includePaperSpace,maxInsertDepth:e.maxInsertDepth,keepRaw:!!e.keepRaw}}function ae(e,t,r){return!!t.file||r.transferInputBuffer===!0?ne(e):e.slice().buffer}function q(e){e.timer&&clearTimeout(e.timer),e.signal&&e.abortHandler&&e.signal.removeEventListener("abort",e.abortHandler)}function K(){if(typeof DOMException<"u")return new DOMException("DWG loading was aborted.","AbortError");const e=new Error("DWG loading was aborted.");return e.name="AbortError",e}function ce(e){const t=((e==null?void 0:e.trim())||"/wasm").replace(/\/+$/,"");return t===""?Nt():le(t)?t:t.startsWith("/")?`${Nt()}${t}`:new URL(t,Mt()).href.replace(/\/+$/,"")}function Mt(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"http://localhost/"}function Nt(){return typeof location<"u"&&location.origin?location.origin:new URL(Mt()).origin}function le(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)}class Et{constructor(t={}){d(this,"id","dwg");d(this,"label","DWG / LibreDWG WebAssembly");d(this,"formats",["dwg"]);d(this,"defaults");d(this,"workerClient",new Pt);this.defaults={useWorker:!0,...t}}accepts(t,r){return R(t)==="dwg"?!0:L(t,r)==="dwg"}async load(t,r={}){var o,a;const i={...this.defaults,...r};(o=i.onProgress)==null||o.call(i,{phase:"read",format:"dwg",message:"Reading DWG bytes…"});const s=await W(t),n=t.fileName??((a=t.file)==null?void 0:a.name);if(i.useWorker===!1)throw new Error("DWG main-thread parsing is intentionally not bundled by the default viewer. Keep useWorker enabled, or register a custom DWG loader for non-browser runtimes.");if(!Z())throw new Error("DWG loading requires Web Worker support in this build. Provide a custom loader for this runtime.");try{return await this.workerClient.load(s,t,{...i,fileName:n})}catch(c){throw he(c)?c:fe(c)}}terminateWorker(){this.workerClient.terminate()}preload(t={}){const r={...this.defaults,...t};return r.useWorker===!1?Promise.reject(new Error("DWG preload requires worker mode in the default viewer.")):this.workerClient.preload(r)}}function he(e){return e instanceof Error&&e.name==="AbortError"}function fe(e){const t=e instanceof Error?e.message:String(e);return new Error(`${t} If the worker asset cannot be resolved by your bundler/CDN, pass workerUrl or workerFactory to CadViewer.`)}function st(e){return{format:e.format,sourceName:e.sourceName,units:e.units,header:e.header??{},layers:e.layers??{},blocks:e.blocks??{},entities:e.entities??[],pages:e.pages,metadata:e.metadata??{},warnings:e.warnings??[],raw:e.raw}}function A(e){switch(String(e??"").toUpperCase()){case"LINE":return"line";case"CIRCLE":return"circle";case"ARC":return"arc";case"LWPOLYLINE":case"POLYLINE":case"POLYLINE_2D":case"POLYLINE2D":case"POLYLINE_3D":case"POLYLINE3D":case"LEADER":case"MULTILEADER":return"polyline";case"ELLIPSE":return"ellipse";case"TEXT":case"MTEXT":case"ATTRIB":case"ATTDEF":case"DIMENSION":return"text";case"POINT":return"point";case"INSERT":return"insert";case"SOLID":case"TRACE":case"3DFACE":return"solid";case"HATCH":return"hatch";case"SPLINE":return"spline";case"PATH":case"XPS_PATH":case"DWF_PATH":return"path";case"IMAGE":case"RASTER_IMAGE":case"DWF_IMAGE":return"image";case"VIEWPORT":return"viewport";default:return"unsupported"}}function It(e,t,r={}){const i=t??String(e.type??e.entityType??e.objectName??"UNKNOWN").toUpperCase(),s=r.includeUnknownProperties===!1?{type:i,kind:A(i)}:{...e,type:i,kind:A(i)};r.keepRaw&&(s.raw=e),s.handle=S(e.handle??e.id),s.layer=S(e.layer??e.layerName),s.lineType=S(e.lineType??e.linetype);const n=r.numericColorMode??"auto",o=y(e.color),a=y(e.colorIndex??e.colorNumber??e.aci??e.aciColor??e.color_index);s.colorIndex=a??(n!=="rgb"&&o!==void 0&&Math.abs(o)<=257?o:void 0);const c=e.trueColor??e.true_color??e.truecolor??e.colorRGB??e.colorRgb??e.rgbColor??e.rgb,l=o!==void 0&&o>=0&&o<=16777215&&(n==="rgb"||n==="auto"&&Math.abs(o)>257);s.trueColor=c??(l?o:void 0),(typeof e.color=="string"||typeof e.color=="number")&&(s.color=e.color),s.colorNumber=y(e.colorNumber)??s.colorNumber,s.colorName=S(e.colorName??e.color_name)??s.colorName,s.fillColor=e.fillColor??e.fill_color,s.fillColorIndex=y(e.fillColorIndex??e.fill_color_index??e.fillColorNumber)??s.fillColorIndex,s.opacity=y(e.opacity??e.alpha)??s.opacity,s.lineweight=y(e.lineweight??e.lineWeight),s.isVisible=!(e.isVisible===!1||e.visible===!1),s.startPoint=P(e.startPoint??e.start??e.p0??e.from)??s.startPoint,s.endPoint=P(e.endPoint??e.end??e.p1??e.to)??s.endPoint,s.center=P(e.center??e.centerPoint)??s.center,s.insertionPoint=P(e.insertionPoint??e.position??e.location??e.point??e.basePoint)??s.insertionPoint,s.radius=y(e.radius)??s.radius,s.startAngle=y(e.startAngle??e.start_angle)??s.startAngle,s.endAngle=y(e.endAngle??e.end_angle)??s.endAngle,s.majorAxisEndPoint=P(e.majorAxisEndPoint??e.majorAxis??e.major)??s.majorAxisEndPoint,s.axisRatio=y(e.axisRatio??e.ratio)??s.axisRatio,s.height=y(e.height??e.textHeight)??s.height,s.textHeight=y(e.textHeight??e.height)??s.textHeight,s.rotation=y(e.rotation??e.angle)??s.rotation,s.text=S(e.text??e.value??e.string??e.contents)??s.text,s.name=S(e.name??e.blockName)??s.name,s.blockName=S(e.blockName??e.name)??s.blockName;const h=nt(e.vertices??e.points);h.length>0&&(s.vertices=h);const f=nt(e.controlPoints??e.control_points);f.length>0&&(s.controlPoints=f);const u=nt(e.fitPoints??e.fit_points);return u.length>0&&(s.fitPoints=u),s}function P(e){if(!e||typeof e!="object")return;const t=e,r=Number(t.x??t.X??t[0]),i=Number(t.y??t.Y??t[1]),s=t.z??t.Z??t[2],n=s===void 0?void 0:Number(s);if(!(!Number.isFinite(r)||!Number.isFinite(i)))return Number.isFinite(n)?{x:r,y:i,z:n}:{x:r,y:i}}function nt(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const i=P(r);if(!i)continue;const s=r,n=i,o=y(s.bulge);o!==void 0&&(n.bulge=o);const a=y(s.startWidth??s.start_width);a!==void 0&&(n.startWidth=a);const c=y(s.endWidth??s.end_width);c!==void 0&&(n.endWidth=c),t.push(n)}return t}function _(e){var r;const t={};for(const i of e.entities){const s=String(i.type??"UNKNOWN").toUpperCase();t[s]=(t[s]??0)+1}return{format:e.format,sourceName:e.sourceName,entityCount:e.entities.length,layerCount:Object.keys(e.layers).length,blockCount:Object.keys(e.blocks).length,pageCount:((r=e.pages)==null?void 0:r.length)??0,byType:t,warnings:[...e.warnings]}}function Tt(e,t){t.name&&(e[t.name]=t,e[t.name.toLowerCase()]=t)}function de(e,t){t.name&&(e[t.name]=t,e[t.name.toLowerCase()]=t)}function ue(e){return e!=null&&e.length?e.flatMap(t=>t.entities.map(r=>({...r,pageIndex:t.index}))):[]}function y(e){const t=Number(e);return Number.isFinite(t)?t:void 0}function S(e){if(typeof e!="string"&&typeof e!="number")return;const t=String(e);return t.length>0?t:void 0}function E(){return{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function D(e){return Number.isFinite(e.minX)&&Number.isFinite(e.minY)&&Number.isFinite(e.maxX)&&Number.isFinite(e.maxY)&&e.maxX>=e.minX&&e.maxY>=e.minY}function v(e,t){m(t)&&(e.minX=Math.min(e.minX,t.x),e.minY=Math.min(e.minY,t.y),e.maxX=Math.max(e.maxX,t.x),e.maxY=Math.max(e.maxY,t.y))}function Lt(e,t,r){if(!m(t)||!Number.isFinite(r))return;const i=Math.abs(r);v(e,{x:t.x-i,y:t.y-i}),v(e,{x:t.x+i,y:t.y+i})}function At(e,t=.02,r=1e-6){if(!D(e))return{minX:-10,minY:-10,maxX:10,maxY:10};const i=Math.max((e.maxX-e.minX)*t,r),s=Math.max((e.maxY-e.minY)*t,r);return{minX:e.minX-i,minY:e.minY-s,maxX:e.maxX+i,maxY:e.maxY+s}}function m(e){return!!e&&typeof e=="object"&&Number.isFinite(e.x)&&Number.isFinite(e.y)}function x(e){return{x:e.x,y:e.y}}function B(e){return e*Math.PI/180}function J(e,t,r,i,s=!0,n=64){if(!m(e)||!Number.isFinite(t))return[];let o=r,a=i;if(!Number.isFinite(o)||!Number.isFinite(a))return[];(Math.abs(o)>Math.PI*2+1e-6||Math.abs(a)>Math.PI*2+1e-6)&&(o=B(o),a=B(a)),s&&a<o&&(a+=Math.PI*2),!s&&o<a&&(o+=Math.PI*2);const c=a-o,l=Math.max(8,Math.min(256,Math.ceil(Math.abs(c)/(Math.PI*2)*n))),h=[];for(let f=0;f<=l;f++){const u=o+c*(f/l);h.push({x:e.x+Math.cos(u)*t,y:e.y+Math.sin(u)*t})}return h}function Q(e,t,r=1,i=0,s=Math.PI*2,n=96){if(!m(e)||!m(t))return[];const o=Math.hypot(t.x,t.y);if(!Number.isFinite(o)||o<=0)return[];const a=o*(Number.isFinite(r)&&r>0?r:1),c=Math.atan2(t.y,t.x);let l=Number.isFinite(i)?i:0,h=Number.isFinite(s)?s:Math.PI*2;(Math.abs(l)>Math.PI*2+1e-6||Math.abs(h)>Math.PI*2+1e-6)&&(l=B(l),h=B(h)),h<l&&(h+=Math.PI*2);const f=Math.max(12,Math.min(256,Math.ceil(Math.abs(h-l)/(Math.PI*2)*n))),u=[],p=Math.cos(c),w=Math.sin(c);for(let N=0;N<=f;N++){const $=l+(h-l)*(N/f),j=Math.cos($)*o,G=Math.sin($)*a;u.push({x:e.x+j*p-G*w,y:e.y+j*w+G*p})}return u}function Bt(e,t,r=0,i=16){if(!Number.isFinite(r)||Math.abs(r)<1e-12)return[x(e),x(t)];const s=Math.hypot(t.x-e.x,t.y-e.y);if(s<=1e-12)return[x(e),x(t)];const n=4*Math.atan(r),o=Math.abs(s/(2*Math.sin(n/2))),a={x:(e.x+t.x)/2,y:(e.y+t.y)/2},c=(t.x-e.x)/s,l=(t.y-e.y)/s,h=r>=0?1:-1,f=Math.sqrt(Math.max(o*o-(s/2)**2,0)),u={x:a.x-h*l*f,y:a.y+h*c*f},p=Math.atan2(e.y-u.y,e.x-u.x),w=Math.atan2(t.y-u.y,t.x-u.x);return J(u,o,p,w,r>=0,i)}function Ft(e){return e.replace(/\\P/g,`
|
|
2
|
-
`).replace(/\\~|\\ /g," ").replace(/\\[A-Za-z][^;]*;/g,"").replace(/[{}]/g,"").replace(/\\[A-Za-z]/g,"").trim()}function O(e,t,r){return Math.min(r,Math.max(t,e))}class
|
|
1
|
+
(function(g,C){typeof exports=="object"&&typeof module<"u"?C(exports,require("dwf-viewer")):typeof define=="function"&&define.amd?define(["exports","dwf-viewer"],C):(g=typeof globalThis<"u"?globalThis:g||self,C(g.LightweightCadViewer={},g.DwfViewerPackage))})(this,function(g,C){"use strict";var gr=Object.defineProperty;var br=(g,C,I)=>C in g?gr(g,C,{enumerable:!0,configurable:!0,writable:!0,value:I}):g[C]=I;var f=(g,C,I)=>br(g,typeof C!="symbol"?C+"":C,I);var I=typeof document<"u"?document.currentScript:null;async function W(e){if(e.buffer instanceof Uint8Array)return e.buffer;if(e.buffer instanceof ArrayBuffer)return new Uint8Array(e.buffer);if(e.file)return new Uint8Array(await e.file.arrayBuffer());throw new Error("CadLoadInput requires a File, ArrayBuffer, or Uint8Array.")}function le(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function R(e){var i;const t=e.fileName??((i=e.file)==null?void 0:i.name)??"",r=t.lastIndexOf(".");return r>=0?t.slice(r+1).toLowerCase():""}function L(e,t){const r=R(e);if(r==="dwg")return"dwg";if(r==="dxf")return"dxf";if(r==="dwfx")return"dwfx";if(r==="xps")return"xps";if(r==="dwf")return"dwf";if(t&&t.byteLength>=6){const i=Pt(t.slice(0,6));if(/^AC10/.test(i))return"dwg";if(t[0]===80&&t[1]===75)return"dwfx";const s=Pt(t.slice(0,Math.min(t.byteLength,2048))).toUpperCase();if(s.includes("SECTION")&&s.includes("ENTITIES"))return"dxf";if(s.includes("DWF"))return"dwf"}return"unknown"}function Pt(e){return Array.from(e,t=>t>=32&&t<=126?String.fromCharCode(t):" ").join("")}class kt{constructor(t=[]){f(this,"loaders",[]);for(const r of t)this.register(r)}register(t){const r=this.loaders.findIndex(i=>i.id===t.id);return r>=0?this.loaders.splice(r,1,t):this.loaders.push(t),this}unregister(t){const r=this.loaders.findIndex(i=>i.id===t);return r>=0&&this.loaders.splice(r,1),this}list(){return[...this.loaders]}async detect(t){const r=await W(t),i=L(t,r),s=this.loaders.find(o=>o.formats.includes(i)&&o.accepts(t,r));if(s)return{loader:s,bytes:r,format:i};const n=this.loaders.find(o=>o.accepts(t,r));if(n)return{loader:n,bytes:r,format:i};throw new Error(`No CAD loader registered for ${i==="unknown"?"this file":i.toUpperCase()}.`)}async load(t,r={}){const{loader:i,bytes:s}=await this.detect(t);return i.load({...t,buffer:s},r)}}class St{constructor(){f(this,"worker");f(this,"sequence",0);f(this,"pending",new Map)}load(t,r,i={}){var l,h;if(!Z())throw new Error("Web Worker is not available in this runtime.");const s=this.ensureWorker(i),n=++this.sequence,o=Math.max(0,Number(i.workerTimeoutMs??0)),a=i.fileName??r.fileName??((l=r.file)==null?void 0:l.name),c=de(t,r,i);return(h=i.onProgress)==null||h.call(i,{phase:"worker-start",format:"dwg",message:"Dispatching DWG parse to worker…",total:t.byteLength}),new Promise((d,u)=>{var b;if((b=i.signal)!=null&&b.aborted){u(K());return}const p={resolve:d,reject:u,onProgress:i.onProgress,signal:i.signal};o>0&&(p.timer=setTimeout(()=>{this.pending.delete(n),this.resetWorker(),u(new Error(`DWG worker timed out after ${o} ms.`))},o)),i.signal&&(p.abortHandler=()=>{this.pending.delete(n),this.resetWorker(),u(K())},i.signal.addEventListener("abort",p.abortHandler,{once:!0})),this.pending.set(n,p);try{s.postMessage({type:"load",requestId:n,bytes:c,fileName:a,options:Mt(i)},[c])}catch(N){this.pending.delete(n),q(p),u(N instanceof Error?N:new Error(String(N)))}})}preload(t={}){var n;if(!Z())return Promise.reject(new Error("Web Worker is not available in this runtime."));const r=this.ensureWorker(t),i=++this.sequence,s=Math.max(0,Number(t.workerTimeoutMs??0));return(n=t.onProgress)==null||n.call(t,{phase:"worker-start",format:"dwg",message:"Starting DWG worker warmup…"}),new Promise((o,a)=>{var l;if((l=t.signal)!=null&&l.aborted){a(K());return}const c={resolve:()=>o(),reject:a,onProgress:t.onProgress,signal:t.signal};s>0&&(c.timer=setTimeout(()=>{this.pending.delete(i),this.resetWorker(),a(new Error(`DWG worker warmup timed out after ${s} ms.`))},s)),t.signal&&(c.abortHandler=()=>{this.pending.delete(i),this.resetWorker(),a(K())},t.signal.addEventListener("abort",c.abortHandler,{once:!0})),this.pending.set(i,c);try{r.postMessage({type:"warmup",requestId:i,options:Mt(t)})}catch(h){this.pending.delete(i),q(c),a(h instanceof Error?h:new Error(String(h)))}})}terminate(){this.resetWorker()}ensureWorker(t){return this.worker||(this.worker=he(t),this.worker.onmessage=r=>this.handleMessage(r.data),this.worker.onerror=r=>{const i=r.message||"DWG worker failed.";this.rejectAll(new Error(i)),this.resetWorker(!1)},this.worker.onmessageerror=()=>{this.rejectAll(new Error("DWG worker returned a message that could not be cloned.")),this.resetWorker(!1)}),this.worker}handleMessage(t){var s,n;if(t.type==="ready")return;const r=this.pending.get(t.requestId);if(!r)return;if(t.type==="progress"){(s=r.onProgress)==null||s.call(r,t.progress);return}if(this.pending.delete(t.requestId),q(r),t.type==="result"){r.resolve(t.result);return}if(t.type==="warmup-result"){(n=r.onProgress)==null||n.call(r,{phase:"worker-ready",format:"dwg",message:"DWG worker warmup complete.",percent:100,elapsedMs:t.elapsedMs}),r.resolve(void 0);return}const i=new Error(t.error.message);i.name=t.error.name||"DwgWorkerError",t.error.stack&&(i.stack=t.error.stack),r.reject(i)}rejectAll(t){for(const[,r]of this.pending)q(r),r.reject(t);this.pending.clear()}resetWorker(t=!0){var r;t&&this.rejectAll(new Error("DWG worker was terminated.")),(r=this.worker)==null||r.terminate(),this.worker=void 0}}function Z(){return typeof Worker<"u"&&typeof URL<"u"}function he(e){return e.workerFactory?e.workerFactory():e.workerUrl?new Worker(e.workerUrl,{type:"module",name:"lightweight-cad-dwg-loader"}):new Worker(new URL("/assets/DwgWorker-CuZJ5EUe.js",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:I&&I.tagName.toUpperCase()==="SCRIPT"&&I.src||new URL("cad-viewer.umd.cjs",document.baseURI).href),{type:"module",name:"lightweight-cad-dwg-loader"})}function Mt(e){return{wasmPath:fe(e.wasmPath),includePaperSpace:e.includePaperSpace,maxInsertDepth:e.maxInsertDepth,keepRaw:!!e.keepRaw}}function de(e,t,r){return!!t.file||r.transferInputBuffer===!0?le(e):e.slice().buffer}function q(e){e.timer&&clearTimeout(e.timer),e.signal&&e.abortHandler&&e.signal.removeEventListener("abort",e.abortHandler)}function K(){if(typeof DOMException<"u")return new DOMException("DWG loading was aborted.","AbortError");const e=new Error("DWG loading was aborted.");return e.name="AbortError",e}function fe(e){const t=((e==null?void 0:e.trim())||"/wasm").replace(/\/+$/,"");return t===""?Et():ue(t)?t:t.startsWith("/")?`${Et()}${t}`:new URL(t,Nt()).href.replace(/\/+$/,"")}function Nt(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"http://localhost/"}function Et(){return typeof location<"u"&&location.origin?location.origin:new URL(Nt()).origin}function ue(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)}class It{constructor(t={}){f(this,"id","dwg");f(this,"label","DWG / LibreDWG WebAssembly");f(this,"formats",["dwg"]);f(this,"defaults");f(this,"workerClient",new St);this.defaults={useWorker:!0,...t}}accepts(t,r){return R(t)==="dwg"?!0:L(t,r)==="dwg"}async load(t,r={}){var o,a;const i={...this.defaults,...r};(o=i.onProgress)==null||o.call(i,{phase:"read",format:"dwg",message:"Reading DWG bytes…"});const s=await W(t),n=t.fileName??((a=t.file)==null?void 0:a.name);if(i.useWorker===!1)throw new Error("DWG main-thread parsing is intentionally not bundled by the default viewer. Keep useWorker enabled, or register a custom DWG loader for non-browser runtimes.");if(!Z())throw new Error("DWG loading requires Web Worker support in this build. Provide a custom loader for this runtime.");try{return await this.workerClient.load(s,t,{...i,fileName:n})}catch(c){throw me(c)?c:pe(c)}}terminateWorker(){this.workerClient.terminate()}preload(t={}){const r={...this.defaults,...t};return r.useWorker===!1?Promise.reject(new Error("DWG preload requires worker mode in the default viewer.")):this.workerClient.preload(r)}}function me(e){return e instanceof Error&&e.name==="AbortError"}function pe(e){const t=e instanceof Error?e.message:String(e);return new Error(`${t} If the worker asset cannot be resolved by your bundler/CDN, pass workerUrl or workerFactory to CadViewer.`)}function nt(e){return{format:e.format,sourceName:e.sourceName,units:e.units,header:e.header??{},layers:e.layers??{},blocks:e.blocks??{},entities:e.entities??[],pages:e.pages,metadata:e.metadata??{},warnings:e.warnings??[],raw:e.raw}}function A(e){switch(String(e??"").toUpperCase()){case"LINE":return"line";case"CIRCLE":return"circle";case"ARC":return"arc";case"LWPOLYLINE":case"POLYLINE":case"POLYLINE_2D":case"POLYLINE2D":case"POLYLINE_3D":case"POLYLINE3D":case"LEADER":case"MULTILEADER":return"polyline";case"ELLIPSE":return"ellipse";case"TEXT":case"MTEXT":case"ATTRIB":case"ATTDEF":case"DIMENSION":return"text";case"POINT":return"point";case"INSERT":return"insert";case"SOLID":case"TRACE":case"3DFACE":return"solid";case"HATCH":return"hatch";case"SPLINE":return"spline";case"PATH":case"XPS_PATH":case"DWF_PATH":return"path";case"IMAGE":case"RASTER_IMAGE":case"DWF_IMAGE":return"image";case"VIEWPORT":return"viewport";default:return"unsupported"}}function Tt(e,t,r={}){const i=t??String(e.type??e.entityType??e.objectName??"UNKNOWN").toUpperCase(),s=r.includeUnknownProperties===!1?{type:i,kind:A(i)}:{...e,type:i,kind:A(i)};r.keepRaw&&(s.raw=e),s.handle=S(e.handle??e.id),s.layer=S(e.layer??e.layerName),s.lineType=S(e.lineType??e.linetype);const n=r.numericColorMode??"auto",o=w(e.color),a=w(e.colorIndex??e.colorNumber??e.aci??e.aciColor??e.color_index);s.colorIndex=a??(n!=="rgb"&&o!==void 0&&Math.abs(o)<=257?o:void 0);const c=e.trueColor??e.true_color??e.truecolor??e.colorRGB??e.colorRgb??e.rgbColor??e.rgb,l=o!==void 0&&o>=0&&o<=16777215&&(n==="rgb"||n==="auto"&&Math.abs(o)>257);s.trueColor=c??(l?o:void 0),(typeof e.color=="string"||typeof e.color=="number")&&(s.color=e.color),s.colorNumber=w(e.colorNumber)??s.colorNumber,s.colorName=S(e.colorName??e.color_name)??s.colorName,s.fillColor=e.fillColor??e.fill_color,s.fillColorIndex=w(e.fillColorIndex??e.fill_color_index??e.fillColorNumber)??s.fillColorIndex,s.opacity=w(e.opacity??e.alpha)??s.opacity,s.lineweight=w(e.lineweight??e.lineWeight),s.isVisible=!(e.isVisible===!1||e.visible===!1),s.startPoint=k(e.startPoint??e.start??e.p0??e.from)??s.startPoint,s.endPoint=k(e.endPoint??e.end??e.p1??e.to)??s.endPoint,s.center=k(e.center??e.centerPoint)??s.center,s.insertionPoint=k(e.insertionPoint??e.position??e.location??e.point??e.basePoint)??s.insertionPoint,s.radius=w(e.radius)??s.radius,s.startAngle=w(e.startAngle??e.start_angle)??s.startAngle,s.endAngle=w(e.endAngle??e.end_angle)??s.endAngle,s.majorAxisEndPoint=k(e.majorAxisEndPoint??e.majorAxis??e.major)??s.majorAxisEndPoint,s.axisRatio=w(e.axisRatio??e.ratio)??s.axisRatio,s.height=w(e.height??e.textHeight)??s.height,s.textHeight=w(e.textHeight??e.height)??s.textHeight,s.rotation=w(e.rotation??e.angle)??s.rotation,s.text=S(e.text??e.value??e.string??e.contents)??s.text,s.name=S(e.name??e.blockName)??s.name,s.blockName=S(e.blockName??e.name)??s.blockName;const h=ot(e.vertices??e.points);h.length>0&&(s.vertices=h);const d=ot(e.controlPoints??e.control_points);d.length>0&&(s.controlPoints=d);const u=ot(e.fitPoints??e.fit_points);return u.length>0&&(s.fitPoints=u),s}function k(e){if(!e||typeof e!="object")return;const t=e,r=Number(t.x??t.X??t[0]),i=Number(t.y??t.Y??t[1]),s=t.z??t.Z??t[2],n=s===void 0?void 0:Number(s);if(!(!Number.isFinite(r)||!Number.isFinite(i)))return Number.isFinite(n)?{x:r,y:i,z:n}:{x:r,y:i}}function ot(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const i=k(r);if(!i)continue;const s=r,n=i,o=w(s.bulge);o!==void 0&&(n.bulge=o);const a=w(s.startWidth??s.start_width);a!==void 0&&(n.startWidth=a);const c=w(s.endWidth??s.end_width);c!==void 0&&(n.endWidth=c),t.push(n)}return t}function _(e){var r;const t={};for(const i of e.entities){const s=String(i.type??"UNKNOWN").toUpperCase();t[s]=(t[s]??0)+1}return{format:e.format,sourceName:e.sourceName,entityCount:e.entities.length,layerCount:Object.keys(e.layers).length,blockCount:Object.keys(e.blocks).length,pageCount:((r=e.pages)==null?void 0:r.length)??0,byType:t,warnings:[...e.warnings]}}function Lt(e,t){t.name&&(e[t.name]=t,e[t.name.toLowerCase()]=t)}function ge(e,t){t.name&&(e[t.name]=t,e[t.name.toLowerCase()]=t)}function be(e){return e!=null&&e.length?e.flatMap(t=>t.entities.map(r=>({...r,pageIndex:t.index}))):[]}function w(e){const t=Number(e);return Number.isFinite(t)?t:void 0}function S(e){if(typeof e!="string"&&typeof e!="number")return;const t=String(e);return t.length>0?t:void 0}function E(){return{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function D(e){return Number.isFinite(e.minX)&&Number.isFinite(e.minY)&&Number.isFinite(e.maxX)&&Number.isFinite(e.maxY)&&e.maxX>=e.minX&&e.maxY>=e.minY}function y(e,t){m(t)&&(e.minX=Math.min(e.minX,t.x),e.minY=Math.min(e.minY,t.y),e.maxX=Math.max(e.maxX,t.x),e.maxY=Math.max(e.maxY,t.y))}function At(e,t,r){if(!m(t)||!Number.isFinite(r))return;const i=Math.abs(r);y(e,{x:t.x-i,y:t.y-i}),y(e,{x:t.x+i,y:t.y+i})}function Bt(e,t=.02,r=1e-6){if(!D(e))return{minX:-10,minY:-10,maxX:10,maxY:10};const i=Math.max((e.maxX-e.minX)*t,r),s=Math.max((e.maxY-e.minY)*t,r);return{minX:e.minX-i,minY:e.minY-s,maxX:e.maxX+i,maxY:e.maxY+s}}function m(e){return!!e&&typeof e=="object"&&Number.isFinite(e.x)&&Number.isFinite(e.y)}function x(e){return{x:e.x,y:e.y}}function B(e){return e*Math.PI/180}function J(e,t,r,i,s=!0,n=64){if(!m(e)||!Number.isFinite(t))return[];let o=r,a=i;if(!Number.isFinite(o)||!Number.isFinite(a))return[];(Math.abs(o)>Math.PI*2+1e-6||Math.abs(a)>Math.PI*2+1e-6)&&(o=B(o),a=B(a)),s&&a<o&&(a+=Math.PI*2),!s&&o<a&&(o+=Math.PI*2);const c=a-o,l=Math.max(8,Math.min(256,Math.ceil(Math.abs(c)/(Math.PI*2)*n))),h=[];for(let d=0;d<=l;d++){const u=o+c*(d/l);h.push({x:e.x+Math.cos(u)*t,y:e.y+Math.sin(u)*t})}return h}function Q(e,t,r=1,i=0,s=Math.PI*2,n=96){if(!m(e)||!m(t))return[];const o=Math.hypot(t.x,t.y);if(!Number.isFinite(o)||o<=0)return[];const a=o*(Number.isFinite(r)&&r>0?r:1),c=Math.atan2(t.y,t.x);let l=Number.isFinite(i)?i:0,h=Number.isFinite(s)?s:Math.PI*2;(Math.abs(l)>Math.PI*2+1e-6||Math.abs(h)>Math.PI*2+1e-6)&&(l=B(l),h=B(h)),h<l&&(h+=Math.PI*2);const d=Math.max(12,Math.min(256,Math.ceil(Math.abs(h-l)/(Math.PI*2)*n))),u=[],p=Math.cos(c),b=Math.sin(c);for(let N=0;N<=d;N++){const $=l+(h-l)*(N/d),j=Math.cos($)*o,G=Math.sin($)*a;u.push({x:e.x+j*p-G*b,y:e.y+j*b+G*p})}return u}function Ft(e,t,r=0,i=16){if(!Number.isFinite(r)||Math.abs(r)<1e-12)return[x(e),x(t)];const s=Math.hypot(t.x-e.x,t.y-e.y);if(s<=1e-12)return[x(e),x(t)];const n=4*Math.atan(r),o=Math.abs(s/(2*Math.sin(n/2))),a={x:(e.x+t.x)/2,y:(e.y+t.y)/2},c=(t.x-e.x)/s,l=(t.y-e.y)/s,h=r>=0?1:-1,d=Math.sqrt(Math.max(o*o-(s/2)**2,0)),u={x:a.x-h*l*d,y:a.y+h*c*d},p=Math.atan2(e.y-u.y,e.x-u.x),b=Math.atan2(t.y-u.y,t.x-u.x);return J(u,o,p,b,r>=0,i)}function Wt(e){return e.replace(/\\P/g,`
|
|
2
|
+
`).replace(/\\~|\\ /g," ").replace(/\\[A-Za-z][^;]*;/g,"").replace(/[{}]/g,"").replace(/\\[A-Za-z]/g,"").trim()}function O(e,t,r){return Math.min(r,Math.max(t,e))}class Rt{constructor(t={}){f(this,"id","dxf");f(this,"label","DXF / JavaScript parser");f(this,"formats",["dxf"]);f(this,"defaults");this.defaults=t}accepts(t,r){return R(t)==="dxf"||L(t,r)==="dxf"}async load(t,r={}){var h;({...this.defaults,...r});const i=performance.now(),s=await W(t),n=Se(s),o=[];let a;try{a=await ve(n)}catch(d){o.push(`dxf-parser failed, using built-in fallback parser: ${d instanceof Error?d.message:String(d)}`),a=Me(n)}const c=ye(a,t.fileName??((h=t.file)==null?void 0:h.name),o),l=performance.now()-i;return{document:c,raw:a,bytes:s.byteLength,elapsedMs:l,format:"dxf",warnings:c.warnings}}}async function ve(e){const t=await import("dxf-parser"),r=t.default??t.DxfParser;if(!r)throw new Error("dxf-parser did not expose a parser constructor.");return new r().parseSync(e)}function ye(e,t,r=[]){const i=e&&typeof e=="object"?e:{},s=we(i),n=xe(i),a=(Array.isArray(i.entities)?i.entities:[]).filter(l=>!!l&&typeof l=="object").map(l=>at(l)),c=nt({format:"dxf",sourceName:t,header:i.header&&typeof i.header=="object"?i.header:{},layers:s,blocks:n,entities:a,metadata:{parser:"dxf-parser + cad-viewer normalizer"},warnings:r,raw:e});return a.length===0&&c.warnings.push("DXF file did not expose any ENTITIES."),c}function at(e){const t=String(e.type??e.entityType??"UNKNOWN").toUpperCase(),r=Tt(e,t),i=w(e.colorIndex??e.colorNumber??e.aci),s=w(e.color);if(r.colorIndex=i??(s!==void 0&&Math.abs(s)<=257?s:void 0),r.trueColor=e.trueColor??e.true_color??e.colorRGB??e.trueColorValue??(s!==void 0&&Math.abs(s)>257?s:void 0),r.layer=S(e.layer??e.layerName)??"0",r.isClosed=!!(e.shape??e.closed??e.isClosed)||(Number(e.flag??e.flags??0)&1)===1,t==="LINE"&&(r.startPoint=k(e.startPoint??{x:e.x1??e.x,y:e.y1??e.y,z:e.z1??e.z})??r.startPoint,r.endPoint=k(e.endPoint??{x:e.x2,y:e.y2,z:e.z2})??r.endPoint),(t==="TEXT"||t==="MTEXT"||t==="ATTRIB"||t==="ATTDEF")&&(r.insertionPoint=k(e.startPoint??e.position??e.insertionPoint)??r.insertionPoint,r.text=S(e.text??e.string??e.value)??r.text,r.textHeight=w(e.textHeight??e.height)??r.textHeight,r.rotation=Ot(e.rotation??e.angle)),(t==="ARC"||t==="ELLIPSE")&&(r.startAngle=zt(e.startAngle??e.start_angle),r.endAngle=zt(e.endAngle??e.end_angle)),t==="INSERT"){r.blockName=S(e.name??e.blockName)??r.blockName,r.insertionPoint=k(e.position??e.insertionPoint??e.point)??r.insertionPoint;const n=w(e.xScale??e.scaleX??e.xscale),o=w(e.yScale??e.scaleY??e.yscale),a=w(e.zScale??e.scaleZ??e.zscale);(n!==void 0||o!==void 0||a!==void 0)&&(r.scale={x:n??1,y:o??n??1,z:a??1}),r.rotation=Ot(e.rotation??e.angle)}if(t==="SPLINE"){const n=tt(e.controlPoints??e.control_points??e.points);n.length&&(r.controlPoints=n);const o=tt(e.fitPoints??e.fit_points);o.length&&(r.fitPoints=o)}return t==="HATCH"&&(r.loops=ke(e),r.fillColorIndex=r.colorIndex),(t==="SOLID"||t==="TRACE"||t==="3DFACE")&&(r.vertices=Pe(e),r.fillColorIndex=r.colorIndex),r}function we(e){const t={},r=e.tables,i=e.layers??(r==null?void 0:r.layer)??(r==null?void 0:r.LAYER)??(r==null?void 0:r.layers),s=Ce(i);for(const n of s){const o=n,a=S(o.name??o.layerName);a&&Lt(t,{name:a,color:o.color??o.colorNumber??o.colorIndex,colorIndex:w(o.colorNumber??o.colorIndex??o.color),lineType:S(o.lineType??o.linetype),isVisible:Number(o.colorNumber??o.colorIndex??o.color??1)>=0,isFrozen:!!o.frozen,isLocked:!!o.locked,raw:o})}return t[0]||Lt(t,{name:"0",colorIndex:7,isVisible:!0}),t}function xe(e){const t={},r=e.blocks;if(!r||typeof r!="object")return t;if(Array.isArray(r))for(const i of r)Dt(t,i);else for(const[i,s]of Object.entries(r))Dt(t,s,i);return t}function Dt(e,t,r){if(!t||typeof t!="object")return;const i=t,s=S(i.name??i.blockName??r);if(!s)return;const o=(Array.isArray(i.entities)?i.entities:[]).filter(a=>!!a&&typeof a=="object").map(a=>at(a));ge(e,{name:s,basePoint:k(i.basePoint??i.position)??{x:0,y:0},entities:o,raw:i})}function Ce(e){if(!e)return[];if(Array.isArray(e))return e;if(typeof e!="object")return[];const t=e;return Array.isArray(t.entries)?t.entries:Array.isArray(t.records)?t.records:Array.isArray(t.layers)?t.layers:Object.values(t).filter(r=>r&&typeof r=="object")}function tt(e){return Array.isArray(e)?e.map(k).filter(t=>!!t):[]}function Pe(e){const t=tt(e.vertices??e.points);if(t.length)return t;const r=[];for(let i=0;i<4;i++){const s=k({x:e[`x${i}`]??e[`x${i+1}`],y:e[`y${i}`]??e[`y${i+1}`],z:e[`z${i}`]??e[`z${i+1}`]});s&&r.push(s)}return r}function ke(e){const t=e.boundaryLoops??e.loops??e.paths;if(Array.isArray(t))return t.map(r=>{const i=r;return{vertices:tt(i.vertices??i.points),isClosed:!0}}).filter(r=>r.vertices&&r.vertices.length>0)}function Ot(e){const t=w(e);if(t!==void 0)return Math.abs(t)>Math.PI*2+1e-6?B(t):t}function zt(e){const t=w(e);if(t!==void 0)return Math.abs(t)>Math.PI*2+1e-6?B(t):t}function Se(e){const t=new TextDecoder("utf-8",{fatal:!1}).decode(e);return t.includes("SECTION")?t:new TextDecoder("iso-8859-1",{fatal:!1}).decode(e)}function Me(e){var l,h;const t=e.replace(/\r\n/g,`
|
|
3
3
|
`).replace(/\r/g,`
|
|
4
4
|
`).split(`
|
|
5
|
-
`),r=[];for(let f=0;f<t.length-1;f+=2){const u=Number((l=t[f])==null?void 0:l.trim()),p=t[f+1]??"";Number.isFinite(u)&&r.push({code:u,value:p.trimEnd()})}const i=[],s={};let n="",o=[],a;for(let f=0;f<r.length;f++){const u=r[f];if(u.code===0&&u.value==="SECTION"){n=((h=r[f+1])==null?void 0:h.code)===2?r[f+1].value.toUpperCase():"",f++;continue}if(u.code===0&&u.value==="ENDSEC"){c(),n="";continue}n==="ENTITIES"&&(u.code===0?(c(),o=[u]):o.push(u))}return c(),{header:{},tables:{},entities:i,blocks:s};function c(){var p;if(!o.length)return;const f=(p=o[0])==null?void 0:p.value.toUpperCase();if(f==="VERTEX"&&a){const w=k(o,10,20,30);w&&(a.vertices??(a.vertices=[])).push({...w,bulge:b(o,42)}),o=[];return}if(f==="SEQEND"){a&&i.push(a),a=void 0,o=[];return}if(a&&(i.push(a),a=void 0),!f||f==="EOF"){o=[];return}const u=ke(f,o);f==="POLYLINE"?a=u:i.push(u),o=[]}}function ke(e,t){const r={type:e,handle:U(t,5),layer:U(t,8)??"0",colorIndex:b(t,62),trueColor:b(t,420),lineType:U(t,6),lineweight:b(t,370)};switch(e){case"LINE":Object.assign(r,{startPoint:k(t,10,20,30),endPoint:k(t,11,21,31)});break;case"CIRCLE":Object.assign(r,{center:k(t,10,20,30),radius:b(t,40)});break;case"ARC":Object.assign(r,{center:k(t,10,20,30),radius:b(t,40),startAngle:et(b(t,50)),endAngle:et(b(t,51))});break;case"POINT":Object.assign(r,{point:k(t,10,20,30)});break;case"TEXT":case"MTEXT":Object.assign(r,{insertionPoint:k(t,10,20,30),text:Me(t),textHeight:b(t,40),rotation:et(b(t,50))});break;case"LWPOLYLINE":Object.assign(r,{vertices:Se(t),flag:b(t,70),isClosed:(Number(b(t,70)??0)&1)===1});break;case"POLYLINE":Object.assign(r,{vertices:[],flag:b(t,70),isClosed:(Number(b(t,70)??0)&1)===1});break;case"ELLIPSE":Object.assign(r,{center:k(t,10,20,30),majorAxisEndPoint:k(t,11,21,31),axisRatio:b(t,40),startAngle:b(t,41),endAngle:b(t,42)});break;case"SPLINE":Object.assign(r,{controlPoints:Pe(t,10,20,30),degree:b(t,71),isClosed:(Number(b(t,70)??0)&1)===1});break;case"INSERT":Object.assign(r,{name:U(t,2),blockName:U(t,2),insertionPoint:k(t,10,20,30),rotation:et(b(t,50)),scale:{x:b(t,41)??1,y:b(t,42)??b(t,41)??1,z:b(t,43)??1}});break;case"SOLID":case"TRACE":case"3DFACE":Object.assign(r,{vertices:[k(t,10,20,30),k(t,11,21,31),k(t,12,22,32),k(t,13,23,33)].filter(Boolean)});break}return ot(r)}function b(e,t){var s;const r=(s=e.find(n=>n.code===t))==null?void 0:s.value,i=Number(r);return Number.isFinite(i)?i:void 0}function U(e,t){var i;const r=(i=e.find(s=>s.code===t))==null?void 0:i.value;return r&&r.length>0?r:void 0}function k(e,t,r,i){const s=b(e,t),n=b(e,r),o=b(e,i);if(!(s===void 0||n===void 0))return o===void 0?{x:s,y:n}:{x:s,y:n,z:o}}function Pe(e,t,r,i){const s=[];for(let n=0;n<e.length;n++){if(e[n].code!==t)continue;const o=Number(e[n].value),a=e.slice(n+1).find(f=>f.code===r),c=e.slice(n+1).find(f=>f.code===i),l=Number(a==null?void 0:a.value),h=Number(c==null?void 0:c.value);Number.isFinite(o)&&Number.isFinite(l)&&s.push(Number.isFinite(h)?{x:o,y:l,z:h}:{x:o,y:l})}return s}function Se(e){const t=[];for(let r=0;r<e.length;r++){if(e[r].code!==10)continue;const i=Number(e[r].value);let s,n;for(let o=r+1;o<e.length&&e[o].code!==10;o++)e[o].code===20&&(s=Number(e[o].value)),e[o].code===42&&(n=Number(e[o].value));Number.isFinite(i)&&Number.isFinite(s)&&t.push({x:i,y:s,bulge:Number.isFinite(n)?n:void 0})}return t}function Me(e){const t=e.filter(r=>r.code===1||r.code===3).map(r=>r.value);return t.length?t.join(""):void 0}function et(e){return typeof e=="number"&&Number.isFinite(e)?B(e):void 0}class zt{constructor(t={}){d(this,"id","dwf");d(this,"label","DWF/DWFx native viewer powered by dwf-viewer");d(this,"formats",["dwf","dwfx","xps"]);d(this,"nativeRenderer",!0);d(this,"defaults");d(this,"native");d(this,"host");d(this,"lastStats");this.defaults=t}accepts(t,r){const i=R(t);if(i==="dwf"||i==="dwfx"||i==="xps")return!0;const s=L(t,r);return s==="dwf"||s==="dwfx"||s==="xps"}async load(t,r={}){var f,u,p,w;const i={...this.defaults,...r},s=performance.now(),n=t.fileName??((f=t.file)==null?void 0:f.name),o=await W(t),a=Xt(L(t,o),R(t));(u=i.onProgress)==null||u.call(i,{phase:"parse",format:a,message:"Opening DWF/DWFx with dwf-viewer…",percent:48});const c=await C.openDwfDocument(o,{fileName:n});(p=i.onProgress)==null||p.call(i,{phase:"normalize",format:a,message:"Reading DWF pages, sheets and model metadata…",percent:76});const l=Yt(c,n,a,i.keepRaw===!0),h=performance.now()-s;return(w=i.onProgress)==null||w.call(i,{phase:"done",format:l.format,message:"DWF/DWFx document ready.",percent:100,elapsedMs:h}),{document:l,raw:i.keepRaw?c:void 0,bytes:o.byteLength,elapsedMs:h,format:l.format,warnings:l.warnings}}async mount(t,r,i={}){var w,N,$,j,G;const s={...this.defaults,...i},n=performance.now(),o=t.fileName??((w=t.file)==null?void 0:w.name),a=await W(t),c=Xt(L(t,a),R(t)),l=Le(s),h=_t(s);(N=s.onProgress)==null||N.call(s,{phase:"native-render",format:c,message:"Mounting native DWF renderer…",percent:28}),this.unmount(),this.host=r,r.replaceChildren(),this.native=new C.DwfViewer(r,{wasmUrl:l,preferWebgl:s.dwfPreferWebgl??!0,preferWasm:s.dwfPreferWasm??!0,background:h,maxDevicePixelRatio:s.dwfMaxDevicePixelRatio??2,maxCanvasPixels:s.dwfMaxCanvasPixels??16777216,maxGpuCacheBytes:s.dwfMaxGpuCacheBytes??160*1024*1024,maxCachedScenes:s.dwfMaxCachedScenes??2}),($=s.onProgress)==null||$.call(s,{phase:"parse",format:c,message:"Parsing DWF package and page streams…",percent:58}),await this.native.load(a,{fileName:o,wasmUrl:l,preferWebgl:s.dwfPreferWebgl??!0,preferWasm:s.dwfPreferWasm??!0,background:h,maxGpuCacheBytes:s.dwfMaxGpuCacheBytes??160*1024*1024,maxCachedScenes:s.dwfMaxCachedScenes??2}),(j=s.onProgress)==null||j.call(s,{phase:"render",format:c,message:"Rendering DWF/DWFx with dwf-viewer…",percent:88}),this.lastStats=await this.native.render();const f=this.native.getDocument(),u=Yt(f,o,c,s.keepRaw===!0);u.metadata.loaderMode="Native DWF",u.metadata.nativeRenderer="dwf-viewer",u.metadata.nativeRenderStats=this.lastStats?{...this.lastStats,warnings:this.lastStats.warnings.length}:void 0;const p=performance.now()-n;return(G=s.onProgress)==null||G.call(s,{phase:"done",format:u.format,message:"DWF/DWFx rendered.",percent:100,elapsedMs:p}),{document:u,raw:s.keepRaw?f:void 0,bytes:a.byteLength,elapsedMs:p,format:u.format,warnings:u.warnings}}unmount(){var t;(t=this.native)==null||t.dispose(),this.native=void 0,this.lastStats=void 0,this.host&&this.host.replaceChildren()}fit(){var t;(t=this.native)==null||t.fit()}zoomIn(){var r;const t=(r=this.native)==null?void 0:r.zoomInButton;t==null||t.click()}zoomOut(){var r;const t=(r=this.native)==null?void 0:r.zoomOutButton;t==null||t.click()}resize(){var t;(t=this.native)==null||t.render()}setNativeOptions(t){var i,s,n;const r=this.native;if(r){if(typeof t.dwfBackground=="string")r.background=t.dwfBackground;else{const o=_t(t);o&&(r.background=o)}typeof t.dwfPreferWebgl=="boolean"&&((i=r.setPreferWebgl)==null||i.call(r,t.dwfPreferWebgl)),typeof t.dwfPreferWasm=="boolean"&&((s=r.setPreferWasm)==null||s.call(r,t.dwfPreferWasm)),(n=r.render)==null||n.call(r)}}getLastNativeStats(){return this.lastStats}}function Yt(e,t,r,i){var a,c;const s=Ht((e==null?void 0:e.diagnostics)??[]),n=((e==null?void 0:e.pageData)??[]).map((l,h)=>Ne(l,h));for(const l of(e==null?void 0:e.pageData)??[])s.push(...Ht(l.diagnostics));const o={parser:"dwf-viewer",nativeRenderer:"dwf-viewer",dwfKind:e==null?void 0:e.kind,packageEntries:((a=e==null?void 0:e.packageEntries)==null?void 0:a.length)??0,resources:((c=e==null?void 0:e.resources)==null?void 0:c.length)??0,pageKinds:Fe(((e==null?void 0:e.pageData)??[]).map(l=>l.kind)),pageNames:((e==null?void 0:e.pages)??[]).map(l=>l.name)};return st({format:r,sourceName:t,layers:{},blocks:{},pages:n,entities:ue(n),metadata:o,warnings:We(s),raw:i?e:void 0})}function Ne(e,t){const r=Ee(e,t);return{index:t,name:e.name||e.sourcePath||`${t+1}`,width:e.width||1e3,height:e.height||1e3,entities:r}}function Ee(e,t){return e.kind==="w2d-text"?e.primitives.flatMap((r,i)=>Ie(r,t,i)):e.kind==="image"?[{type:"DWF_IMAGE_PAGE",kind:"image",pageIndex:t,width:e.width,height:e.height,imageSource:e.sourcePath}]:e.kind==="w3d-model"?e.model.meshes.map((r,i)=>({id:r.id,type:"W3D_MESH",kind:"solid",pageIndex:t,color:r.color?Be(r.color):void 0,name:r.name||`mesh-${i+1}`,raw:{vertexCount:r.vertexCount,triangleCount:r.triangleCount,materialId:r.materialId}})):e.kind==="xps-fixed-page"?[{type:"XPS_FIXED_PAGE",kind:"viewport",pageIndex:t,width:e.width,height:e.height,raw:{sourcePath:e.sourcePath}}]:[{type:"DWF_PAGE",kind:"viewport",pageIndex:t,width:e.width,height:e.height,raw:{sourcePath:e.sourcePath}}]}function Ie(e,t,r){const i={id:`dwf-${t}-${r}`,pageIndex:t,color:e.stroke,fillColor:e.fill,lineweight:e.lineWidth,raw:{matrix:e.matrix}};if(e.type==="polyline"||e.type==="polygon")return[{...i,type:e.type==="polygon"?"DWF_POLYGON":"DWF_POLYLINE",kind:"polyline",vertices:Te(e.points),isClosed:e.type==="polygon"}];if(e.type==="path")return[{...i,type:"DWF_PATH",kind:"path",commands:e.commands}];if(e.type==="text")return[{...i,type:"DWF_TEXT",kind:"text",insertionPoint:{x:e.x,y:e.y,z:0},text:e.text,textHeight:e.size}];if(e.type==="rect"){const s=e.x,n=e.y,o=e.width,a=e.height;return[{...i,type:"DWF_RECT",kind:"polyline",isClosed:!0,vertices:[{x:s,y:n,z:0},{x:s+o,y:n,z:0},{x:s+o,y:n+a,z:0},{x:s,y:n+a,z:0}]}]}return[]}function Te(e){const t=[];for(let r=0;r+1<e.length;r+=2)t.push({x:e[r],y:e[r+1],z:0});return t}function Ht(e){return e.filter(t=>t.level!=="info").map(t=>`${t.code}: ${t.message}${t.source?` (${t.source})`:""}`)}function Xt(e,t){return t==="dwf"||t==="dwfx"||t==="xps"?t:e==="dwf"||e==="dwfx"||e==="xps"?e:"dwf"}function Le(e){if(e.dwfWasmUrl)return e.dwfWasmUrl;if(typeof document>"u")return;const t=e.wasmPath?new URL(Ae(e.wasmPath),document.baseURI).href:new URL("wasm/",document.baseURI).href;return new URL("dwfv-render.wasm",t).href}function _t(e){if(e.dwfBackground)return e.dwfBackground;const t=e.canvasOptions;return(t==null?void 0:t.background)??"#05070d"}function Ae(e){return e.endsWith("/")?e:`${e}/`}function Be(e){const[t,r,i]=e.map(s=>Math.max(0,Math.min(255,Math.round(s*255))));return`#${at(t)}${at(r)}${at(i)}`}function at(e){return e.toString(16).padStart(2,"0")}function Fe(e){const t={};for(const r of e)t[r]=(t[r]??0)+1;return t}function We(e){return Array.from(new Set(e))}function Ut(e={}){return new kt([new Et(e),new Wt(e),new zt(e)])}function Vt(e){const t=e;return t.nativeRenderer===!0&&typeof t.mount=="function"}const Re={1:"#ff0000",2:"#ffff00",3:"#00ff00",4:"#00ffff",5:"#0000ff",6:"#ff00ff",8:"#808080",9:"#c0c0c0",10:"#ff0000",11:"#ff7f7f",12:"#a50000",13:"#a55252",14:"#7f0000",15:"#7f3f3f",16:"#4c0000",17:"#4c2626",18:"#260000",19:"#261313",20:"#ff3f00",21:"#ff9f7f",22:"#a52900",23:"#a56752",24:"#7f1f00",25:"#7f4f3f",26:"#4c1300",27:"#4c2f26",28:"#260900",29:"#261713",30:"#ff7f00",31:"#ffbf7f",32:"#a55200",33:"#a57c52",34:"#7f3f00",35:"#7f5f3f",36:"#4c2600",37:"#4c3926",38:"#261300",39:"#261c13",40:"#ffbf00",41:"#ffdf7f",42:"#a57c00",43:"#a59152",44:"#7f5f00",45:"#7f6f3f",46:"#4c3900",47:"#4c4226",48:"#261c00",49:"#262113",50:"#ffff00",51:"#ffff7f",52:"#a5a500",53:"#a5a552",54:"#7f7f00",55:"#7f7f3f",56:"#4c4c00",57:"#4c4c26",58:"#262600",59:"#262613",60:"#bfff00",61:"#dfff7f",62:"#7ca500",63:"#91a552",64:"#5f7f00",65:"#6f7f3f",66:"#394c00",67:"#424c26",68:"#1c2600",69:"#212613",70:"#7fff00",71:"#bfff7f",72:"#52a500",73:"#7ca552",74:"#3f7f00",75:"#5f7f3f",76:"#264c00",77:"#394c26",78:"#132600",79:"#1c2613",80:"#3fff00",81:"#9fff7f",82:"#29a500",83:"#67a552",84:"#1f7f00",85:"#4f7f3f",86:"#134c00",87:"#2f4c26",88:"#092600",89:"#172613",90:"#00ff00",91:"#7fff7f",92:"#00a500",93:"#52a552",94:"#007f00",95:"#3f7f3f",96:"#004c00",97:"#264c26",98:"#002600",99:"#132613",100:"#00ff3f",101:"#7fff9f",102:"#00a529",103:"#52a567",104:"#007f1f",105:"#3f7f4f",106:"#004c13",107:"#264c2f",108:"#002609",109:"#132617",110:"#00ff7f",111:"#7fffbf",112:"#00a552",113:"#52a57c",114:"#007f3f",115:"#3f7f5f",116:"#004c26",117:"#264c39",118:"#002613",119:"#13261c",120:"#00ffbf",121:"#7fffdf",122:"#00a57c",123:"#52a591",124:"#007f5f",125:"#3f7f6f",126:"#004c39",127:"#264c42",128:"#00261c",129:"#132621",130:"#00ffff",131:"#7fffff",132:"#00a5a5",133:"#52a5a5",134:"#007f7f",135:"#3f7f7f",136:"#004c4c",137:"#264c4c",138:"#002626",139:"#132626",140:"#00bfff",141:"#7fdfff",142:"#007ca5",143:"#5291a5",144:"#005f7f",145:"#3f6f7f",146:"#00394c",147:"#26424c",148:"#001c26",149:"#132126",150:"#007fff",151:"#7fbfff",152:"#0052a5",153:"#527ca5",154:"#003f7f",155:"#3f5f7f",156:"#00264c",157:"#26394c",158:"#001326",159:"#131c26",160:"#003fff",161:"#7f9fff",162:"#0029a5",163:"#5267a5",164:"#001f7f",165:"#3f4f7f",166:"#00134c",167:"#262f4c",168:"#000926",169:"#131726",170:"#0000ff",171:"#7f7fff",172:"#0000a5",173:"#5252a5",174:"#00007f",175:"#3f3f7f",176:"#00004c",177:"#26264c",178:"#000026",179:"#131326",180:"#3f00ff",181:"#9f7fff",182:"#2900a5",183:"#6752a5",184:"#1f007f",185:"#4f3f7f",186:"#13004c",187:"#2f264c",188:"#090026",189:"#171326",190:"#7f00ff",191:"#bf7fff",192:"#5200a5",193:"#7c52a5",194:"#3f007f",195:"#5f3f7f",196:"#26004c",197:"#39264c",198:"#130026",199:"#1c1326",200:"#bf00ff",201:"#df7fff",202:"#7c00a5",203:"#9152a5",204:"#5f007f",205:"#6f3f7f",206:"#39004c",207:"#42264c",208:"#1c0026",209:"#211326",210:"#ff00ff",211:"#ff7fff",212:"#a500a5",213:"#a552a5",214:"#7f007f",215:"#7f3f7f",216:"#4c004c",217:"#4c264c",218:"#260026",219:"#261326",220:"#ff00bf",221:"#ff7fdf",222:"#a5007c",223:"#a55291",224:"#7f005f",225:"#7f3f6f",226:"#4c0039",227:"#4c2642",228:"#26001c",229:"#261321",230:"#ff007f",231:"#ff7fbf",232:"#a50052",233:"#a5527c",234:"#7f003f",235:"#7f3f5f",236:"#4c0026",237:"#4c2639",238:"#260013",239:"#26131c",240:"#ff003f",241:"#ff7f9f",242:"#a50029",243:"#a55267",244:"#7f001f",245:"#7f3f4f",246:"#4c0013",247:"#4c262f",248:"#260009",249:"#261317",250:"#333333",251:"#505050",252:"#696969",253:"#828282",254:"#bebebe",255:"#ffffff"};function T(e,t="#ffffff",r=t){if(typeof e!="number"||Number.isNaN(e))return t;const i=Math.abs(Math.trunc(e));return i===0||i===256||i===257?t:i===7?r:Re[i]??t}function z(e,t="rgb"){const r=Math.max(0,Math.trunc(e))&16777215,i=r>>16&255,s=r>>8&255,n=r&255;return`rgb(${t==="rgb"?i:n}, ${s}, ${t==="rgb"?n:i})`}function Y(e){if(typeof e=="string"){const t=e.trim();return t?/^(#|rgb\(|rgba\(|hsl\(|hsla\()/i.test(t)?De(t)??t:{red:"#ff0000",yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",blue:"#0000ff",magenta:"#ff00ff",white:"#ffffff",black:"#000000",grey:"#808080",gray:"#808080"}[t.toLowerCase()]:void 0}if(e&&typeof e=="object"){const t=e,r=Number(t.r??t.red),i=Number(t.g??t.green),s=Number(t.b??t.blue),n=Number(t.a??t.alpha??1);if([r,i,s].every(Number.isFinite))return Number.isFinite(n)&&n>=0&&n<1?`rgba(${r}, ${i}, ${s}, ${n})`:`rgb(${r}, ${i}, ${s})`}}function De(e){if(!e)return;const t=e.trim();if(/^#[0-9a-f]{8}$/i.test(t)){const r=parseInt(t.slice(1,3),16)/255,i=parseInt(t.slice(3,5),16),s=parseInt(t.slice(5,7),16),n=parseInt(t.slice(7,9),16);return r>=.999?`rgb(${i}, ${s}, ${n})`:`rgba(${i}, ${s}, ${n}, ${dt(r)})`}if(/^#[0-9a-f]{6}$/i.test(t)||/^#[0-9a-f]{3}$/i.test(t))return t;if(/^sc#/i.test(t)){const r=t.slice(3).split(",").map(a=>Number(a.trim())),[i,s,n,o]=r.length===4?r:[1,...r];if([i,s,n,o].every(Number.isFinite))return`rgba(${Math.round(s*255)}, ${Math.round(n*255)}, ${Math.round(o*255)}, ${dt(i)})`}}function F(e,t,r={}){const i=r.foreground??"#ffffff",s=i;let n;const o=Y(e.trueColor)??Y(e.color)??Y(e.colorName);if(o&&(n=o),!n){const a=_e(e,["trueColor","true_color","truecolor","colorRGB","colorRgb","rgbColor","rgb"]);typeof a=="number"&&a>=0&&a<=16777215&&(n=z(a,r.trueColorByteOrder??"rgb"))}if(!n){const a=Zt(e.colorIndex,e.colorNumber,e.aci);typeof a=="number"&&Math.abs(a)<=257&&a!==256&&a!==0&&a!==257&&(n=T(a,s,i))}if(!n&&typeof e.color=="number"){const a=Number(e.color);Math.abs(a)<=257?a!==0&&a!==256&&a!==257&&(n=T(a,s,i)):n=z(a,r.trueColorByteOrder??"rgb")}if(!n){const a=Xe(t,e.layer);n=ze(a,r)}return $t(n??s,r)}function ct(e,t,r={}){let i;const s=Y(e.fillColor);if(s&&(i=s),!i&&typeof e.fillColor=="number"){const n=e.fillColor;i=Math.abs(n)<=257?T(n,r.foreground??"#ffffff",r.foreground??"#ffffff"):z(n,r.trueColorByteOrder??"rgb")}return!i&&typeof e.fillColorIndex=="number"&&(i=T(e.fillColorIndex,r.foreground??"#ffffff",r.foreground??"#ffffff")),i?$t(i,r):void 0}function $t(e,t={}){if(t.contrastMode!=="adaptive")return e;const r=t.background??"#0b1020",i=t.foreground??"#ffffff";return Oe(e,r,i,t.minColorContrast??2.4)}function Oe(e,t,r,i=2.4){const s=lt(r)??{r:255,g:255,b:255,a:1},n=lt(t)??{r:11,g:16,b:32,a:1},o=lt(e);if(!o)return e;const a=qt(o,n);if(ft(a,n)>=i)return e;const c=ht(n),l=c<.5?{r:255,g:255,b:255,a:o.a}:{r:0,g:0,b:0,a:o.a};for(const h of[.25,.4,.55,.7,.85,1]){const f=Ue(o,l,h);if(ft(qt(f,n),n)>=i)return Kt(f)}return ft(s,n)>=i?Kt(s):c<.5?"#ffffff":"#000000"}function jt(e){return e?e.isVisible!==!1&&e.isFrozen!==!0:!0}function ze(e,t){if(!e)return;const r=t.foreground??"#ffffff",i=Y(e.trueColor);if(i)return i;if(typeof e.trueColor=="number"&&e.trueColor>=0&&e.trueColor<=16777215)return z(e.trueColor,t.trueColorByteOrder??"rgb");const s=Y(e.color);if(s)return s;if(He(e.colorIndex))return T(e.colorIndex,r,r);if(typeof e.color=="number"){const n=Number(e.color);return Math.abs(n)<=257?T(n,r,r):z(n,t.trueColorByteOrder??"rgb")}if(typeof e.colorIndex=="number")return T(e.colorIndex,r,r)}function Ye(e){return Zt(e.colorIndex,e.colorNumber,e.aci)===0?!0:e.trueColor===void 0&&e.color===0}function Gt(e,t,r,i={}){if(!Ye(e))return e;const s=F(t,r,i);return{...e,color:s,trueColor:void 0,colorIndex:void 0,colorNumber:void 0}}function He(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(Math.trunc(e))>=1&&Math.abs(Math.trunc(e))<=255}function Xe(e,t){if(!(!e||!t))return e.layers[t]??e.layers[t.toLowerCase()]??Object.values(e.layers).find(r=>r.name.toLowerCase()===t.toLowerCase())}function Zt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function _e(e,t){const r=e;for(const i of t){const s=r[i];if(typeof s=="number"&&Number.isFinite(s))return s}}function lt(e){const t=e.trim().toLowerCase();if(/^#[0-9a-f]{3}$/i.test(t))return{r:parseInt(t[1]+t[1],16),g:parseInt(t[2]+t[2],16),b:parseInt(t[3]+t[3],16),a:1};if(/^#[0-9a-f]{6}$/i.test(t))return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16),a:1};const r=t.match(/^rgba?\(([^)]+)\)$/i);if(r){const i=r[1].split(/[,\s/]+/).filter(Boolean).map(s=>Number(s.replace("%","")));if(i.length>=3&&i.slice(0,3).every(Number.isFinite)){const s=/%/.test(r[1]);return{r:H(s?i[0]*2.55:i[0]),g:H(s?i[1]*2.55:i[1]),b:H(s?i[2]*2.55:i[2]),a:Number.isFinite(i[3])?Math.max(0,Math.min(1,i[3])):1}}}}function qt(e,t){const r=e.a+t.a*(1-e.a);return r<=0?{r:0,g:0,b:0,a:0}:{r:(e.r*e.a+t.r*t.a*(1-e.a))/r,g:(e.g*e.a+t.g*t.a*(1-e.a))/r,b:(e.b*e.a+t.b*t.a*(1-e.a))/r,a:r}}function Ue(e,t,r){const i=Math.max(0,Math.min(1,r));return{r:e.r+(t.r-e.r)*i,g:e.g+(t.g-e.g)*i,b:e.b+(t.b-e.b)*i,a:e.a}}function ht(e){const t=[e.r,e.g,e.b].map(r=>{const i=r/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4});return .2126*t[0]+.7152*t[1]+.0722*t[2]}function ft(e,t){const r=ht(e),i=ht(t),s=Math.max(r,i),n=Math.min(r,i);return(s+.05)/(n+.05)}function Kt(e){const t=H(e.r),r=H(e.g),i=H(e.b);return e.a<.999?`rgba(${t}, ${r}, ${i}, ${dt(e.a)})`:`rgb(${t}, ${r}, ${i})`}function H(e){return Math.max(0,Math.min(255,Math.round(e)))}function dt(e){return Math.round(e*1e3)/1e3}function ut(e,t){return{a:e.a*t.a+e.c*t.b,b:e.b*t.a+e.d*t.b,c:e.a*t.c+e.c*t.d,d:e.b*t.c+e.d*t.d,e:e.a*t.e+e.c*t.f+e.e,f:e.b*t.e+e.d*t.f+e.f}}function Jt(e,t){return{a:1,b:0,c:0,d:1,e,f:t}}function Ve(e){const t=Math.cos(e),r=Math.sin(e);return{a:t,b:r,c:-r,d:t,e:0,f:0}}function $e(e,t=e){return{a:e,b:0,c:0,d:t,e:0,f:0}}function M(e,t){return{x:e.x*t.a+e.y*t.c+t.e,y:e.x*t.b+e.y*t.d+t.f,z:"z"in e?e.z:void 0}}function Qt(e,t){if(e)return e.map(r=>({cmd:r.cmd,points:r.points.map(i=>M(i,t))}))}function rt(e,t={x:0,y:0}){const r=e.insertionPoint??{x:0,y:0},i=e.scale,s=Number(typeof i=="object"&&i?i.x??1:e.scaleX??1),n=Number(typeof i=="object"&&i?i.y??s:e.scaleY??s),o=Number(e.rotation??0);let a=Jt(r.x,r.y);return a=ut(a,Ve(Number.isFinite(o)?o:0)),a=ut(a,$e(Number.isFinite(s)?s:1,Number.isFinite(n)?n:1)),a=ut(a,Jt(-t.x,-t.y)),a}function it(e,t){const r={...e,raw:e.raw??e};if(e.startPoint&&(r.startPoint=M(e.startPoint,t)),e.endPoint&&(r.endPoint=M(e.endPoint,t)),e.center&&(r.center=M(e.center,t)),e.insertionPoint&&(r.insertionPoint=M(e.insertionPoint,t)),e.majorAxisEndPoint){const s=M({x:0,y:0},t),n=M(e.majorAxisEndPoint,t);r.majorAxisEndPoint={x:n.x-s.x,y:n.y-s.y,z:n.z}}e.vertices&&(r.vertices=e.vertices.map(s=>({...M(s,t),bulge:s.bulge,startWidth:s.startWidth,endWidth:s.endWidth}))),e.points&&(r.points=e.points.map(s=>M(s,t))),e.controlPoints&&(r.controlPoints=e.controlPoints.map(s=>M(s,t))),e.fitPoints&&(r.fitPoints=e.fitPoints.map(s=>M(s,t))),e.commands&&(r.commands=Qt(e.commands,t)),e.loops&&(r.loops=e.loops.map(s=>{var n;return{...s,vertices:(n=s.vertices)==null?void 0:n.map(o=>M(o,t)),commands:Qt(s.commands,t)}}));const i=Math.sqrt(Math.abs(t.a*t.d-t.b*t.c));return typeof e.radius=="number"&&Number.isFinite(i)&&(r.radius=e.radius*i),r}const je={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class mt{constructor(t,r={}){d(this,"canvas");d(this,"ctx");d(this,"opts");d(this,"document");d(this,"bounds",E());d(this,"view",{centerX:0,centerY:0,scale:1});d(this,"fitScale",1);d(this,"dpr",1);d(this,"isDragging",!1);d(this,"lastPointer");d(this,"resizeObserver");d(this,"imageCache",new Map);d(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"});d(this,"onStats");d(this,"onViewChange");const i=t.getContext("2d");if(!i)throw new Error("Canvas 2D context is not available.");this.canvas=t,this.ctx=i,this.opts={...je,...r},this.canvas.classList.add("cad-viewer-canvas"),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t)),this.resize()}destroy(){var t;(t=this.resizeObserver)==null||t.disconnect()}clear(){this.document=void 0,this.bounds=E(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange()}setDocument(t){this.document=t,this.bounds=this.computeBounds(t),this.fitToView()}getDocument(){return this.document}setOptions(t){Object.assign(this.opts,t),this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(t=.92){if(!D(this.bounds)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const r=Math.max(1,this.cssWidth),i=Math.max(1,this.cssHeight),s=Math.max(this.bounds.maxX-this.bounds.minX,1e-9),n=Math.max(this.bounds.maxY-this.bounds.minY,1e-9),o=this.clampScale(Math.min(r/s,i/n)*t);this.fitScale=o,this.view={centerX:(this.bounds.minX+this.bounds.maxX)/2,centerY:(this.bounds.minY+this.bounds.maxY)/2,scale:o},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const t=Math.max(1,Math.floor(this.cssWidth*this.dpr)),r=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==t||this.canvas.height!==r)&&(this.canvas.width=t,this.canvas.height=r),this.render(),this.emitViewChange()}zoom(t,r){if(!Number.isFinite(t)||t<=0)return;const i=r??{x:this.cssWidth/2,y:this.cssHeight/2},s=this.screenToWorld(i);this.view.scale=this.clampScale(this.view.scale*t);const n=this.screenToWorld(i);this.view.centerX+=s.x-n.x,this.view.centerY+=s.y-n.y,this.render(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(t,r){!Number.isFinite(t)||!Number.isFinite(r)||(this.view.centerX-=t/this.view.scale,this.view.centerY+=r/this.view.scale,this.render(),this.emitViewChange())}setViewState(t){if(![t.centerX,t.centerY,t.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...t,scale:this.clampScale(t.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return Ge(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(t){return{x:this.cssWidth/2+(t.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(t.y-this.view.centerY)*this.view.scale}}screenToWorld(t){return{x:this.view.centerX+(t.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(t.y-this.cssHeight/2)/this.view.scale}}render(){var r,i;const t=performance.now();if(this.stats={total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"},this.clearCanvas(),this.document){this.opts.showPageBounds&&((r=this.document.pages)!=null&&r.length)&&this.drawPageBounds(this.document);for(const s of this.document.entities)this.drawEntityTracked(s,0)}return this.stats.renderElapsedMs=performance.now()-t,(i=this.onStats)==null||i.call(this,this.getStats()),this.getStats()}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}bindEvents(){this.canvas.addEventListener("wheel",r=>{r.preventDefault();const i=r.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(i,{x:r.offsetX,y:r.offsetY})},{passive:!1}),this.canvas.addEventListener("pointerdown",r=>{this.canvas.setPointerCapture(r.pointerId),this.isDragging=!0,this.lastPointer={x:r.clientX,y:r.clientY},this.canvas.classList.add("is-dragging")}),this.canvas.addEventListener("pointermove",r=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(r.clientX-this.lastPointer.x,r.clientY-this.lastPointer.y),this.lastPointer={x:r.clientX,y:r.clientY})});const t=r=>{r&&this.canvas.hasPointerCapture(r.pointerId)&&this.canvas.releasePointerCapture(r.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",t),this.canvas.addEventListener("pointercancel",()=>t())}clearCanvas(){const t=this.ctx;t.save(),t.setTransform(this.dpr,0,0,this.dpr,0,0),t.clearRect(0,0,this.cssWidth,this.cssHeight),t.fillStyle=this.opts.background,t.fillRect(0,0,this.cssWidth,this.cssHeight),t.restore()}drawPageBounds(t){const r=this.ctx;r.save(),r.setTransform(this.dpr,0,0,this.dpr,0,0),r.strokeStyle="rgba(148, 163, 184, 0.35)",r.lineWidth=1,r.setLineDash([8,6]);for(const i of t.pages??[]){const s=this.worldToScreen({x:0,y:0}),n=this.worldToScreen({x:i.width,y:i.height});r.strokeRect(Math.min(s.x,n.x),Math.min(s.y,n.y),Math.abs(n.x-s.x),Math.abs(n.y-s.y))}r.restore()}drawEntityTracked(t,r){this.stats.total++;const i=String(t.type??"UNKNOWN").toUpperCase();this.stats.byType[i]=(this.stats.byType[i]??0)+1;const s=this.lookupLayer(t.layer);if(t.isVisible===!1||!jt(s)){this.stats.skipped++;return}this.drawEntity(t,i,r)}drawEntity(t,r,i){switch(t.kind??A(r)){case"line":return this.drawLine(t);case"circle":return this.drawCircle(t);case"arc":return this.drawArc(t);case"polyline":return this.drawPolyline(t);case"ellipse":return this.drawEllipse(t);case"text":return this.drawText(t);case"point":return this.drawPoint(t);case"insert":return this.drawInsert(t,i);case"solid":return this.drawSolid(t);case"hatch":return this.drawHatch(t);case"spline":return this.drawSpline(t);case"path":return this.drawPath(t);case"image":return this.drawImage(t);case"viewport":return this.markSkipped(r);default:this.stats.unsupported[r]=(this.stats.unsupported[r]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.drawUnsupportedMarker(t)}}beginStyledPath(t,r=!1){const i=this.ctx;i.save(),i.setTransform(this.dpr,0,0,this.dpr,0,0);const s=F(t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),n=ct(t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast})??s;i.strokeStyle=s,i.fillStyle=r?n:s,i.globalAlpha=O(Number(t.opacity??1),0,1),i.lineCap="round",i.lineJoin="round";const o=typeof t.lineweight=="number"&&t.lineweight>0?t.lineweight:0;i.lineWidth=Math.max(1,Math.min(12,o>0?o/30:1)),i.beginPath()}finishStroke(){this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}finishFillStroke(t=!1){t&&this.ctx.fill(),this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}drawLine(t){const r=t.startPoint,i=t.endPoint;if(!m(r)||!m(i))return this.markSkipped("LINE");const s=this.worldToScreen(r),n=this.worldToScreen(i);this.beginStyledPath(t),this.ctx.moveTo(s.x,s.y),this.ctx.lineTo(n.x,n.y),this.finishStroke()}drawCircle(t){const r=t.center,i=Number(t.radius);if(!m(r)||!Number.isFinite(i))return this.markSkipped("CIRCLE");const s=this.worldToScreen(r);this.beginStyledPath(t),this.ctx.arc(s.x,s.y,Math.abs(i)*this.view.scale,0,Math.PI*2),this.finishStroke()}drawArc(t){const r=t.center,i=Number(t.radius),s=Number(t.startAngle),n=Number(t.endAngle);if(!m(r)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(n))return this.markSkipped("ARC");this.strokeWorldPolyline(t,J(x(r),i,s,n,!0),!1)}drawPolyline(t){const r=t.vertices??t.points;if(!Array.isArray(r)||r.length<2)return this.markSkipped(String(t.type));const i=!!t.isClosed||(Number(t.flag)&1)===1,s=[],n=i?r.length:r.length-1;for(let o=0;o<n;o++){const a=r[o],c=r[(o+1)%r.length];if(!m(a)||!m(c))continue;const l=Bt(a,c,Number(a.bulge??0));s.length>0&&l.shift(),s.push(...l)}this.strokeWorldPolyline(t,s,i)}drawEllipse(t){const r=t.center,i=t.majorAxisEndPoint,s=Number(t.axisRatio??1);if(!m(r)||!m(i))return this.markSkipped("ELLIPSE");const n=Q(r,i,s,Number(t.startAngle??0),Number(t.endAngle??Math.PI*2)),o=Math.abs(Number(t.endAngle??Math.PI*2)-Number(t.startAngle??0))>=Math.PI*2-1e-6;this.strokeWorldPolyline(t,n,o)}drawPoint(t){const r=t.point??t.location??t.center??t.insertionPoint;if(!m(r))return this.markSkipped("POINT");const i=this.worldToScreen(r);this.beginStyledPath(t),this.ctx.moveTo(i.x-3,i.y),this.ctx.lineTo(i.x+3,i.y),this.ctx.moveTo(i.x,i.y-3),this.ctx.lineTo(i.x,i.y+3),this.finishStroke()}drawText(t){const r=t.insertionPoint??t.startPoint??t.center,i=Ft(String(t.text??t.value??"")),s=Number(t.textHeight??t.height??1);if(!m(r)||!i)return this.markSkipped(String(t.type));this.drawTextAt(t,r,i,s,Number(t.rotation??0))}drawInsert(t,r){const i=this.lookupBlock(t.blockName??t.name);if(i&&r<this.opts.maxInsertDepth){const a=rt(t,i.basePoint??{x:0,y:0});for(const c of i.entities){const l=Gt(c,t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast});this.drawEntityTracked(it(l,a),r+1)}return}const s=t.insertionPoint;if(!m(s))return this.markSkipped("INSERT");const n=this.worldToScreen(s);this.beginStyledPath(t);const o=5;if(this.ctx.rect(n.x-o,n.y-o,o*2,o*2),this.finishStroke(),Array.isArray(t.attribs))for(const a of t.attribs)this.drawText(a)}drawSolid(t){const r=t.vertices??t.points;if(!Array.isArray(r)||r.length<3)return this.markSkipped(String(t.type));this.beginStyledPath(t,!0);const i=this.worldToScreen(r[0]);this.ctx.moveTo(i.x,i.y);for(const s of r.slice(1)){if(!m(s))continue;const n=this.worldToScreen(s);this.ctx.lineTo(n.x,n.y)}this.ctx.closePath(),this.finishFillStroke(!0)}drawHatch(t){var i,s;const r=t.loops;if(!Array.isArray(r)||r.length===0)return this.markSkipped("HATCH");this.beginStyledPath(t,!0);for(const n of r)if((i=n.commands)!=null&&i.length)this.addPathCommands(n.commands);else if((s=n.vertices)!=null&&s.length){const o=this.worldToScreen(n.vertices[0]);this.ctx.moveTo(o.x,o.y);for(const a of n.vertices.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}this.ctx.closePath()}this.finishFillStroke(!!ct(t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}))}drawSpline(t){var i;const r=(i=t.fitPoints)!=null&&i.length?t.fitPoints:t.controlPoints;if(!r||r.length<2)return this.markSkipped("SPLINE");this.strokeWorldPolyline(t,r,!!t.isClosed)}drawPath(t){var r;if(!((r=t.commands)!=null&&r.length))return this.markSkipped(String(t.type));this.beginStyledPath(t,!!t.fillColor),this.addPathCommands(t.commands),this.finishFillStroke(!!t.fillColor)}addPathCommands(t){for(const r of t)if(r.cmd==="M"){const i=this.worldToScreen(r.points[0]);this.ctx.moveTo(i.x,i.y)}else if(r.cmd==="L"){const i=this.worldToScreen(r.points[0]);this.ctx.lineTo(i.x,i.y)}else if(r.cmd==="C"){const[i,s,n]=r.points.map(o=>this.worldToScreen(o));this.ctx.bezierCurveTo(i.x,i.y,s.x,s.y,n.x,n.y)}else if(r.cmd==="Q"){const[i,s]=r.points.map(n=>this.worldToScreen(n));this.ctx.quadraticCurveTo(i.x,i.y,s.x,s.y)}else r.cmd==="Z"&&this.ctx.closePath()}drawImage(t){const r=t.insertionPoint;if(!m(r))return this.markSkipped(String(t.type));const i=Number(t.width??32),s=Number(t.height??32),n=this.worldToScreen(r),o=this.worldToScreen({x:r.x+i,y:r.y-s}),a=Math.min(n.x,o.x),c=Math.min(n.y,o.y),l=Math.abs(o.x-n.x),h=Math.abs(o.y-n.y),f=t.imageDataUrl;if(f){const u=this.getImage(f);if(u.complete&&u.naturalWidth>0){this.ctx.save(),this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0),this.ctx.drawImage(u,a,c,l,h),this.ctx.restore(),this.stats.drawn++;return}u.onload=()=>this.render()}if(!this.opts.showImagePlaceholders)return this.markSkipped(String(t.type));this.beginStyledPath(t),this.ctx.rect(a,c,l,h),this.ctx.moveTo(a,c),this.ctx.lineTo(a+l,c+h),this.ctx.moveTo(a+l,c),this.ctx.lineTo(a,c+h),this.finishStroke()}getImage(t){let r=this.imageCache.get(t);return r||(r=new Image,r.src=t,this.imageCache.set(t,r)),r}drawUnsupportedMarker(t){const r=this.entityAnchor(t);if(!r)return;const i=this.worldToScreen(r);this.beginStyledPath(t),this.ctx.moveTo(i.x-4,i.y-4),this.ctx.lineTo(i.x+4,i.y+4),this.ctx.moveTo(i.x+4,i.y-4),this.ctx.lineTo(i.x-4,i.y+4),this.finishStroke()}drawTextAt(t,r,i,s,n){const o=this.ctx,a=this.worldToScreen(r);o.save(),o.setTransform(this.dpr,0,0,this.dpr,0,0),o.translate(a.x,a.y),o.rotate(-n);const c=Math.max(4,Math.min(256,Math.abs(s)*this.view.scale));o.font=`${c}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,o.fillStyle=F(t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),o.globalAlpha=O(Number(t.opacity??1),0,1),o.textBaseline="alphabetic";for(const[l,h]of i.split(/\r?\n/g).entries())o.fillText(h,0,l*c*1.22);o.restore(),this.stats.drawn++}strokeWorldPolyline(t,r,i){const s=r.filter(m);if(s.length<2)return this.markSkipped(String(t.type));this.beginStyledPath(t);const n=this.worldToScreen(s[0]);this.ctx.moveTo(n.x,n.y);for(const o of s.slice(1)){const a=this.worldToScreen(o);this.ctx.lineTo(a.x,a.y)}i&&this.ctx.closePath(),this.finishStroke()}markSkipped(t){this.stats.skipped++,this.stats.unsupported[t]=this.stats.unsupported[t]??0}entityAnchor(t){for(const r of["startPoint","insertionPoint","center","point","location"]){const i=t[r];if(m(i))return x(i)}if(Array.isArray(t.vertices)&&m(t.vertices[0]))return x(t.vertices[0]);if(Array.isArray(t.commands)&&t.commands.length){const r=t.commands.find(i=>i.points.length>0);if(r)return x(r.points[0])}}computeBounds(t){var i;const r=E();if((i=t.pages)!=null&&i.length)for(const s of t.pages)v(r,{x:0,y:0}),v(r,{x:s.width,y:s.height});for(const s of t.entities)this.includeEntityBounds(r,s,0);return At(r)}includeEntityBounds(t,r,i){const s=String(r.type??"").toUpperCase(),n=r.kind??A(s);if(n==="insert"){const o=this.lookupBlock(r.blockName??r.name);if(o&&i<this.opts.maxInsertDepth){const a=rt(r,o.basePoint??{x:0,y:0});for(const c of o.entities)this.includeEntityBounds(t,it(c,a),i+1);return}}if(n==="line")m(r.startPoint)&&v(t,r.startPoint),m(r.endPoint)&&v(t,r.endPoint);else if(n==="circle"||n==="arc")m(r.center)&&Number.isFinite(r.radius)&&Lt(t,r.center,Number(r.radius));else if(n==="polyline"||n==="solid"||n==="spline")for(const o of[...r.vertices??[],...r.points??[],...r.controlPoints??[],...r.fitPoints??[]])m(o)&&v(t,o);else if(n==="ellipse")m(r.center)&&m(r.majorAxisEndPoint)&&Q(r.center,r.majorAxisEndPoint,Number(r.axisRatio??1),Number(r.startAngle??0),Number(r.endAngle??Math.PI*2)).forEach(o=>v(t,o));else if(n==="path")for(const o of r.commands??[])for(const a of o.points)v(t,a);else if(n==="hatch")for(const o of r.loops??[]){for(const a of o.vertices??[])v(t,a);for(const a of o.commands??[])for(const c of a.points)v(t,c)}else{const o=this.entityAnchor(r);o&&v(t,o)}}lookupLayer(t){if(!(!this.document||!t))return this.document.layers[t]??this.document.layers[t.toLowerCase()]??Object.values(this.document.layers).find(r=>r.name.toLowerCase()===t.toLowerCase())}lookupBlock(t){if(!(!this.document||!t))return this.document.blocks[t]??this.document.blocks[t.toLowerCase()]??Object.values(this.document.blocks).find(r=>r.name.toLowerCase()===t.toLowerCase())}clampScale(t){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,t))}emitViewChange(){var t;(t=this.onViewChange)==null||t.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function Ge(e){return{total:e.total,drawn:e.drawn,skipped:e.skipped,byType:{...e.byType},unsupported:{...e.unsupported},renderElapsedMs:e.renderElapsedMs,backend:e.backend,primitiveCount:e.primitiveCount,visiblePrimitiveCount:e.visiblePrimitiveCount,culledPrimitiveCount:e.culledPrimitiveCount,gpuMemoryBytes:e.gpuMemoryBytes,buildElapsedMs:e.buildElapsedMs}}const Ze={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class pt{constructor(t,r={}){d(this,"canvas");d(this,"backend","webgl");d(this,"gl");d(this,"program");d(this,"eventController",new AbortController);d(this,"imageCache",new Map);d(this,"opts");d(this,"document");d(this,"bounds",E());d(this,"view",{centerX:0,centerY:0,scale:1});d(this,"fitScale",1);d(this,"dpr",1);d(this,"isDragging",!1);d(this,"lastPointer");d(this,"resizeObserver");d(this,"overlayCanvas");d(this,"overlayCtx");d(this,"scene");d(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});d(this,"rafHandle",0);d(this,"onStats");d(this,"onViewChange");const i=qe(t,r);if(!i)throw new Error('WebGL is not available. Use renderer: "canvas2d" to force the Canvas2D fallback.');this.canvas=t,this.gl=i,this.program=Ke(i),this.opts={...Ze,...r},this.canvas.classList.add("cad-viewer-canvas","cad-viewer-webgl-canvas"),this.createOverlayCanvas(),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t)),this.resize()}static isSupported(){return gt()}destroy(){var t,r;this.eventController.abort(),(t=this.resizeObserver)==null||t.disconnect(),this.cancelScheduledRender(),this.disposeScene(),(r=this.overlayCanvas)==null||r.remove()}clear(){this.document=void 0,this.bounds=E(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.disposeScene(),this.render(),this.emitViewChange()}setDocument(t){this.document=t,this.bounds=ir(t,this.opts),this.disposeScene();const r=Qe(t,this.opts,this.bounds);this.scene=Je(this.gl,r),this.stats=or(this.scene,0),this.fitToView()}getDocument(){return this.document}setOptions(t){const r=nr(this.opts,t);if(this.opts={...this.opts,...t},r&&this.document){this.setDocument(this.document);return}this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(t=.92){if(!D(this.bounds)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const r=Math.max(1,this.cssWidth),i=Math.max(1,this.cssHeight),s=Math.max(this.bounds.maxX-this.bounds.minX,1e-9),n=Math.max(this.bounds.maxY-this.bounds.minY,1e-9),o=this.clampScale(Math.min(r/s,i/n)*t);this.fitScale=o,this.view={centerX:(this.bounds.minX+this.bounds.maxX)/2,centerY:(this.bounds.minY+this.bounds.maxY)/2,scale:o},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const t=Math.max(1,Math.floor(this.cssWidth*this.dpr)),r=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==t||this.canvas.height!==r)&&(this.canvas.width=t,this.canvas.height=r),this.resizeOverlay(t,r),this.render(),this.emitViewChange()}zoom(t,r){if(!Number.isFinite(t)||t<=0)return;const i=r??{x:this.cssWidth/2,y:this.cssHeight/2},s=this.screenToWorld(i);this.view.scale=this.clampScale(this.view.scale*t);const n=this.screenToWorld(i);this.view.centerX+=s.x-n.x,this.view.centerY+=s.y-n.y,this.scheduleRender(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(t,r){!Number.isFinite(t)||!Number.isFinite(r)||(this.view.centerX-=t/this.view.scale,this.view.centerY+=r/this.view.scale,this.scheduleRender(),this.emitViewChange())}setViewState(t){if(![t.centerX,t.centerY,t.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...t,scale:this.clampScale(t.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return ar(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(t){return{x:this.cssWidth/2+(t.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(t.y-this.view.centerY)*this.view.scale}}screenToWorld(t){return{x:this.view.centerX+(t.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(t.y-this.cssHeight/2)/this.view.scale}}render(){return this.cancelScheduledRender(),this.renderNow()}renderNow(){var l;const t=performance.now(),r=this.gl;r.viewport(0,0,this.canvas.width,this.canvas.height);const i=wt(this.opts.background,[11,16,32,255]);r.clearColor(i[0]/255,i[1]/255,i[2]/255,i[3]/255),r.clear(r.COLOR_BUFFER_BIT),r.disable(r.DEPTH_TEST),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA);let s=0,n=0;const o=this.scene,a=this.visibleWorldBounds();if(o){r.useProgram(this.program.program),r.uniform2f(this.program.uViewCenter,this.view.centerX-o.origin.x,this.view.centerY-o.origin.y),r.uniform1f(this.program.uScale,this.view.scale*this.dpr),r.uniform2f(this.program.uViewport,this.canvas.width,this.canvas.height),r.uniform1f(this.program.uPointSize,Math.max(2,Math.min(12,4*this.dpr)));const h=this.drawBatches(o.lineBatches,r.LINES,a);s+=h.visible,n+=h.culled;const f=this.drawBatches(o.triangleBatches,r.TRIANGLES,a);s+=f.visible,n+=f.culled;const u=this.drawBatches(o.pointBatches,r.POINTS,a);s+=u.visible,n+=u.culled}this.renderOverlay(a);const c=performance.now()-t;return this.stats=o?{...o.stats,renderElapsedMs:c,backend:"webgl",primitiveCount:o.primitiveCount,visiblePrimitiveCount:s,culledPrimitiveCount:n,gpuMemoryBytes:o.gpuMemoryBytes,buildElapsedMs:o.buildElapsedMs}:{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:c,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0},(l=this.onStats)==null||l.call(this,this.getStats()),this.getStats()}drawBatches(t,r,i){const s=this.gl;let n=0,o=0;for(const a of t){if(!yt(a.bounds,i)){o+=a.primitiveCount;continue}s.bindBuffer(s.ARRAY_BUFFER,a.positionBuffer),s.enableVertexAttribArray(this.program.aPosition),s.vertexAttribPointer(this.program.aPosition,2,s.FLOAT,!1,0,0),s.bindBuffer(s.ARRAY_BUFFER,a.colorBuffer),s.enableVertexAttribArray(this.program.aColor),s.vertexAttribPointer(this.program.aColor,4,s.UNSIGNED_BYTE,!0,0,0),s.drawArrays(r,0,a.vertexCount),n+=a.primitiveCount}return{visible:n,culled:o}}scheduleRender(){this.rafHandle||(this.rafHandle=window.requestAnimationFrame(()=>{this.rafHandle=0,this.renderNow()}))}cancelScheduledRender(){this.rafHandle&&(window.cancelAnimationFrame(this.rafHandle),this.rafHandle=0)}renderOverlay(t){var s,n;const r=this.overlayCtx,i=this.overlayCanvas;!r||!i||(r.save(),r.setTransform(this.dpr,0,0,this.dpr,0,0),r.clearRect(0,0,this.cssWidth,this.cssHeight),this.opts.showPageBounds&&((n=(s=this.document)==null?void 0:s.pages)!=null&&n.length)&&this.drawPageBoundsOverlay(r),this.scene&&(this.drawImagesOverlay(r,this.scene.imageItems,t),this.drawTextOverlay(r,this.scene.textItems,t)),r.restore())}drawPageBoundsOverlay(t){var r,i;if((i=(r=this.document)==null?void 0:r.pages)!=null&&i.length){t.save(),t.strokeStyle="rgba(148, 163, 184, 0.34)",t.lineWidth=1,t.setLineDash([8,6]);for(const s of this.document.pages){const n=this.worldToScreen({x:0,y:0}),o=this.worldToScreen({x:s.width,y:s.height});t.strokeRect(Math.min(n.x,o.x),Math.min(n.y,o.y),Math.abs(o.x-n.x),Math.abs(o.y-n.y))}t.restore()}}drawTextOverlay(t,r,i){const s=this.opts.maxVisibleTextLabels;let n=0;for(const o of r){if(n>=s)break;if(!yt(o.bounds,i))continue;const a=Math.abs(o.height)*this.view.scale;if(a<this.opts.textMinPixelHeight)continue;const c=this.worldToScreen(o.point);if(c.x<-512||c.y<-512||c.x>this.cssWidth+512||c.y>this.cssHeight+512)continue;t.save(),t.translate(c.x,c.y),t.rotate(-o.rotation);const l=Math.max(4,Math.min(256,a));t.font=`${l}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,t.fillStyle=o.color,t.globalAlpha=o.opacity,t.textBaseline="alphabetic";for(const[h,f]of o.text.split(/\r?\n/g).entries())t.fillText(f,0,h*l*1.22);t.restore(),n++}}drawImagesOverlay(t,r,i){for(const s of r){if(!yt(s.bounds,i))continue;const n=this.worldToScreen(s.point),o=this.worldToScreen({x:s.point.x+s.width,y:s.point.y-s.height}),a=Math.min(n.x,o.x),c=Math.min(n.y,o.y),l=Math.abs(o.x-n.x),h=Math.abs(o.y-n.y);if(!(l<1||h<1)){if(s.source){const f=this.getImage(s.source);if(f.complete&&f.naturalWidth>0){t.save(),t.globalAlpha=s.opacity,t.drawImage(f,a,c,l,h),t.restore();continue}f.onload=()=>this.scheduleRender()}this.opts.showImagePlaceholders&&(t.save(),t.strokeStyle=s.color,t.globalAlpha=s.opacity,t.lineWidth=1,t.strokeRect(a,c,l,h),t.beginPath(),t.moveTo(a,c),t.lineTo(a+l,c+h),t.moveTo(a+l,c),t.lineTo(a,c+h),t.stroke(),t.restore())}}}getImage(t){let r=this.imageCache.get(t);return r||(r=new Image,r.src=t,this.imageCache.set(t,r)),r}createOverlayCanvas(){const t=this.canvas.parentElement;if(!t||typeof document>"u")return;window.getComputedStyle(t).position==="static"&&(t.style.position="relative");const i=document.createElement("canvas");i.className="cad-viewer-text-overlay",i.setAttribute("aria-hidden","true"),i.style.position="absolute",i.style.inset="0",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.zIndex="1";const s=i.getContext("2d");s&&(t.appendChild(i),this.overlayCanvas=i,this.overlayCtx=s)}resizeOverlay(t,r){this.overlayCanvas&&(this.overlayCanvas.width!==t||this.overlayCanvas.height!==r)&&(this.overlayCanvas.width=t,this.overlayCanvas.height=r)}bindEvents(){const t=this.eventController.signal;this.canvas.addEventListener("wheel",i=>{i.preventDefault();const s=i.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(s,{x:i.offsetX,y:i.offsetY})},{passive:!1,signal:t}),this.canvas.addEventListener("pointerdown",i=>{this.canvas.setPointerCapture(i.pointerId),this.isDragging=!0,this.lastPointer={x:i.clientX,y:i.clientY},this.canvas.classList.add("is-dragging")},{signal:t}),this.canvas.addEventListener("pointermove",i=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(i.clientX-this.lastPointer.x,i.clientY-this.lastPointer.y),this.lastPointer={x:i.clientX,y:i.clientY})},{signal:t});const r=i=>{i&&this.canvas.hasPointerCapture(i.pointerId)&&this.canvas.releasePointerCapture(i.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",r,{signal:t}),this.canvas.addEventListener("pointercancel",()=>r(),{signal:t}),this.canvas.addEventListener("webglcontextlost",i=>{i.preventDefault(),this.cancelScheduledRender()},{signal:t})}visibleWorldBounds(){const t=this.cssWidth/Math.max(this.view.scale,1e-12)/2,r=this.cssHeight/Math.max(this.view.scale,1e-12)/2;return{minX:this.view.centerX-t,maxX:this.view.centerX+t,minY:this.view.centerY-r,maxY:this.view.centerY+r}}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}clampScale(t){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,t))}disposeScene(){if(!this.scene)return;const t=this.gl;for(const r of[...this.scene.lineBatches,...this.scene.triangleBatches,...this.scene.pointBatches])t.deleteBuffer(r.positionBuffer),t.deleteBuffer(r.colorBuffer);this.scene=void 0}emitViewChange(){var t;(t=this.onViewChange)==null||t.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function gt(){if(typeof document>"u")return!1;const e=document.createElement("canvas");return!!(e.getContext("webgl2")??e.getContext("webgl")??e.getContext("experimental-webgl"))}function qe(e,t){const r={alpha:!1,antialias:t.antialias??!0,depth:!1,stencil:!1,preserveDrawingBuffer:t.preserveDrawingBuffer??!1,powerPreference:t.powerPreference??"high-performance"};return e.getContext("webgl2",r)??e.getContext("webgl",r)??e.getContext("experimental-webgl",r)??void 0}function Ke(e){const t=`
|
|
5
|
+
`),r=[];for(let d=0;d<t.length-1;d+=2){const u=Number((l=t[d])==null?void 0:l.trim()),p=t[d+1]??"";Number.isFinite(u)&&r.push({code:u,value:p.trimEnd()})}const i=[],s={};let n="",o=[],a;for(let d=0;d<r.length;d++){const u=r[d];if(u.code===0&&u.value==="SECTION"){n=((h=r[d+1])==null?void 0:h.code)===2?r[d+1].value.toUpperCase():"",d++;continue}if(u.code===0&&u.value==="ENDSEC"){c(),n="";continue}n==="ENTITIES"&&(u.code===0?(c(),o=[u]):o.push(u))}return c(),{header:{},tables:{},entities:i,blocks:s};function c(){var p;if(!o.length)return;const d=(p=o[0])==null?void 0:p.value.toUpperCase();if(d==="VERTEX"&&a){const b=P(o,10,20,30);b&&(a.vertices??(a.vertices=[])).push({...b,bulge:v(o,42)}),o=[];return}if(d==="SEQEND"){a&&i.push(a),a=void 0,o=[];return}if(a&&(i.push(a),a=void 0),!d||d==="EOF"){o=[];return}const u=Ne(d,o);d==="POLYLINE"?a=u:i.push(u),o=[]}}function Ne(e,t){const r={type:e,handle:U(t,5),layer:U(t,8)??"0",colorIndex:v(t,62),trueColor:v(t,420),lineType:U(t,6),lineweight:v(t,370)};switch(e){case"LINE":Object.assign(r,{startPoint:P(t,10,20,30),endPoint:P(t,11,21,31)});break;case"CIRCLE":Object.assign(r,{center:P(t,10,20,30),radius:v(t,40)});break;case"ARC":Object.assign(r,{center:P(t,10,20,30),radius:v(t,40),startAngle:et(v(t,50)),endAngle:et(v(t,51))});break;case"POINT":Object.assign(r,{point:P(t,10,20,30)});break;case"TEXT":case"MTEXT":Object.assign(r,{insertionPoint:P(t,10,20,30),text:Te(t),textHeight:v(t,40),rotation:et(v(t,50))});break;case"LWPOLYLINE":Object.assign(r,{vertices:Ie(t),flag:v(t,70),isClosed:(Number(v(t,70)??0)&1)===1});break;case"POLYLINE":Object.assign(r,{vertices:[],flag:v(t,70),isClosed:(Number(v(t,70)??0)&1)===1});break;case"ELLIPSE":Object.assign(r,{center:P(t,10,20,30),majorAxisEndPoint:P(t,11,21,31),axisRatio:v(t,40),startAngle:v(t,41),endAngle:v(t,42)});break;case"SPLINE":Object.assign(r,{controlPoints:Ee(t,10,20,30),degree:v(t,71),isClosed:(Number(v(t,70)??0)&1)===1});break;case"INSERT":Object.assign(r,{name:U(t,2),blockName:U(t,2),insertionPoint:P(t,10,20,30),rotation:et(v(t,50)),scale:{x:v(t,41)??1,y:v(t,42)??v(t,41)??1,z:v(t,43)??1}});break;case"SOLID":case"TRACE":case"3DFACE":Object.assign(r,{vertices:[P(t,10,20,30),P(t,11,21,31),P(t,12,22,32),P(t,13,23,33)].filter(Boolean)});break}return at(r)}function v(e,t){var s;const r=(s=e.find(n=>n.code===t))==null?void 0:s.value,i=Number(r);return Number.isFinite(i)?i:void 0}function U(e,t){var i;const r=(i=e.find(s=>s.code===t))==null?void 0:i.value;return r&&r.length>0?r:void 0}function P(e,t,r,i){const s=v(e,t),n=v(e,r),o=v(e,i);if(!(s===void 0||n===void 0))return o===void 0?{x:s,y:n}:{x:s,y:n,z:o}}function Ee(e,t,r,i){const s=[];for(let n=0;n<e.length;n++){if(e[n].code!==t)continue;const o=Number(e[n].value),a=e.slice(n+1).find(d=>d.code===r),c=e.slice(n+1).find(d=>d.code===i),l=Number(a==null?void 0:a.value),h=Number(c==null?void 0:c.value);Number.isFinite(o)&&Number.isFinite(l)&&s.push(Number.isFinite(h)?{x:o,y:l,z:h}:{x:o,y:l})}return s}function Ie(e){const t=[];for(let r=0;r<e.length;r++){if(e[r].code!==10)continue;const i=Number(e[r].value);let s,n;for(let o=r+1;o<e.length&&e[o].code!==10;o++)e[o].code===20&&(s=Number(e[o].value)),e[o].code===42&&(n=Number(e[o].value));Number.isFinite(i)&&Number.isFinite(s)&&t.push({x:i,y:s,bulge:Number.isFinite(n)?n:void 0})}return t}function Te(e){const t=e.filter(r=>r.code===1||r.code===3).map(r=>r.value);return t.length?t.join(""):void 0}function et(e){return typeof e=="number"&&Number.isFinite(e)?B(e):void 0}class Yt{constructor(t={}){f(this,"id","dwf");f(this,"label","DWF/DWFx native viewer powered by dwf-viewer");f(this,"formats",["dwf","dwfx","xps"]);f(this,"nativeRenderer",!0);f(this,"defaults");f(this,"native");f(this,"host");f(this,"lastStats");this.defaults=t}accepts(t,r){const i=R(t);if(i==="dwf"||i==="dwfx"||i==="xps")return!0;const s=L(t,r);return s==="dwf"||s==="dwfx"||s==="xps"}async load(t,r={}){var d,u,p,b;const i={...this.defaults,...r},s=performance.now(),n=t.fileName??((d=t.file)==null?void 0:d.name),o=await W(t),a=_t(L(t,o),R(t));(u=i.onProgress)==null||u.call(i,{phase:"parse",format:a,message:"Opening DWF/DWFx with dwf-viewer…",percent:48});const c=await C.openDwfDocument(o,{fileName:n});(p=i.onProgress)==null||p.call(i,{phase:"normalize",format:a,message:"Reading DWF pages, sheets and model metadata…",percent:76});const l=Ht(c,n,a,i.keepRaw===!0),h=performance.now()-s;return(b=i.onProgress)==null||b.call(i,{phase:"done",format:l.format,message:"DWF/DWFx document ready.",percent:100,elapsedMs:h}),{document:l,raw:i.keepRaw?c:void 0,bytes:o.byteLength,elapsedMs:h,format:l.format,warnings:l.warnings}}async mount(t,r,i={}){var $,j,G,ae,ce;const s={...this.defaults,...i},n=performance.now(),o=t.fileName??(($=t.file)==null?void 0:$.name),a=await W(t),c=_t(L(t,a),R(t)),l=We(s),h=Ut(s),d=Re(s,l,h),u=Vt(s,l,h);(j=s.onProgress)==null||j.call(s,{phase:"native-render",format:c,message:"Mounting native DWF renderer…",percent:28}),this.unmount(),this.host=r,r.replaceChildren(),this.native=new C.DwfViewer(r,d),(G=s.onProgress)==null||G.call(s,{phase:"parse",format:c,message:"Parsing DWF package and page streams…",percent:58}),await this.native.load(a,{fileName:o,...u}),(ae=s.onProgress)==null||ae.call(s,{phase:"render",format:c,message:"Rendering DWF/DWFx with dwf-viewer…",percent:88}),this.lastStats=await this.native.render();const p=this.native.getDocument(),b=Ht(p,o,c,s.keepRaw===!0);b.metadata.loaderMode="Native DWF",b.metadata.nativeRenderer="dwf-viewer",b.metadata.nativeRenderStats=this.lastStats?{...this.lastStats,warnings:this.lastStats.warnings.length}:void 0;const N=performance.now()-n;return(ce=s.onProgress)==null||ce.call(s,{phase:"done",format:b.format,message:"DWF/DWFx rendered.",percent:100,elapsedMs:N}),{document:b,raw:s.keepRaw?p:void 0,bytes:a.byteLength,elapsedMs:N,format:b.format,warnings:b.warnings}}unmount(){var t;(t=this.native)==null||t.dispose(),this.native=void 0,this.lastStats=void 0,this.host&&this.host.replaceChildren()}fit(){var t;(t=this.native)==null||t.fit()}zoomIn(){var r;const t=(r=this.native)==null?void 0:r.zoomInButton;t==null||t.click()}zoomOut(){var r;const t=(r=this.native)==null?void 0:r.zoomOutButton;t==null||t.click()}resize(){var t;(t=this.native)==null||t.render()}setNativeOptions(t){var i,s,n,o;const r=this.native;if(r){if(typeof t.dwfBackground=="string")r.background=t.dwfBackground;else{const a=Ut(t);a&&(r.background=a)}typeof t.dwfPreferWebgl=="boolean"&&((i=r.setPreferWebgl)==null||i.call(r,t.dwfPreferWebgl)),typeof t.dwfPreferWasm=="boolean"&&((s=r.setPreferWasm)==null||s.call(r,t.dwfPreferWasm)),t.dwfLineWeightMode&&((n=r.setLineWeightMode)==null||n.call(r,t.dwfLineWeightMode)),rt(r,"minStrokeCssPx",t.dwfMinStrokeCssPx),rt(r,"maxOverviewStrokeCssPx",t.dwfMaxOverviewStrokeCssPx),rt(r,"minTextCssPx",t.dwfMinTextCssPx),rt(r,"minFilledAreaCssPx",t.dwfMinFilledAreaCssPx),(o=r.render)==null||o.call(r)}}getLastNativeStats(){return this.lastStats}}function Ht(e,t,r,i){var a,c;const s=Xt((e==null?void 0:e.diagnostics)??[]),n=((e==null?void 0:e.pageData)??[]).map((l,h)=>Le(l,h));for(const l of(e==null?void 0:e.pageData)??[])s.push(...Xt(l.diagnostics));const o={parser:"dwf-viewer",nativeRenderer:"dwf-viewer",dwfKind:e==null?void 0:e.kind,packageEntries:((a=e==null?void 0:e.packageEntries)==null?void 0:a.length)??0,resources:((c=e==null?void 0:e.resources)==null?void 0:c.length)??0,pageKinds:ze(((e==null?void 0:e.pageData)??[]).map(l=>l.kind)),pageNames:((e==null?void 0:e.pages)??[]).map(l=>l.name)};return nt({format:r,sourceName:t,layers:{},blocks:{},pages:n,entities:be(n),metadata:o,warnings:Ye(s),raw:i?e:void 0})}function Le(e,t){const r=Ae(e,t);return{index:t,name:e.name||e.sourcePath||`${t+1}`,width:e.width||1e3,height:e.height||1e3,entities:r}}function Ae(e,t){return e.kind==="w2d-text"?e.primitives.flatMap((r,i)=>Be(r,t,i)):e.kind==="image"?[{type:"DWF_IMAGE_PAGE",kind:"image",pageIndex:t,width:e.width,height:e.height,imageSource:e.sourcePath}]:e.kind==="w3d-model"?e.model.meshes.map((r,i)=>({id:r.id,type:"W3D_MESH",kind:"solid",pageIndex:t,color:r.color?Oe(r.color):void 0,name:r.name||`mesh-${i+1}`,raw:{vertexCount:r.vertexCount,triangleCount:r.triangleCount,materialId:r.materialId}})):e.kind==="xps-fixed-page"?[{type:"XPS_FIXED_PAGE",kind:"viewport",pageIndex:t,width:e.width,height:e.height,raw:{sourcePath:e.sourcePath}}]:[{type:"DWF_PAGE",kind:"viewport",pageIndex:t,width:e.width,height:e.height,raw:{sourcePath:e.sourcePath}}]}function Be(e,t,r){const i={id:`dwf-${t}-${r}`,pageIndex:t,color:e.stroke,fillColor:e.fill,lineweight:e.lineWidth,raw:{matrix:e.matrix}};if(e.type==="polyline"||e.type==="polygon")return[{...i,type:e.type==="polygon"?"DWF_POLYGON":"DWF_POLYLINE",kind:"polyline",vertices:Fe(e.points),isClosed:e.type==="polygon"}];if(e.type==="path")return[{...i,type:"DWF_PATH",kind:"path",commands:e.commands}];if(e.type==="text")return[{...i,type:"DWF_TEXT",kind:"text",insertionPoint:{x:e.x,y:e.y,z:0},text:e.text,textHeight:e.size}];if(e.type==="rect"){const s=e.x,n=e.y,o=e.width,a=e.height;return[{...i,type:"DWF_RECT",kind:"polyline",isClosed:!0,vertices:[{x:s,y:n,z:0},{x:s+o,y:n,z:0},{x:s+o,y:n+a,z:0},{x:s,y:n+a,z:0}]}]}return[]}function Fe(e){const t=[];for(let r=0;r+1<e.length;r+=2)t.push({x:e[r],y:e[r+1],z:0});return t}function Xt(e){return e.filter(t=>t.level!=="info").map(t=>`${t.code}: ${t.message}${t.source?` (${t.source})`:""}`)}function _t(e,t){return t==="dwf"||t==="dwfx"||t==="xps"?t:e==="dwf"||e==="dwfx"||e==="xps"?e:"dwf"}function We(e){if(e.dwfWasmUrl)return e.dwfWasmUrl;if(typeof document>"u")return;const t=e.wasmPath?new URL(De(e.wasmPath),document.baseURI).href:new URL("wasm/",document.baseURI).href;return new URL("dwfv-render.wasm",t).href}function Ut(e){if(e.dwfBackground)return e.dwfBackground;const t=e.canvasOptions;return(t==null?void 0:t.background)??"#05070d"}function Re(e,t,r){return{...Vt(e,t,r),maxDevicePixelRatio:e.dwfMaxDevicePixelRatio??2,maxCanvasPixels:e.dwfMaxCanvasPixels??16777216}}function Vt(e,t,r){return{wasmUrl:t,preferWebgl:e.dwfPreferWebgl??!0,preferWasm:e.dwfPreferWasm??!0,background:r,maxGpuCacheBytes:e.dwfMaxGpuCacheBytes??160*1024*1024,maxCachedScenes:e.dwfMaxCachedScenes??2,lineWeightMode:e.dwfLineWeightMode??"adaptive",minStrokeCssPx:e.dwfMinStrokeCssPx,maxOverviewStrokeCssPx:e.dwfMaxOverviewStrokeCssPx,minTextCssPx:e.dwfMinTextCssPx,minFilledAreaCssPx:e.dwfMinFilledAreaCssPx}}function rt(e,t,r){typeof r=="number"&&Number.isFinite(r)&&(e[t]=r)}function De(e){return e.endsWith("/")?e:`${e}/`}function Oe(e){const[t,r,i]=e.map(s=>Math.max(0,Math.min(255,Math.round(s*255))));return`#${ct(t)}${ct(r)}${ct(i)}`}function ct(e){return e.toString(16).padStart(2,"0")}function ze(e){const t={};for(const r of e)t[r]=(t[r]??0)+1;return t}function Ye(e){return Array.from(new Set(e))}function $t(e={}){return new kt([new It(e),new Rt(e),new Yt(e)])}function jt(e){const t=e;return t.nativeRenderer===!0&&typeof t.mount=="function"}const He={1:"#ff0000",2:"#ffff00",3:"#00ff00",4:"#00ffff",5:"#0000ff",6:"#ff00ff",8:"#808080",9:"#c0c0c0",10:"#ff0000",11:"#ff7f7f",12:"#a50000",13:"#a55252",14:"#7f0000",15:"#7f3f3f",16:"#4c0000",17:"#4c2626",18:"#260000",19:"#261313",20:"#ff3f00",21:"#ff9f7f",22:"#a52900",23:"#a56752",24:"#7f1f00",25:"#7f4f3f",26:"#4c1300",27:"#4c2f26",28:"#260900",29:"#261713",30:"#ff7f00",31:"#ffbf7f",32:"#a55200",33:"#a57c52",34:"#7f3f00",35:"#7f5f3f",36:"#4c2600",37:"#4c3926",38:"#261300",39:"#261c13",40:"#ffbf00",41:"#ffdf7f",42:"#a57c00",43:"#a59152",44:"#7f5f00",45:"#7f6f3f",46:"#4c3900",47:"#4c4226",48:"#261c00",49:"#262113",50:"#ffff00",51:"#ffff7f",52:"#a5a500",53:"#a5a552",54:"#7f7f00",55:"#7f7f3f",56:"#4c4c00",57:"#4c4c26",58:"#262600",59:"#262613",60:"#bfff00",61:"#dfff7f",62:"#7ca500",63:"#91a552",64:"#5f7f00",65:"#6f7f3f",66:"#394c00",67:"#424c26",68:"#1c2600",69:"#212613",70:"#7fff00",71:"#bfff7f",72:"#52a500",73:"#7ca552",74:"#3f7f00",75:"#5f7f3f",76:"#264c00",77:"#394c26",78:"#132600",79:"#1c2613",80:"#3fff00",81:"#9fff7f",82:"#29a500",83:"#67a552",84:"#1f7f00",85:"#4f7f3f",86:"#134c00",87:"#2f4c26",88:"#092600",89:"#172613",90:"#00ff00",91:"#7fff7f",92:"#00a500",93:"#52a552",94:"#007f00",95:"#3f7f3f",96:"#004c00",97:"#264c26",98:"#002600",99:"#132613",100:"#00ff3f",101:"#7fff9f",102:"#00a529",103:"#52a567",104:"#007f1f",105:"#3f7f4f",106:"#004c13",107:"#264c2f",108:"#002609",109:"#132617",110:"#00ff7f",111:"#7fffbf",112:"#00a552",113:"#52a57c",114:"#007f3f",115:"#3f7f5f",116:"#004c26",117:"#264c39",118:"#002613",119:"#13261c",120:"#00ffbf",121:"#7fffdf",122:"#00a57c",123:"#52a591",124:"#007f5f",125:"#3f7f6f",126:"#004c39",127:"#264c42",128:"#00261c",129:"#132621",130:"#00ffff",131:"#7fffff",132:"#00a5a5",133:"#52a5a5",134:"#007f7f",135:"#3f7f7f",136:"#004c4c",137:"#264c4c",138:"#002626",139:"#132626",140:"#00bfff",141:"#7fdfff",142:"#007ca5",143:"#5291a5",144:"#005f7f",145:"#3f6f7f",146:"#00394c",147:"#26424c",148:"#001c26",149:"#132126",150:"#007fff",151:"#7fbfff",152:"#0052a5",153:"#527ca5",154:"#003f7f",155:"#3f5f7f",156:"#00264c",157:"#26394c",158:"#001326",159:"#131c26",160:"#003fff",161:"#7f9fff",162:"#0029a5",163:"#5267a5",164:"#001f7f",165:"#3f4f7f",166:"#00134c",167:"#262f4c",168:"#000926",169:"#131726",170:"#0000ff",171:"#7f7fff",172:"#0000a5",173:"#5252a5",174:"#00007f",175:"#3f3f7f",176:"#00004c",177:"#26264c",178:"#000026",179:"#131326",180:"#3f00ff",181:"#9f7fff",182:"#2900a5",183:"#6752a5",184:"#1f007f",185:"#4f3f7f",186:"#13004c",187:"#2f264c",188:"#090026",189:"#171326",190:"#7f00ff",191:"#bf7fff",192:"#5200a5",193:"#7c52a5",194:"#3f007f",195:"#5f3f7f",196:"#26004c",197:"#39264c",198:"#130026",199:"#1c1326",200:"#bf00ff",201:"#df7fff",202:"#7c00a5",203:"#9152a5",204:"#5f007f",205:"#6f3f7f",206:"#39004c",207:"#42264c",208:"#1c0026",209:"#211326",210:"#ff00ff",211:"#ff7fff",212:"#a500a5",213:"#a552a5",214:"#7f007f",215:"#7f3f7f",216:"#4c004c",217:"#4c264c",218:"#260026",219:"#261326",220:"#ff00bf",221:"#ff7fdf",222:"#a5007c",223:"#a55291",224:"#7f005f",225:"#7f3f6f",226:"#4c0039",227:"#4c2642",228:"#26001c",229:"#261321",230:"#ff007f",231:"#ff7fbf",232:"#a50052",233:"#a5527c",234:"#7f003f",235:"#7f3f5f",236:"#4c0026",237:"#4c2639",238:"#260013",239:"#26131c",240:"#ff003f",241:"#ff7f9f",242:"#a50029",243:"#a55267",244:"#7f001f",245:"#7f3f4f",246:"#4c0013",247:"#4c262f",248:"#260009",249:"#261317",250:"#333333",251:"#505050",252:"#696969",253:"#828282",254:"#bebebe",255:"#ffffff"};function T(e,t="#ffffff",r=t){if(typeof e!="number"||Number.isNaN(e))return t;const i=Math.abs(Math.trunc(e));return i===0||i===256||i===257?t:i===7?r:He[i]??t}function z(e,t="rgb"){const r=Math.max(0,Math.trunc(e))&16777215,i=r>>16&255,s=r>>8&255,n=r&255;return`rgb(${t==="rgb"?i:n}, ${s}, ${t==="rgb"?n:i})`}function Y(e){if(typeof e=="string"){const t=e.trim();return t?/^(#|rgb\(|rgba\(|hsl\(|hsla\()/i.test(t)?Xe(t)??t:{red:"#ff0000",yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",blue:"#0000ff",magenta:"#ff00ff",white:"#ffffff",black:"#000000",grey:"#808080",gray:"#808080"}[t.toLowerCase()]:void 0}if(e&&typeof e=="object"){const t=e,r=Number(t.r??t.red),i=Number(t.g??t.green),s=Number(t.b??t.blue),n=Number(t.a??t.alpha??1);if([r,i,s].every(Number.isFinite))return Number.isFinite(n)&&n>=0&&n<1?`rgba(${r}, ${i}, ${s}, ${n})`:`rgb(${r}, ${i}, ${s})`}}function Xe(e){if(!e)return;const t=e.trim();if(/^#[0-9a-f]{8}$/i.test(t)){const r=parseInt(t.slice(1,3),16)/255,i=parseInt(t.slice(3,5),16),s=parseInt(t.slice(5,7),16),n=parseInt(t.slice(7,9),16);return r>=.999?`rgb(${i}, ${s}, ${n})`:`rgba(${i}, ${s}, ${n}, ${ut(r)})`}if(/^#[0-9a-f]{6}$/i.test(t)||/^#[0-9a-f]{3}$/i.test(t))return t;if(/^sc#/i.test(t)){const r=t.slice(3).split(",").map(a=>Number(a.trim())),[i,s,n,o]=r.length===4?r:[1,...r];if([i,s,n,o].every(Number.isFinite))return`rgba(${Math.round(s*255)}, ${Math.round(n*255)}, ${Math.round(o*255)}, ${ut(i)})`}}function F(e,t,r={}){const i=r.foreground??"#ffffff",s=i;let n;const o=Y(e.trueColor)??Y(e.color)??Y(e.colorName);if(o&&(n=o),!n){const a=Ge(e,["trueColor","true_color","truecolor","colorRGB","colorRgb","rgbColor","rgb"]);typeof a=="number"&&a>=0&&a<=16777215&&(n=z(a,r.trueColorByteOrder??"rgb"))}if(!n){const a=Kt(e.colorIndex,e.colorNumber,e.aci);typeof a=="number"&&Math.abs(a)<=257&&a!==256&&a!==0&&a!==257&&(n=T(a,s,i))}if(!n&&typeof e.color=="number"){const a=Number(e.color);Math.abs(a)<=257?a!==0&&a!==256&&a!==257&&(n=T(a,s,i)):n=z(a,r.trueColorByteOrder??"rgb")}if(!n){const a=je(t,e.layer);n=Ue(a,r)}return Gt(n??s,r)}function lt(e,t,r={}){let i;const s=Y(e.fillColor);if(s&&(i=s),!i&&typeof e.fillColor=="number"){const n=e.fillColor;i=Math.abs(n)<=257?T(n,r.foreground??"#ffffff",r.foreground??"#ffffff"):z(n,r.trueColorByteOrder??"rgb")}return!i&&typeof e.fillColorIndex=="number"&&(i=T(e.fillColorIndex,r.foreground??"#ffffff",r.foreground??"#ffffff")),i?Gt(i,r):void 0}function Gt(e,t={}){if(t.contrastMode!=="adaptive")return e;const r=t.background??"#0b1020",i=t.foreground??"#ffffff";return _e(e,r,i,t.minColorContrast??2.4)}function _e(e,t,r,i=2.4){const s=ht(r)??{r:255,g:255,b:255,a:1},n=ht(t)??{r:11,g:16,b:32,a:1},o=ht(e);if(!o)return e;const a=Jt(o,n);if(ft(a,n)>=i)return e;const c=dt(n),l=c<.5?{r:255,g:255,b:255,a:o.a}:{r:0,g:0,b:0,a:o.a};for(const h of[.25,.4,.55,.7,.85,1]){const d=Ze(o,l,h);if(ft(Jt(d,n),n)>=i)return Qt(d)}return ft(s,n)>=i?Qt(s):c<.5?"#ffffff":"#000000"}function Zt(e){return e?e.isVisible!==!1&&e.isFrozen!==!0:!0}function Ue(e,t){if(!e)return;const r=t.foreground??"#ffffff",i=Y(e.trueColor);if(i)return i;if(typeof e.trueColor=="number"&&e.trueColor>=0&&e.trueColor<=16777215)return z(e.trueColor,t.trueColorByteOrder??"rgb");const s=Y(e.color);if(s)return s;if($e(e.colorIndex))return T(e.colorIndex,r,r);if(typeof e.color=="number"){const n=Number(e.color);return Math.abs(n)<=257?T(n,r,r):z(n,t.trueColorByteOrder??"rgb")}if(typeof e.colorIndex=="number")return T(e.colorIndex,r,r)}function Ve(e){return Kt(e.colorIndex,e.colorNumber,e.aci)===0?!0:e.trueColor===void 0&&e.color===0}function qt(e,t,r,i={}){if(!Ve(e))return e;const s=F(t,r,i);return{...e,color:s,trueColor:void 0,colorIndex:void 0,colorNumber:void 0}}function $e(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(Math.trunc(e))>=1&&Math.abs(Math.trunc(e))<=255}function je(e,t){if(!(!e||!t))return e.layers[t]??e.layers[t.toLowerCase()]??Object.values(e.layers).find(r=>r.name.toLowerCase()===t.toLowerCase())}function Kt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Ge(e,t){const r=e;for(const i of t){const s=r[i];if(typeof s=="number"&&Number.isFinite(s))return s}}function ht(e){const t=e.trim().toLowerCase();if(/^#[0-9a-f]{3}$/i.test(t))return{r:parseInt(t[1]+t[1],16),g:parseInt(t[2]+t[2],16),b:parseInt(t[3]+t[3],16),a:1};if(/^#[0-9a-f]{6}$/i.test(t))return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16),a:1};const r=t.match(/^rgba?\(([^)]+)\)$/i);if(r){const i=r[1].split(/[,\s/]+/).filter(Boolean).map(s=>Number(s.replace("%","")));if(i.length>=3&&i.slice(0,3).every(Number.isFinite)){const s=/%/.test(r[1]);return{r:H(s?i[0]*2.55:i[0]),g:H(s?i[1]*2.55:i[1]),b:H(s?i[2]*2.55:i[2]),a:Number.isFinite(i[3])?Math.max(0,Math.min(1,i[3])):1}}}}function Jt(e,t){const r=e.a+t.a*(1-e.a);return r<=0?{r:0,g:0,b:0,a:0}:{r:(e.r*e.a+t.r*t.a*(1-e.a))/r,g:(e.g*e.a+t.g*t.a*(1-e.a))/r,b:(e.b*e.a+t.b*t.a*(1-e.a))/r,a:r}}function Ze(e,t,r){const i=Math.max(0,Math.min(1,r));return{r:e.r+(t.r-e.r)*i,g:e.g+(t.g-e.g)*i,b:e.b+(t.b-e.b)*i,a:e.a}}function dt(e){const t=[e.r,e.g,e.b].map(r=>{const i=r/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4});return .2126*t[0]+.7152*t[1]+.0722*t[2]}function ft(e,t){const r=dt(e),i=dt(t),s=Math.max(r,i),n=Math.min(r,i);return(s+.05)/(n+.05)}function Qt(e){const t=H(e.r),r=H(e.g),i=H(e.b);return e.a<.999?`rgba(${t}, ${r}, ${i}, ${ut(e.a)})`:`rgb(${t}, ${r}, ${i})`}function H(e){return Math.max(0,Math.min(255,Math.round(e)))}function ut(e){return Math.round(e*1e3)/1e3}function mt(e,t){return{a:e.a*t.a+e.c*t.b,b:e.b*t.a+e.d*t.b,c:e.a*t.c+e.c*t.d,d:e.b*t.c+e.d*t.d,e:e.a*t.e+e.c*t.f+e.e,f:e.b*t.e+e.d*t.f+e.f}}function te(e,t){return{a:1,b:0,c:0,d:1,e,f:t}}function qe(e){const t=Math.cos(e),r=Math.sin(e);return{a:t,b:r,c:-r,d:t,e:0,f:0}}function Ke(e,t=e){return{a:e,b:0,c:0,d:t,e:0,f:0}}function M(e,t){return{x:e.x*t.a+e.y*t.c+t.e,y:e.x*t.b+e.y*t.d+t.f,z:"z"in e?e.z:void 0}}function ee(e,t){if(e)return e.map(r=>({cmd:r.cmd,points:r.points.map(i=>M(i,t))}))}function it(e,t={x:0,y:0}){const r=e.insertionPoint??{x:0,y:0},i=e.scale,s=Number(typeof i=="object"&&i?i.x??1:e.scaleX??1),n=Number(typeof i=="object"&&i?i.y??s:e.scaleY??s),o=Number(e.rotation??0);let a=te(r.x,r.y);return a=mt(a,qe(Number.isFinite(o)?o:0)),a=mt(a,Ke(Number.isFinite(s)?s:1,Number.isFinite(n)?n:1)),a=mt(a,te(-t.x,-t.y)),a}function st(e,t){const r={...e,raw:e.raw??e};if(e.startPoint&&(r.startPoint=M(e.startPoint,t)),e.endPoint&&(r.endPoint=M(e.endPoint,t)),e.center&&(r.center=M(e.center,t)),e.insertionPoint&&(r.insertionPoint=M(e.insertionPoint,t)),e.majorAxisEndPoint){const s=M({x:0,y:0},t),n=M(e.majorAxisEndPoint,t);r.majorAxisEndPoint={x:n.x-s.x,y:n.y-s.y,z:n.z}}e.vertices&&(r.vertices=e.vertices.map(s=>({...M(s,t),bulge:s.bulge,startWidth:s.startWidth,endWidth:s.endWidth}))),e.points&&(r.points=e.points.map(s=>M(s,t))),e.controlPoints&&(r.controlPoints=e.controlPoints.map(s=>M(s,t))),e.fitPoints&&(r.fitPoints=e.fitPoints.map(s=>M(s,t))),e.commands&&(r.commands=ee(e.commands,t)),e.loops&&(r.loops=e.loops.map(s=>{var n;return{...s,vertices:(n=s.vertices)==null?void 0:n.map(o=>M(o,t)),commands:ee(s.commands,t)}}));const i=Math.sqrt(Math.abs(t.a*t.d-t.b*t.c));return typeof e.radius=="number"&&Number.isFinite(i)&&(r.radius=e.radius*i),r}const Je={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class pt{constructor(t,r={}){f(this,"canvas");f(this,"ctx");f(this,"opts");f(this,"document");f(this,"bounds",E());f(this,"view",{centerX:0,centerY:0,scale:1});f(this,"fitScale",1);f(this,"dpr",1);f(this,"isDragging",!1);f(this,"lastPointer");f(this,"resizeObserver");f(this,"imageCache",new Map);f(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"});f(this,"onStats");f(this,"onViewChange");const i=t.getContext("2d");if(!i)throw new Error("Canvas 2D context is not available.");this.canvas=t,this.ctx=i,this.opts={...Je,...r},this.canvas.classList.add("cad-viewer-canvas"),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t)),this.resize()}destroy(){var t;(t=this.resizeObserver)==null||t.disconnect()}clear(){this.document=void 0,this.bounds=E(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange()}setDocument(t){this.document=t,this.bounds=this.computeBounds(t),this.fitToView()}getDocument(){return this.document}setOptions(t){Object.assign(this.opts,t),this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(t=.92){if(!D(this.bounds)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const r=Math.max(1,this.cssWidth),i=Math.max(1,this.cssHeight),s=Math.max(this.bounds.maxX-this.bounds.minX,1e-9),n=Math.max(this.bounds.maxY-this.bounds.minY,1e-9),o=this.clampScale(Math.min(r/s,i/n)*t);this.fitScale=o,this.view={centerX:(this.bounds.minX+this.bounds.maxX)/2,centerY:(this.bounds.minY+this.bounds.maxY)/2,scale:o},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const t=Math.max(1,Math.floor(this.cssWidth*this.dpr)),r=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==t||this.canvas.height!==r)&&(this.canvas.width=t,this.canvas.height=r),this.render(),this.emitViewChange()}zoom(t,r){if(!Number.isFinite(t)||t<=0)return;const i=r??{x:this.cssWidth/2,y:this.cssHeight/2},s=this.screenToWorld(i);this.view.scale=this.clampScale(this.view.scale*t);const n=this.screenToWorld(i);this.view.centerX+=s.x-n.x,this.view.centerY+=s.y-n.y,this.render(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(t,r){!Number.isFinite(t)||!Number.isFinite(r)||(this.view.centerX-=t/this.view.scale,this.view.centerY+=r/this.view.scale,this.render(),this.emitViewChange())}setViewState(t){if(![t.centerX,t.centerY,t.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...t,scale:this.clampScale(t.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return Qe(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(t){return{x:this.cssWidth/2+(t.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(t.y-this.view.centerY)*this.view.scale}}screenToWorld(t){return{x:this.view.centerX+(t.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(t.y-this.cssHeight/2)/this.view.scale}}render(){var r,i;const t=performance.now();if(this.stats={total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"},this.clearCanvas(),this.document){this.opts.showPageBounds&&((r=this.document.pages)!=null&&r.length)&&this.drawPageBounds(this.document);for(const s of this.document.entities)this.drawEntityTracked(s,0)}return this.stats.renderElapsedMs=performance.now()-t,(i=this.onStats)==null||i.call(this,this.getStats()),this.getStats()}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}bindEvents(){this.canvas.addEventListener("wheel",r=>{r.preventDefault();const i=r.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(i,{x:r.offsetX,y:r.offsetY})},{passive:!1}),this.canvas.addEventListener("pointerdown",r=>{this.canvas.setPointerCapture(r.pointerId),this.isDragging=!0,this.lastPointer={x:r.clientX,y:r.clientY},this.canvas.classList.add("is-dragging")}),this.canvas.addEventListener("pointermove",r=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(r.clientX-this.lastPointer.x,r.clientY-this.lastPointer.y),this.lastPointer={x:r.clientX,y:r.clientY})});const t=r=>{r&&this.canvas.hasPointerCapture(r.pointerId)&&this.canvas.releasePointerCapture(r.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",t),this.canvas.addEventListener("pointercancel",()=>t())}clearCanvas(){const t=this.ctx;t.save(),t.setTransform(this.dpr,0,0,this.dpr,0,0),t.clearRect(0,0,this.cssWidth,this.cssHeight),t.fillStyle=this.opts.background,t.fillRect(0,0,this.cssWidth,this.cssHeight),t.restore()}drawPageBounds(t){const r=this.ctx;r.save(),r.setTransform(this.dpr,0,0,this.dpr,0,0),r.strokeStyle="rgba(148, 163, 184, 0.35)",r.lineWidth=1,r.setLineDash([8,6]);for(const i of t.pages??[]){const s=this.worldToScreen({x:0,y:0}),n=this.worldToScreen({x:i.width,y:i.height});r.strokeRect(Math.min(s.x,n.x),Math.min(s.y,n.y),Math.abs(n.x-s.x),Math.abs(n.y-s.y))}r.restore()}drawEntityTracked(t,r){this.stats.total++;const i=String(t.type??"UNKNOWN").toUpperCase();this.stats.byType[i]=(this.stats.byType[i]??0)+1;const s=this.lookupLayer(t.layer);if(t.isVisible===!1||!Zt(s)){this.stats.skipped++;return}this.drawEntity(t,i,r)}drawEntity(t,r,i){switch(t.kind??A(r)){case"line":return this.drawLine(t);case"circle":return this.drawCircle(t);case"arc":return this.drawArc(t);case"polyline":return this.drawPolyline(t);case"ellipse":return this.drawEllipse(t);case"text":return this.drawText(t);case"point":return this.drawPoint(t);case"insert":return this.drawInsert(t,i);case"solid":return this.drawSolid(t);case"hatch":return this.drawHatch(t);case"spline":return this.drawSpline(t);case"path":return this.drawPath(t);case"image":return this.drawImage(t);case"viewport":return this.markSkipped(r);default:this.stats.unsupported[r]=(this.stats.unsupported[r]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.drawUnsupportedMarker(t)}}beginStyledPath(t,r=!1){const i=this.ctx;i.save(),i.setTransform(this.dpr,0,0,this.dpr,0,0);const s=F(t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),n=lt(t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast})??s;i.strokeStyle=s,i.fillStyle=r?n:s,i.globalAlpha=O(Number(t.opacity??1),0,1),i.lineCap="round",i.lineJoin="round";const o=typeof t.lineweight=="number"&&t.lineweight>0?t.lineweight:0;i.lineWidth=Math.max(1,Math.min(12,o>0?o/30:1)),i.beginPath()}finishStroke(){this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}finishFillStroke(t=!1){t&&this.ctx.fill(),this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}drawLine(t){const r=t.startPoint,i=t.endPoint;if(!m(r)||!m(i))return this.markSkipped("LINE");const s=this.worldToScreen(r),n=this.worldToScreen(i);this.beginStyledPath(t),this.ctx.moveTo(s.x,s.y),this.ctx.lineTo(n.x,n.y),this.finishStroke()}drawCircle(t){const r=t.center,i=Number(t.radius);if(!m(r)||!Number.isFinite(i))return this.markSkipped("CIRCLE");const s=this.worldToScreen(r);this.beginStyledPath(t),this.ctx.arc(s.x,s.y,Math.abs(i)*this.view.scale,0,Math.PI*2),this.finishStroke()}drawArc(t){const r=t.center,i=Number(t.radius),s=Number(t.startAngle),n=Number(t.endAngle);if(!m(r)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(n))return this.markSkipped("ARC");this.strokeWorldPolyline(t,J(x(r),i,s,n,!0),!1)}drawPolyline(t){const r=t.vertices??t.points;if(!Array.isArray(r)||r.length<2)return this.markSkipped(String(t.type));const i=!!t.isClosed||(Number(t.flag)&1)===1,s=[],n=i?r.length:r.length-1;for(let o=0;o<n;o++){const a=r[o],c=r[(o+1)%r.length];if(!m(a)||!m(c))continue;const l=Ft(a,c,Number(a.bulge??0));s.length>0&&l.shift(),s.push(...l)}this.strokeWorldPolyline(t,s,i)}drawEllipse(t){const r=t.center,i=t.majorAxisEndPoint,s=Number(t.axisRatio??1);if(!m(r)||!m(i))return this.markSkipped("ELLIPSE");const n=Q(r,i,s,Number(t.startAngle??0),Number(t.endAngle??Math.PI*2)),o=Math.abs(Number(t.endAngle??Math.PI*2)-Number(t.startAngle??0))>=Math.PI*2-1e-6;this.strokeWorldPolyline(t,n,o)}drawPoint(t){const r=t.point??t.location??t.center??t.insertionPoint;if(!m(r))return this.markSkipped("POINT");const i=this.worldToScreen(r);this.beginStyledPath(t),this.ctx.moveTo(i.x-3,i.y),this.ctx.lineTo(i.x+3,i.y),this.ctx.moveTo(i.x,i.y-3),this.ctx.lineTo(i.x,i.y+3),this.finishStroke()}drawText(t){const r=t.insertionPoint??t.startPoint??t.center,i=Wt(String(t.text??t.value??"")),s=Number(t.textHeight??t.height??1);if(!m(r)||!i)return this.markSkipped(String(t.type));this.drawTextAt(t,r,i,s,Number(t.rotation??0))}drawInsert(t,r){const i=this.lookupBlock(t.blockName??t.name);if(i&&r<this.opts.maxInsertDepth){const a=it(t,i.basePoint??{x:0,y:0});for(const c of i.entities){const l=qt(c,t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast});this.drawEntityTracked(st(l,a),r+1)}return}const s=t.insertionPoint;if(!m(s))return this.markSkipped("INSERT");const n=this.worldToScreen(s);this.beginStyledPath(t);const o=5;if(this.ctx.rect(n.x-o,n.y-o,o*2,o*2),this.finishStroke(),Array.isArray(t.attribs))for(const a of t.attribs)this.drawText(a)}drawSolid(t){const r=t.vertices??t.points;if(!Array.isArray(r)||r.length<3)return this.markSkipped(String(t.type));this.beginStyledPath(t,!0);const i=this.worldToScreen(r[0]);this.ctx.moveTo(i.x,i.y);for(const s of r.slice(1)){if(!m(s))continue;const n=this.worldToScreen(s);this.ctx.lineTo(n.x,n.y)}this.ctx.closePath(),this.finishFillStroke(!0)}drawHatch(t){var i,s;const r=t.loops;if(!Array.isArray(r)||r.length===0)return this.markSkipped("HATCH");this.beginStyledPath(t,!0);for(const n of r)if((i=n.commands)!=null&&i.length)this.addPathCommands(n.commands);else if((s=n.vertices)!=null&&s.length){const o=this.worldToScreen(n.vertices[0]);this.ctx.moveTo(o.x,o.y);for(const a of n.vertices.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}this.ctx.closePath()}this.finishFillStroke(!!lt(t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}))}drawSpline(t){var i;const r=(i=t.fitPoints)!=null&&i.length?t.fitPoints:t.controlPoints;if(!r||r.length<2)return this.markSkipped("SPLINE");this.strokeWorldPolyline(t,r,!!t.isClosed)}drawPath(t){var r;if(!((r=t.commands)!=null&&r.length))return this.markSkipped(String(t.type));this.beginStyledPath(t,!!t.fillColor),this.addPathCommands(t.commands),this.finishFillStroke(!!t.fillColor)}addPathCommands(t){for(const r of t)if(r.cmd==="M"){const i=this.worldToScreen(r.points[0]);this.ctx.moveTo(i.x,i.y)}else if(r.cmd==="L"){const i=this.worldToScreen(r.points[0]);this.ctx.lineTo(i.x,i.y)}else if(r.cmd==="C"){const[i,s,n]=r.points.map(o=>this.worldToScreen(o));this.ctx.bezierCurveTo(i.x,i.y,s.x,s.y,n.x,n.y)}else if(r.cmd==="Q"){const[i,s]=r.points.map(n=>this.worldToScreen(n));this.ctx.quadraticCurveTo(i.x,i.y,s.x,s.y)}else r.cmd==="Z"&&this.ctx.closePath()}drawImage(t){const r=t.insertionPoint;if(!m(r))return this.markSkipped(String(t.type));const i=Number(t.width??32),s=Number(t.height??32),n=this.worldToScreen(r),o=this.worldToScreen({x:r.x+i,y:r.y-s}),a=Math.min(n.x,o.x),c=Math.min(n.y,o.y),l=Math.abs(o.x-n.x),h=Math.abs(o.y-n.y),d=t.imageDataUrl;if(d){const u=this.getImage(d);if(u.complete&&u.naturalWidth>0){this.ctx.save(),this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0),this.ctx.drawImage(u,a,c,l,h),this.ctx.restore(),this.stats.drawn++;return}u.onload=()=>this.render()}if(!this.opts.showImagePlaceholders)return this.markSkipped(String(t.type));this.beginStyledPath(t),this.ctx.rect(a,c,l,h),this.ctx.moveTo(a,c),this.ctx.lineTo(a+l,c+h),this.ctx.moveTo(a+l,c),this.ctx.lineTo(a,c+h),this.finishStroke()}getImage(t){let r=this.imageCache.get(t);return r||(r=new Image,r.src=t,this.imageCache.set(t,r)),r}drawUnsupportedMarker(t){const r=this.entityAnchor(t);if(!r)return;const i=this.worldToScreen(r);this.beginStyledPath(t),this.ctx.moveTo(i.x-4,i.y-4),this.ctx.lineTo(i.x+4,i.y+4),this.ctx.moveTo(i.x+4,i.y-4),this.ctx.lineTo(i.x-4,i.y+4),this.finishStroke()}drawTextAt(t,r,i,s,n){const o=this.ctx,a=this.worldToScreen(r);o.save(),o.setTransform(this.dpr,0,0,this.dpr,0,0),o.translate(a.x,a.y),o.rotate(-n);const c=Math.max(4,Math.min(256,Math.abs(s)*this.view.scale));o.font=`${c}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,o.fillStyle=F(t,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),o.globalAlpha=O(Number(t.opacity??1),0,1),o.textBaseline="alphabetic";for(const[l,h]of i.split(/\r?\n/g).entries())o.fillText(h,0,l*c*1.22);o.restore(),this.stats.drawn++}strokeWorldPolyline(t,r,i){const s=r.filter(m);if(s.length<2)return this.markSkipped(String(t.type));this.beginStyledPath(t);const n=this.worldToScreen(s[0]);this.ctx.moveTo(n.x,n.y);for(const o of s.slice(1)){const a=this.worldToScreen(o);this.ctx.lineTo(a.x,a.y)}i&&this.ctx.closePath(),this.finishStroke()}markSkipped(t){this.stats.skipped++,this.stats.unsupported[t]=this.stats.unsupported[t]??0}entityAnchor(t){for(const r of["startPoint","insertionPoint","center","point","location"]){const i=t[r];if(m(i))return x(i)}if(Array.isArray(t.vertices)&&m(t.vertices[0]))return x(t.vertices[0]);if(Array.isArray(t.commands)&&t.commands.length){const r=t.commands.find(i=>i.points.length>0);if(r)return x(r.points[0])}}computeBounds(t){var i;const r=E();if((i=t.pages)!=null&&i.length)for(const s of t.pages)y(r,{x:0,y:0}),y(r,{x:s.width,y:s.height});for(const s of t.entities)this.includeEntityBounds(r,s,0);return Bt(r)}includeEntityBounds(t,r,i){const s=String(r.type??"").toUpperCase(),n=r.kind??A(s);if(n==="insert"){const o=this.lookupBlock(r.blockName??r.name);if(o&&i<this.opts.maxInsertDepth){const a=it(r,o.basePoint??{x:0,y:0});for(const c of o.entities)this.includeEntityBounds(t,st(c,a),i+1);return}}if(n==="line")m(r.startPoint)&&y(t,r.startPoint),m(r.endPoint)&&y(t,r.endPoint);else if(n==="circle"||n==="arc")m(r.center)&&Number.isFinite(r.radius)&&At(t,r.center,Number(r.radius));else if(n==="polyline"||n==="solid"||n==="spline")for(const o of[...r.vertices??[],...r.points??[],...r.controlPoints??[],...r.fitPoints??[]])m(o)&&y(t,o);else if(n==="ellipse")m(r.center)&&m(r.majorAxisEndPoint)&&Q(r.center,r.majorAxisEndPoint,Number(r.axisRatio??1),Number(r.startAngle??0),Number(r.endAngle??Math.PI*2)).forEach(o=>y(t,o));else if(n==="path")for(const o of r.commands??[])for(const a of o.points)y(t,a);else if(n==="hatch")for(const o of r.loops??[]){for(const a of o.vertices??[])y(t,a);for(const a of o.commands??[])for(const c of a.points)y(t,c)}else{const o=this.entityAnchor(r);o&&y(t,o)}}lookupLayer(t){if(!(!this.document||!t))return this.document.layers[t]??this.document.layers[t.toLowerCase()]??Object.values(this.document.layers).find(r=>r.name.toLowerCase()===t.toLowerCase())}lookupBlock(t){if(!(!this.document||!t))return this.document.blocks[t]??this.document.blocks[t.toLowerCase()]??Object.values(this.document.blocks).find(r=>r.name.toLowerCase()===t.toLowerCase())}clampScale(t){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,t))}emitViewChange(){var t;(t=this.onViewChange)==null||t.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function Qe(e){return{total:e.total,drawn:e.drawn,skipped:e.skipped,byType:{...e.byType},unsupported:{...e.unsupported},renderElapsedMs:e.renderElapsedMs,backend:e.backend,primitiveCount:e.primitiveCount,visiblePrimitiveCount:e.visiblePrimitiveCount,culledPrimitiveCount:e.culledPrimitiveCount,gpuMemoryBytes:e.gpuMemoryBytes,buildElapsedMs:e.buildElapsedMs}}const tr={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class gt{constructor(t,r={}){f(this,"canvas");f(this,"backend","webgl");f(this,"gl");f(this,"program");f(this,"eventController",new AbortController);f(this,"imageCache",new Map);f(this,"opts");f(this,"document");f(this,"bounds",E());f(this,"view",{centerX:0,centerY:0,scale:1});f(this,"fitScale",1);f(this,"dpr",1);f(this,"isDragging",!1);f(this,"lastPointer");f(this,"resizeObserver");f(this,"overlayCanvas");f(this,"overlayCtx");f(this,"scene");f(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});f(this,"rafHandle",0);f(this,"onStats");f(this,"onViewChange");const i=er(t,r);if(!i)throw new Error('WebGL is not available. Use renderer: "canvas2d" to force the Canvas2D fallback.');this.canvas=t,this.gl=i,this.program=rr(i),this.opts={...tr,...r},this.canvas.classList.add("cad-viewer-canvas","cad-viewer-webgl-canvas"),this.createOverlayCanvas(),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t)),this.resize()}static isSupported(){return bt()}destroy(){var t,r;this.eventController.abort(),(t=this.resizeObserver)==null||t.disconnect(),this.cancelScheduledRender(),this.disposeScene(),(r=this.overlayCanvas)==null||r.remove()}clear(){this.document=void 0,this.bounds=E(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.disposeScene(),this.render(),this.emitViewChange()}setDocument(t){this.document=t,this.bounds=cr(t,this.opts),this.disposeScene();const r=sr(t,this.opts,this.bounds);this.scene=ir(this.gl,r),this.stats=dr(this.scene,0),this.fitToView()}getDocument(){return this.document}setOptions(t){const r=hr(this.opts,t);if(this.opts={...this.opts,...t},r&&this.document){this.setDocument(this.document);return}this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(t=.92){if(!D(this.bounds)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const r=Math.max(1,this.cssWidth),i=Math.max(1,this.cssHeight),s=Math.max(this.bounds.maxX-this.bounds.minX,1e-9),n=Math.max(this.bounds.maxY-this.bounds.minY,1e-9),o=this.clampScale(Math.min(r/s,i/n)*t);this.fitScale=o,this.view={centerX:(this.bounds.minX+this.bounds.maxX)/2,centerY:(this.bounds.minY+this.bounds.maxY)/2,scale:o},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const t=Math.max(1,Math.floor(this.cssWidth*this.dpr)),r=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==t||this.canvas.height!==r)&&(this.canvas.width=t,this.canvas.height=r),this.resizeOverlay(t,r),this.render(),this.emitViewChange()}zoom(t,r){if(!Number.isFinite(t)||t<=0)return;const i=r??{x:this.cssWidth/2,y:this.cssHeight/2},s=this.screenToWorld(i);this.view.scale=this.clampScale(this.view.scale*t);const n=this.screenToWorld(i);this.view.centerX+=s.x-n.x,this.view.centerY+=s.y-n.y,this.scheduleRender(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(t,r){!Number.isFinite(t)||!Number.isFinite(r)||(this.view.centerX-=t/this.view.scale,this.view.centerY+=r/this.view.scale,this.scheduleRender(),this.emitViewChange())}setViewState(t){if(![t.centerX,t.centerY,t.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...t,scale:this.clampScale(t.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return fr(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(t){return{x:this.cssWidth/2+(t.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(t.y-this.view.centerY)*this.view.scale}}screenToWorld(t){return{x:this.view.centerX+(t.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(t.y-this.cssHeight/2)/this.view.scale}}render(){return this.cancelScheduledRender(),this.renderNow()}renderNow(){var l;const t=performance.now(),r=this.gl;r.viewport(0,0,this.canvas.width,this.canvas.height);const i=xt(this.opts.background,[11,16,32,255]);r.clearColor(i[0]/255,i[1]/255,i[2]/255,i[3]/255),r.clear(r.COLOR_BUFFER_BIT),r.disable(r.DEPTH_TEST),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA);let s=0,n=0;const o=this.scene,a=this.visibleWorldBounds();if(o){r.useProgram(this.program.program),r.uniform2f(this.program.uViewCenter,this.view.centerX-o.origin.x,this.view.centerY-o.origin.y),r.uniform1f(this.program.uScale,this.view.scale*this.dpr),r.uniform2f(this.program.uViewport,this.canvas.width,this.canvas.height),r.uniform1f(this.program.uPointSize,Math.max(2,Math.min(12,4*this.dpr)));const h=this.drawBatches(o.lineBatches,r.LINES,a);s+=h.visible,n+=h.culled;const d=this.drawBatches(o.triangleBatches,r.TRIANGLES,a);s+=d.visible,n+=d.culled;const u=this.drawBatches(o.pointBatches,r.POINTS,a);s+=u.visible,n+=u.culled}this.renderOverlay(a);const c=performance.now()-t;return this.stats=o?{...o.stats,renderElapsedMs:c,backend:"webgl",primitiveCount:o.primitiveCount,visiblePrimitiveCount:s,culledPrimitiveCount:n,gpuMemoryBytes:o.gpuMemoryBytes,buildElapsedMs:o.buildElapsedMs}:{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:c,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0},(l=this.onStats)==null||l.call(this,this.getStats()),this.getStats()}drawBatches(t,r,i){const s=this.gl;let n=0,o=0;for(const a of t){if(!wt(a.bounds,i)){o+=a.primitiveCount;continue}s.bindBuffer(s.ARRAY_BUFFER,a.positionBuffer),s.enableVertexAttribArray(this.program.aPosition),s.vertexAttribPointer(this.program.aPosition,2,s.FLOAT,!1,0,0),s.bindBuffer(s.ARRAY_BUFFER,a.colorBuffer),s.enableVertexAttribArray(this.program.aColor),s.vertexAttribPointer(this.program.aColor,4,s.UNSIGNED_BYTE,!0,0,0),s.drawArrays(r,0,a.vertexCount),n+=a.primitiveCount}return{visible:n,culled:o}}scheduleRender(){this.rafHandle||(this.rafHandle=window.requestAnimationFrame(()=>{this.rafHandle=0,this.renderNow()}))}cancelScheduledRender(){this.rafHandle&&(window.cancelAnimationFrame(this.rafHandle),this.rafHandle=0)}renderOverlay(t){var s,n;const r=this.overlayCtx,i=this.overlayCanvas;!r||!i||(r.save(),r.setTransform(this.dpr,0,0,this.dpr,0,0),r.clearRect(0,0,this.cssWidth,this.cssHeight),this.opts.showPageBounds&&((n=(s=this.document)==null?void 0:s.pages)!=null&&n.length)&&this.drawPageBoundsOverlay(r),this.scene&&(this.drawImagesOverlay(r,this.scene.imageItems,t),this.drawTextOverlay(r,this.scene.textItems,t)),r.restore())}drawPageBoundsOverlay(t){var r,i;if((i=(r=this.document)==null?void 0:r.pages)!=null&&i.length){t.save(),t.strokeStyle="rgba(148, 163, 184, 0.34)",t.lineWidth=1,t.setLineDash([8,6]);for(const s of this.document.pages){const n=this.worldToScreen({x:0,y:0}),o=this.worldToScreen({x:s.width,y:s.height});t.strokeRect(Math.min(n.x,o.x),Math.min(n.y,o.y),Math.abs(o.x-n.x),Math.abs(o.y-n.y))}t.restore()}}drawTextOverlay(t,r,i){const s=this.opts.maxVisibleTextLabels;let n=0;for(const o of r){if(n>=s)break;if(!wt(o.bounds,i))continue;const a=Math.abs(o.height)*this.view.scale;if(a<this.opts.textMinPixelHeight)continue;const c=this.worldToScreen(o.point);if(c.x<-512||c.y<-512||c.x>this.cssWidth+512||c.y>this.cssHeight+512)continue;t.save(),t.translate(c.x,c.y),t.rotate(-o.rotation);const l=Math.max(4,Math.min(256,a));t.font=`${l}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,t.fillStyle=o.color,t.globalAlpha=o.opacity,t.textBaseline="alphabetic";for(const[h,d]of o.text.split(/\r?\n/g).entries())t.fillText(d,0,h*l*1.22);t.restore(),n++}}drawImagesOverlay(t,r,i){for(const s of r){if(!wt(s.bounds,i))continue;const n=this.worldToScreen(s.point),o=this.worldToScreen({x:s.point.x+s.width,y:s.point.y-s.height}),a=Math.min(n.x,o.x),c=Math.min(n.y,o.y),l=Math.abs(o.x-n.x),h=Math.abs(o.y-n.y);if(!(l<1||h<1)){if(s.source){const d=this.getImage(s.source);if(d.complete&&d.naturalWidth>0){t.save(),t.globalAlpha=s.opacity,t.drawImage(d,a,c,l,h),t.restore();continue}d.onload=()=>this.scheduleRender()}this.opts.showImagePlaceholders&&(t.save(),t.strokeStyle=s.color,t.globalAlpha=s.opacity,t.lineWidth=1,t.strokeRect(a,c,l,h),t.beginPath(),t.moveTo(a,c),t.lineTo(a+l,c+h),t.moveTo(a+l,c),t.lineTo(a,c+h),t.stroke(),t.restore())}}}getImage(t){let r=this.imageCache.get(t);return r||(r=new Image,r.src=t,this.imageCache.set(t,r)),r}createOverlayCanvas(){const t=this.canvas.parentElement;if(!t||typeof document>"u")return;window.getComputedStyle(t).position==="static"&&(t.style.position="relative");const i=document.createElement("canvas");i.className="cad-viewer-text-overlay",i.setAttribute("aria-hidden","true"),i.style.position="absolute",i.style.inset="0",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.zIndex="1";const s=i.getContext("2d");s&&(t.appendChild(i),this.overlayCanvas=i,this.overlayCtx=s)}resizeOverlay(t,r){this.overlayCanvas&&(this.overlayCanvas.width!==t||this.overlayCanvas.height!==r)&&(this.overlayCanvas.width=t,this.overlayCanvas.height=r)}bindEvents(){const t=this.eventController.signal;this.canvas.addEventListener("wheel",i=>{i.preventDefault();const s=i.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(s,{x:i.offsetX,y:i.offsetY})},{passive:!1,signal:t}),this.canvas.addEventListener("pointerdown",i=>{this.canvas.setPointerCapture(i.pointerId),this.isDragging=!0,this.lastPointer={x:i.clientX,y:i.clientY},this.canvas.classList.add("is-dragging")},{signal:t}),this.canvas.addEventListener("pointermove",i=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(i.clientX-this.lastPointer.x,i.clientY-this.lastPointer.y),this.lastPointer={x:i.clientX,y:i.clientY})},{signal:t});const r=i=>{i&&this.canvas.hasPointerCapture(i.pointerId)&&this.canvas.releasePointerCapture(i.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",r,{signal:t}),this.canvas.addEventListener("pointercancel",()=>r(),{signal:t}),this.canvas.addEventListener("webglcontextlost",i=>{i.preventDefault(),this.cancelScheduledRender()},{signal:t})}visibleWorldBounds(){const t=this.cssWidth/Math.max(this.view.scale,1e-12)/2,r=this.cssHeight/Math.max(this.view.scale,1e-12)/2;return{minX:this.view.centerX-t,maxX:this.view.centerX+t,minY:this.view.centerY-r,maxY:this.view.centerY+r}}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}clampScale(t){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,t))}disposeScene(){if(!this.scene)return;const t=this.gl;for(const r of[...this.scene.lineBatches,...this.scene.triangleBatches,...this.scene.pointBatches])t.deleteBuffer(r.positionBuffer),t.deleteBuffer(r.colorBuffer);this.scene=void 0}emitViewChange(){var t;(t=this.onViewChange)==null||t.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function bt(){if(typeof document>"u")return!1;const e=document.createElement("canvas");return!!(e.getContext("webgl2")??e.getContext("webgl")??e.getContext("experimental-webgl"))}function er(e,t){const r={alpha:!1,antialias:t.antialias??!0,depth:!1,stencil:!1,preserveDrawingBuffer:t.preserveDrawingBuffer??!1,powerPreference:t.powerPreference??"high-performance"};return e.getContext("webgl2",r)??e.getContext("webgl",r)??e.getContext("experimental-webgl",r)??void 0}function rr(e){const t=`
|
|
6
6
|
attribute vec2 a_position;
|
|
7
7
|
attribute vec4 a_color;
|
|
8
8
|
uniform vec2 u_viewCenter;
|
|
@@ -26,5 +26,5 @@
|
|
|
26
26
|
void main() {
|
|
27
27
|
gl_FragColor = v_color;
|
|
28
28
|
}
|
|
29
|
-
`,i=te(e,e.VERTEX_SHADER,t),s=te(e,e.FRAGMENT_SHADER,r),n=e.createProgram();if(!n)throw new Error("Failed to create WebGL program.");if(e.attachShader(n,i),e.attachShader(n,s),e.linkProgram(n),!e.getProgramParameter(n,e.LINK_STATUS)){const h=e.getProgramInfoLog(n)??"Unknown WebGL program link error.";throw e.deleteProgram(n),new Error(h)}e.deleteShader(i),e.deleteShader(s);const o=e.getUniformLocation(n,"u_viewCenter"),a=e.getUniformLocation(n,"u_scale"),c=e.getUniformLocation(n,"u_viewport"),l=e.getUniformLocation(n,"u_pointSize");if(!o||!a||!c||!l)throw new Error("Failed to resolve WebGL shader uniforms.");return{program:n,aPosition:e.getAttribLocation(n,"a_position"),aColor:e.getAttribLocation(n,"a_color"),uViewCenter:o,uScale:a,uViewport:c,uPointSize:l}}function te(e,t,r){const i=e.createShader(t);if(!i)throw new Error("Failed to create WebGL shader.");if(e.shaderSource(i,r),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){const s=e.getShaderInfoLog(i)??"Unknown WebGL shader compile error.";throw e.deleteShader(i),new Error(s)}return i}function Je(e,t){let r=0;const i=a=>a.map(c=>{const l=ee(e,c.positions),h=ee(e,c.colors),f=c.positions.byteLength+c.colors.byteLength;return r+=f,{positionBuffer:l,colorBuffer:h,vertexCount:c.positions.length/2,primitiveCount:c.primitiveCount,bounds:c.bounds,gpuBytes:f}}),s=i(t.lineBatches),n=i(t.triangleBatches),o=i(t.pointBatches);return{origin:t.origin,lineBatches:s,triangleBatches:n,pointBatches:o,textItems:t.textItems,imageItems:t.imageItems,stats:t.stats,primitiveCount:t.primitiveCount,gpuMemoryBytes:r,buildElapsedMs:t.buildElapsedMs}}function ee(e,t){const r=e.createBuffer();if(!r)throw new Error("Failed to create WebGL buffer.");return e.bindBuffer(e.ARRAY_BUFFER,r),e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW),r}function Qe(e,t,r){const i=performance.now(),s=D(r)?{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}:{x:0,y:0},n=new tr(e,t,r,s);for(const a of e.entities)n.addEntityTracked(a,0);const o=n.finalize();return o.buildElapsedMs=performance.now()-i,o}class tr{constructor(t,r,i,s){d(this,"lineBuckets",new Map);d(this,"triangleBuckets",new Map);d(this,"pointBuckets",new Map);d(this,"textItems",[]);d(this,"imageItems",[]);d(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});d(this,"tileSize");d(this,"maxVerticesPerBatch");d(this,"primitiveCount",0);this.document=t,this.opts=r,this.bounds=i,this.origin=s;const n=D(i)?Math.max(i.maxX-i.minX,i.maxY-i.minY,1e-9):1;this.tileSize=r.enableSpatialIndex?n/Math.max(8,r.spatialIndexCellCount):Number.POSITIVE_INFINITY,this.maxVerticesPerBatch=Math.max(4096,Math.floor(r.maxVerticesPerBatch))}addEntityTracked(t,r){this.stats.total++;const i=String(t.type??"UNKNOWN").toUpperCase();this.stats.byType[i]=(this.stats.byType[i]??0)+1;const s=this.lookupLayer(t.layer);if(t.isVisible===!1||!jt(s)){this.stats.skipped++;return}this.addEntity(t,i,r)}finalize(){const t=bt(this.lineBuckets,this.maxVerticesPerBatch),r=bt(this.triangleBuckets,this.maxVerticesPerBatch),i=bt(this.pointBuckets,this.maxVerticesPerBatch);return this.stats.primitiveCount=this.primitiveCount,{origin:this.origin,lineBatches:t,triangleBatches:r,pointBatches:i,textItems:this.textItems,imageItems:this.imageItems,stats:this.stats,primitiveCount:this.primitiveCount,buildElapsedMs:0}}addEntity(t,r,i){switch(t.kind??A(r)){case"line":return this.addLineEntity(t);case"circle":return this.addCircleEntity(t);case"arc":return this.addArcEntity(t);case"polyline":return this.addPolylineEntity(t);case"ellipse":return this.addEllipseEntity(t);case"text":return this.addTextEntity(t);case"point":return this.addPointEntity(t);case"insert":return this.addInsertEntity(t,i);case"solid":return this.addSolidEntity(t);case"hatch":return this.addHatchEntity(t);case"spline":return this.addSplineEntity(t);case"path":return this.addPathEntity(t);case"image":return this.addImageEntity(t);case"viewport":return this.markSkipped(r);default:this.stats.unsupported[r]=(this.stats.unsupported[r]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.addUnsupportedMarker(t)}}addLineEntity(t){if(!m(t.startPoint)||!m(t.endPoint))return this.markSkipped("LINE");this.addSegment(t.startPoint,t.endPoint,this.strokeBytes(t)),this.stats.drawn++}addCircleEntity(t){const r=t.center,i=Number(t.radius);if(!m(r)||!Number.isFinite(i))return this.markSkipped("CIRCLE");const s=Math.max(16,Math.min(this.opts.maxCurveSegments,Math.ceil(Math.sqrt(Math.abs(i))*12))),n=J(r,i,0,Math.PI*2,!0,s);this.addPolyline(n,!0,this.strokeBytes(t)),this.stats.drawn++}addArcEntity(t){const r=t.center,i=Number(t.radius),s=Number(t.startAngle),n=Number(t.endAngle);if(!m(r)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(n))return this.markSkipped("ARC");this.addPolyline(J(r,i,s,n,!0,this.opts.maxCurveSegments),!1,this.strokeBytes(t)),this.stats.drawn++}addPolylineEntity(t){const r=t.vertices??t.points;if(!Array.isArray(r)||r.length<2)return this.markSkipped(String(t.type));const i=!!t.isClosed||(Number(t.flag)&1)===1,s=[],n=i?r.length:r.length-1;for(let o=0;o<n;o++){const a=r[o],c=r[(o+1)%r.length];if(!m(a)||!m(c))continue;const l=Bt(a,c,Number(a.bulge??0),Math.max(4,Math.min(24,this.opts.maxCurveSegments/4)));s.length>0&&l.shift(),s.push(...l)}if(s.length<2)return this.markSkipped(String(t.type));this.addPolyline(s,i,this.strokeBytes(t)),this.stats.drawn++}addEllipseEntity(t){if(!m(t.center)||!m(t.majorAxisEndPoint))return this.markSkipped("ELLIPSE");const r=Q(t.center,t.majorAxisEndPoint,Number(t.axisRatio??1),Number(t.startAngle??0),Number(t.endAngle??Math.PI*2),this.opts.maxCurveSegments),i=Math.abs(Number(t.endAngle??Math.PI*2)-Number(t.startAngle??0))>=Math.PI*2-1e-6;this.addPolyline(r,i,this.strokeBytes(t)),this.stats.drawn++}addTextEntity(t){const r=t.insertionPoint??t.startPoint??t.center,i=Ft(String(t.text??t.value??"")),s=Number(t.textHeight??t.height??1);if(!m(r)||!i||!Number.isFinite(s))return this.markSkipped(String(t.type));const n=x(r),o=Math.max(1,i.split(/\r?\n/g).reduce((c,l)=>Math.max(c,l.length),0))*Math.abs(s)*.62,a=Math.max(1,i.split(/\r?\n/g).length)*Math.abs(s)*1.22;this.textItems.push({point:n,text:i,height:s,rotation:Number(t.rotation??0),color:F(t,this.document,this.colorOptions()),opacity:O(Number(t.opacity??1),0,1),bounds:{minX:n.x-o*.1,minY:n.y-a,maxX:n.x+o,maxY:n.y+a}}),this.stats.drawn++}addPointEntity(t){const r=t.point??t.location??t.center??t.insertionPoint;if(!m(r))return this.markSkipped("POINT");this.addPoint(r,this.strokeBytes(t)),this.stats.drawn++}addInsertEntity(t,r){const i=this.lookupBlock(t.blockName??t.name);if(i&&r<this.opts.maxInsertDepth){const n=rt(t,i.basePoint??{x:0,y:0});for(const o of i.entities){const a=Gt(o,t,this.document,this.colorOptions());this.addEntityTracked(it(a,n),r+1)}return}const s=t.insertionPoint;if(!m(s))return this.markSkipped("INSERT");if(this.addPoint(s,this.strokeBytes(t)),Array.isArray(t.attribs))for(const n of t.attribs)this.addTextEntity(n);this.stats.drawn++}addSolidEntity(t){const r=t.vertices??t.points;if(!Array.isArray(r)||r.length<3)return this.markSkipped(String(t.type));const i=r.filter(m).map(x);if(i.length<3)return this.markSkipped(String(t.type));const s=this.fillBytes(t)??this.strokeBytes(t);this.addTriangleFan(i,s),this.addPolyline(i,!0,this.strokeBytes(t)),this.stats.drawn++}addHatchEntity(t){var o;const r=t.loops;if(!Array.isArray(r)||r.length===0)return this.markSkipped("HATCH");const i=this.strokeBytes(t),s=this.fillBytes(t);let n=!1;for(const a of r){const c=(o=a.commands)!=null&&o.length?re(a.commands,this.opts.maxCurveSegments):(a.vertices??[]).filter(m).map(x);c.length<2||(this.addPolyline(c,!0,i),s&&c.length>=3&&this.addTriangleFan(c,s),n=!0)}if(!n)return this.markSkipped("HATCH");this.stats.drawn++}addSplineEntity(t){var i;const r=(i=t.fitPoints)!=null&&i.length?t.fitPoints:t.controlPoints;if(!r||r.length<2)return this.markSkipped("SPLINE");this.addPolyline(r.filter(m).map(x),!!t.isClosed,this.strokeBytes(t)),this.stats.drawn++}addPathEntity(t){var s;if(!((s=t.commands)!=null&&s.length))return this.markSkipped(String(t.type));const r=re(t.commands,this.opts.maxCurveSegments);if(r.length<2)return this.markSkipped(String(t.type));this.addPolyline(r,!1,this.strokeBytes(t));const i=this.fillBytes(t);i&&r.length>=3&&this.addTriangleFan(r,i),this.stats.drawn++}addImageEntity(t){const r=t.insertionPoint;if(!m(r))return this.markSkipped(String(t.type));const i=Number(t.width??32),s=Number(t.height??32);if(!Number.isFinite(i)||!Number.isFinite(s))return this.markSkipped(String(t.type));const n=x(r),o=vt([n,{x:n.x+i,y:n.y-s}]);this.imageItems.push({point:n,width:i,height:s,source:t.imageDataUrl??t.imageSource,color:F(t,this.document,this.colorOptions()),opacity:O(Number(t.opacity??1),0,1),bounds:o}),this.stats.drawn++}addUnsupportedMarker(t){const r=ie(t);r&&this.addPoint(r,this.strokeBytes(t))}addPolyline(t,r,i){const s=t.filter(m).map(x);if(!(s.length<2)){for(let n=0;n<s.length-1;n++)this.addSegment(s[n],s[n+1],i);r&&this.addSegment(s[s.length-1],s[0],i)}}addSegment(t,r,i){if(!m(t)||!m(r)||Math.hypot(t.x-r.x,t.y-r.y)<=1e-14)return;const s=this.batchFor(this.lineBuckets,vt([t,r]));X(s,t,i,this.origin),X(s,r,i,this.origin),s.primitiveCount++,this.primitiveCount++}addPoint(t,r){const i=this.batchFor(this.pointBuckets,sr(t));X(i,t,r,this.origin),i.primitiveCount++,this.primitiveCount++}addTriangleFan(t,r){const i=t.filter(m).map(x);if(i.length<3)return;const s=vt(i),n=this.batchFor(this.triangleBuckets,s);for(let o=1;o<i.length-1;o++)X(n,i[0],r,this.origin),X(n,i[o],r,this.origin),X(n,i[o+1],r,this.origin),n.primitiveCount++,this.primitiveCount++}batchFor(t,r){const i=this.bucketKey(r);let s=t.get(i);return s||(s=er(),t.set(i,s)),v(s.bounds,{x:r.minX,y:r.minY}),v(s.bounds,{x:r.maxX,y:r.maxY}),s}bucketKey(t){if(!Number.isFinite(this.tileSize))return"all";const r=(t.minX+t.maxX)/2,i=(t.minY+t.maxY)/2,s=Math.floor((r-this.bounds.minX)/this.tileSize),n=Math.floor((i-this.bounds.minY)/this.tileSize);return`${s}:${n}`}strokeBytes(t){return wt(F(t,this.document,this.colorOptions()),[255,255,255,255],O(Number(t.opacity??1),0,1))}fillBytes(t){const r=ct(t,this.document,this.colorOptions());return r?wt(r,[255,255,255,255],O(Number(t.opacity??1),0,1)):void 0}colorOptions(){return{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}}markSkipped(t){this.stats.skipped++,this.stats.unsupported[t]=this.stats.unsupported[t]??0}lookupLayer(t){if(t)return this.document.layers[t]??this.document.layers[t.toLowerCase()]??Object.values(this.document.layers).find(r=>r.name.toLowerCase()===t.toLowerCase())}lookupBlock(t){if(t)return this.document.blocks[t]??this.document.blocks[t.toLowerCase()]??Object.values(this.document.blocks).find(r=>r.name.toLowerCase()===t.toLowerCase())}}function er(){return{positions:[],colors:[],bounds:E(),primitiveCount:0}}function X(e,t,r,i){e.positions.push(t.x-i.x,t.y-i.y),e.colors.push(r[0],r[1],r[2],r[3])}function bt(e,t){const r=[];for(const i of e.values()){const s=i.positions.length/2;if(s<=0||!D(i.bounds))continue;if(s<=t){r.push({positions:new Float32Array(i.positions),colors:new Uint8Array(i.colors),bounds:{...i.bounds},primitiveCount:i.primitiveCount});continue}const n=rr(i),o=Math.max(n,Math.floor(t/n)*n);for(let a=0;a<s;a+=o){const c=Math.min(s,a+o),l=i.positions.slice(a*2,c*2),h=i.colors.slice(a*4,c*4),f=E();for(let u=0;u<l.length;u+=2)v(f,{x:l[u],y:l[u+1]});r.push({positions:new Float32Array(l),colors:new Uint8Array(h),bounds:{...i.bounds},primitiveCount:Math.floor((c-a)/n)})}}return r}function rr(e){const t=e.positions.length/2;return t===e.primitiveCount?1:t===e.primitiveCount*3?3:2}function ir(e,t){var n;const r=E();if((n=e.pages)!=null&&n.length)for(const o of e.pages)v(r,{x:0,y:0}),v(r,{x:o.width,y:o.height});const i=o=>{if(o)return e.blocks[o]??e.blocks[o.toLowerCase()]??Object.values(e.blocks).find(a=>a.name.toLowerCase()===o.toLowerCase())},s=(o,a)=>{const c=String(o.type??"").toUpperCase(),l=o.kind??A(c);if(l==="insert"){const h=i(o.blockName??o.name);if(h&&a<t.maxInsertDepth){const f=rt(o,h.basePoint??{x:0,y:0});for(const u of h.entities)s(it(u,f),a+1);return}}if(l==="line")m(o.startPoint)&&v(r,o.startPoint),m(o.endPoint)&&v(r,o.endPoint);else if(l==="circle"||l==="arc")m(o.center)&&Number.isFinite(o.radius)&&Lt(r,o.center,Number(o.radius));else if(l==="polyline"||l==="solid"||l==="spline")for(const h of[...o.vertices??[],...o.points??[],...o.controlPoints??[],...o.fitPoints??[]])m(h)&&v(r,h);else if(l==="ellipse")m(o.center)&&m(o.majorAxisEndPoint)&&Q(o.center,o.majorAxisEndPoint,Number(o.axisRatio??1),Number(o.startAngle??0),Number(o.endAngle??Math.PI*2),t.maxCurveSegments).forEach(h=>v(r,h));else if(l==="path")for(const h of o.commands??[])for(const f of h.points)v(r,f);else if(l==="hatch")for(const h of o.loops??[]){for(const f of h.vertices??[])v(r,f);for(const f of h.commands??[])for(const u of f.points)v(r,u)}else{const h=ie(o);h&&v(r,h)}};for(const o of e.entities)s(o,0);return At(r)}function re(e,t){const r=[];let i,s;const n=o=>{(!r.length||Math.hypot(r[r.length-1].x-o.x,r[r.length-1].y-o.y)>1e-12)&&r.push(x(o)),i=x(o)};for(const o of e)if(o.cmd==="M")i=x(o.points[0]),s=i,n(i);else if(o.cmd==="L")n(o.points[0]);else if(o.cmd==="Q"&&i&&o.points.length>=2){const a=i,[c,l]=o.points,h=Math.max(4,Math.min(t,24));for(let f=1;f<=h;f++){const u=f/h,p=1-u;n({x:p*p*a.x+2*p*u*c.x+u*u*l.x,y:p*p*a.y+2*p*u*c.y+u*u*l.y})}}else if(o.cmd==="C"&&i&&o.points.length>=3){const a=i,[c,l,h]=o.points,f=Math.max(6,Math.min(t,32));for(let u=1;u<=f;u++){const p=u/f,w=1-p;n({x:w**3*a.x+3*w*w*p*c.x+3*w*p*p*l.x+p**3*h.x,y:w**3*a.y+3*w*w*p*c.y+3*w*p*p*l.y+p**3*h.y})}}else o.cmd==="Z"&&s&&n(s);return r}function ie(e){for(const t of["startPoint","insertionPoint","center","point","location"]){const r=e[t];if(m(r))return x(r)}if(Array.isArray(e.vertices)&&m(e.vertices[0]))return x(e.vertices[0]);if(Array.isArray(e.commands)&&e.commands.length){const t=e.commands.find(r=>r.points.length>0);if(t)return x(t.points[0])}}function vt(e){const t=E();for(const r of e)v(t,r);return t}function sr(e){return{minX:e.x,minY:e.y,maxX:e.x,maxY:e.y}}function yt(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function nr(e,t){return t.trueColorByteOrder!==void 0&&t.trueColorByteOrder!==e.trueColorByteOrder||t.contrastMode!==void 0&&t.contrastMode!==e.contrastMode||t.minColorContrast!==void 0&&t.minColorContrast!==e.minColorContrast||t.foreground!==void 0&&t.foreground!==e.foreground||t.background!==void 0&&t.background!==e.background||t.maxInsertDepth!==void 0&&t.maxInsertDepth!==e.maxInsertDepth||t.maxCurveSegments!==void 0&&t.maxCurveSegments!==e.maxCurveSegments||t.spatialIndexCellCount!==void 0&&t.spatialIndexCellCount!==e.spatialIndexCellCount||t.maxVerticesPerBatch!==void 0&&t.maxVerticesPerBatch!==e.maxVerticesPerBatch||t.enableSpatialIndex!==void 0&&t.enableSpatialIndex!==e.enableSpatialIndex}function or(e,t){return{...e.stats,renderElapsedMs:t,backend:"webgl",primitiveCount:e.primitiveCount,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:e.gpuMemoryBytes,buildElapsedMs:e.buildElapsedMs}}function ar(e){return{total:e.total,drawn:e.drawn,skipped:e.skipped,byType:{...e.byType},unsupported:{...e.unsupported},renderElapsedMs:e.renderElapsedMs,backend:e.backend,primitiveCount:e.primitiveCount,visiblePrimitiveCount:e.visiblePrimitiveCount,culledPrimitiveCount:e.culledPrimitiveCount,gpuMemoryBytes:e.gpuMemoryBytes,buildElapsedMs:e.buildElapsedMs}}function wt(e,t,r=1){const i=e.trim().toLowerCase();let s;if(/^#[0-9a-f]{3}$/i.test(i))s=[parseInt(i[1]+i[1],16),parseInt(i[2]+i[2],16),parseInt(i[3]+i[3],16),255];else if(/^#[0-9a-f]{6}$/i.test(i))s=[parseInt(i.slice(1,3),16),parseInt(i.slice(3,5),16),parseInt(i.slice(5,7),16),255];else{const o=i.match(/^rgba?\(([^)]+)\)$/i);if(o){const a=o[1].split(/[\s,\/]+/).filter(Boolean),c=a.slice(0,3).some(h=>h.includes("%")),l=a.map(h=>Number(h.replace("%","")));l.length>=3&&l.slice(0,3).every(Number.isFinite)&&(s=[V(c?l[0]*2.55:l[0]),V(c?l[1]*2.55:l[1]),V(c?l[2]*2.55:l[2]),V((Number.isFinite(l[3])?l[3]:1)*255)])}}const n=s??t;return[n[0],n[1],n[2],V(n[3]*r)]}function V(e){return Math.max(0,Math.min(255,Math.round(e)))}class se{constructor(t={}){d(this,"canvas");d(this,"renderer");d(this,"registry");d(this,"nativeHost");d(this,"options");d(this,"lastResult");d(this,"activeNativeLoader");var r;if(this.options={autoFit:!0,...t},this.registry=t.registry??Ut(t),t.loaders)for(const i of t.loaders)this.registry.register(i);if(this.canvas=t.canvas??document.createElement("canvas"),this.canvas.classList.add("cad-viewer-canvas"),t.container)t.container.classList.add("cad-viewer-container"),t.canvas||(this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",t.container.appendChild(this.canvas)),this.nativeHost=t.nativeHost??document.createElement("div"),this.nativeHost.classList.add("cad-viewer-native-host"),t.nativeHost||t.container.appendChild(this.nativeHost);else if(t.nativeHost)this.nativeHost=t.nativeHost,this.nativeHost.classList.add("cad-viewer-native-host");else if((r=t.canvas)!=null&&r.parentElement){t.canvas.parentElement.classList.add("cad-viewer-container");const i=document.createElement("div");i.classList.add("cad-viewer-native-host"),t.canvas.parentElement.appendChild(i),this.nativeHost=i}this.renderer=hr(t.renderer??"auto",this.canvas,t.canvasOptions),this.renderer.onStats=i=>{var s,n;return(n=(s=this.options).onRenderStats)==null?void 0:n.call(s,i)},this.renderer.onViewChange=i=>{var s,n;return(n=(s=this.options).onViewChange)==null?void 0:n.call(s,i)}}registerLoader(t){return this.registry.register(t),this}async loadFile(t,r={}){var i,s;return(s=(i=this.options).onLoadStart)==null||s.call(i,t),this.loadThroughRegistry({file:t,fileName:t.name},r,t.name)}async loadBuffer(t,r,i={}){var s,n;return(n=(s=this.options).onLoadStart)==null||n.call(s,t),this.loadThroughRegistry({buffer:t,fileName:r},i,r)}async load(t,r={}){var i,s,n;return(s=(i=this.options).onLoadStart)==null||s.call(i,t),this.loadThroughRegistry(t,r,t.fileName??((n=t.file)==null?void 0:n.name))}setDocument(t,r){var s,n;this.deactivateNativeRenderer();const i={document:t,raw:t.raw,bytes:0,elapsedMs:0,format:t.format,warnings:t.warnings,summary:_(t),fileName:r};return this.renderer.setDocument(t),this.options.autoFit||this.renderer.render(),this.lastResult=i,(n=(s=this.options).onLoad)==null||n.call(s,i),i}fit(){var t,r;this.activeNativeLoader?(r=(t=this.activeNativeLoader).fit)==null||r.call(t):this.renderer.fitToView()}zoomIn(){var t,r;this.activeNativeLoader?(r=(t=this.activeNativeLoader).zoomIn)==null||r.call(t):this.renderer.zoomIn()}zoomOut(){var t,r;this.activeNativeLoader?(r=(t=this.activeNativeLoader).zoomOut)==null||r.call(t):this.renderer.zoomOut()}resize(){var t,r;this.activeNativeLoader?(r=(t=this.activeNativeLoader).resize)==null||r.call(t):this.renderer.resize()}setCanvasOptions(t){var r,i;this.options.canvasOptions={...this.options.canvasOptions??{},...t},this.renderer.setOptions(t),this.activeNativeLoader&&((i=(r=this.activeNativeLoader).setNativeOptions)==null||i.call(r,{...this.mergeLoadOptions({}),dwfBackground:t.background??this.options.dwfBackground}))}async preloadDwg(t={}){const r=this.registry.list().find(i=>i.id==="dwg");if(!(r!=null&&r.preload))throw new Error("The registered DWG loader does not support preload().");return r.preload(this.mergeLoadOptions(t))}clear(){this.lastResult=void 0,this.deactivateNativeRenderer(),this.renderer.clear()}destroy(){var t,r,i;this.deactivateNativeRenderer();for(const s of this.registry.list()){const n=s;(t=n.terminateWorker)==null||t.call(n),(r=n.unmount)==null||r.call(n),(i=n.destroy)==null||i.call(n)}this.renderer.destroy()}getLoadResult(){return this.lastResult}getDocument(){var t;return this.activeNativeLoader?(t=this.lastResult)==null?void 0:t.document:this.renderer.getDocument()}getZoomPercent(){return this.activeNativeLoader?100:this.renderer.getZoomPercent()}isNativeRendererActive(){return!!this.activeNativeLoader}async loadThroughRegistry(t,r,i){var s,n;try{const o=this.mergeLoadOptions(r);xt(o.signal);const a=await this.registry.detect(t),c={...t,buffer:a.bytes};if(Vt(a.loader))return await this.applyNativeLoadResult(a.loader,c,o,i);const l=await a.loader.load(c,o);return this.applyLoadResult(l,i)}catch(o){const a=lr(o);throw(n=(s=this.options).onError)==null||n.call(s,a),a}}applyLoadResult(t,r){var s,n,o,a;this.deactivateNativeRenderer(),(n=(s=this.options).onLoadProgress)==null||n.call(s,{phase:"render",format:t.format,message:"Rendering normalized CAD scene…",percent:96}),this.renderer.setDocument(t.document),this.options.autoFit||this.renderer.render();const i={...t,fileName:r,summary:_(t.document)};return this.lastResult=i,(a=(o=this.options).onLoad)==null||a.call(o,i),i}async applyNativeLoadResult(t,r,i,s){var n,o,a;if(!this.nativeHost)throw new Error("Native DWF rendering requires CadViewerOptions.container, nativeHost, or a canvas parent element.");xt(i.signal),this.renderer.clear(),(n=this.activeNativeLoader)==null||n.unmount(),this.activeNativeLoader=t,this.canvas.style.display="none",this.nativeHost.classList.add("is-active");try{const c=await t.mount(r,this.nativeHost,i);xt(i.signal);const l={...c,fileName:s,summary:_(c.document)};return this.lastResult=l,this.emitNativeRenderStats(c),(a=(o=this.options).onLoad)==null||a.call(o,l),l}catch(c){throw this.deactivateNativeRenderer(),c}}deactivateNativeRenderer(){var t,r;if(!this.activeNativeLoader&&!((t=this.nativeHost)!=null&&t.classList.contains("is-active"))){this.canvas.style.display="";return}(r=this.activeNativeLoader)==null||r.unmount(),this.activeNativeLoader=void 0,this.nativeHost&&(this.nativeHost.classList.remove("is-active"),this.nativeHost.replaceChildren()),this.canvas.style.display=""}emitNativeRenderStats(t){var o,a,c,l;const r=t.document.metadata,i=Number(((o=r.nativeRenderStats)==null?void 0:o.commands)??t.document.entities.length??0),n=String(((a=r.nativeRenderStats)==null?void 0:a.backend)??"webgl").includes("webgl")?"webgl":"canvas2d";(l=(c=this.options).onRenderStats)==null||l.call(c,{total:i,drawn:i,skipped:0,byType:_(t.document).byType,unsupported:{},renderElapsedMs:t.elapsedMs,backend:n,primitiveCount:i,visiblePrimitiveCount:i,culledPrimitiveCount:0,gpuMemoryBytes:void 0,buildElapsedMs:t.elapsedMs})}mergeLoadOptions(t){const r=this.options.onProgress,i=t.onProgress;return{...this.options,...t,onProgress:s=>{var n,o;(o=(n=this.options).onLoadProgress)==null||o.call(n,s),r==null||r(s),i&&i!==r&&i(s)}}}}function cr(e={}){return new se(e)}function lr(e){return e instanceof Error?e:new Error(String(e))}function xt(e){if(e!=null&&e.aborted)throw new DOMException("Loading cancelled.","AbortError")}function hr(e,t,r={}){if(e==="canvas2d")return new mt(t,r);if(e==="webgl")return new pt(t,r);if(gt())try{return new pt(t,r)}catch{}return new mt(t,r)}g.CadCanvasRenderer=mt,g.CadLoaderRegistry=kt,g.CadViewer=se,g.CadWebGLRenderer=pt,g.DwfLoader=zt,g.DwgLoader=Et,g.DwgWorkerClient=Pt,g.DxfLoader=Wt,g.colorFromAci=T,g.colorFromTrueColor=z,g.createCadDocument=st,g.createCadViewer=cr,g.createDefaultLoaderRegistry=Ut,g.detectCadFormat=L,g.inferEntityKind=A,g.isCadNativeRenderableLoader=Vt,g.isWebGLAvailable=gt,g.normalizeCadEntity=It,g.readInputBytes=W,g.resolveCadColor=F,g.summarizeCadDocument=_,g.supportsDwgWorker=Z,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
29
|
+
`,i=re(e,e.VERTEX_SHADER,t),s=re(e,e.FRAGMENT_SHADER,r),n=e.createProgram();if(!n)throw new Error("Failed to create WebGL program.");if(e.attachShader(n,i),e.attachShader(n,s),e.linkProgram(n),!e.getProgramParameter(n,e.LINK_STATUS)){const h=e.getProgramInfoLog(n)??"Unknown WebGL program link error.";throw e.deleteProgram(n),new Error(h)}e.deleteShader(i),e.deleteShader(s);const o=e.getUniformLocation(n,"u_viewCenter"),a=e.getUniformLocation(n,"u_scale"),c=e.getUniformLocation(n,"u_viewport"),l=e.getUniformLocation(n,"u_pointSize");if(!o||!a||!c||!l)throw new Error("Failed to resolve WebGL shader uniforms.");return{program:n,aPosition:e.getAttribLocation(n,"a_position"),aColor:e.getAttribLocation(n,"a_color"),uViewCenter:o,uScale:a,uViewport:c,uPointSize:l}}function re(e,t,r){const i=e.createShader(t);if(!i)throw new Error("Failed to create WebGL shader.");if(e.shaderSource(i,r),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){const s=e.getShaderInfoLog(i)??"Unknown WebGL shader compile error.";throw e.deleteShader(i),new Error(s)}return i}function ir(e,t){let r=0;const i=a=>a.map(c=>{const l=ie(e,c.positions),h=ie(e,c.colors),d=c.positions.byteLength+c.colors.byteLength;return r+=d,{positionBuffer:l,colorBuffer:h,vertexCount:c.positions.length/2,primitiveCount:c.primitiveCount,bounds:c.bounds,gpuBytes:d}}),s=i(t.lineBatches),n=i(t.triangleBatches),o=i(t.pointBatches);return{origin:t.origin,lineBatches:s,triangleBatches:n,pointBatches:o,textItems:t.textItems,imageItems:t.imageItems,stats:t.stats,primitiveCount:t.primitiveCount,gpuMemoryBytes:r,buildElapsedMs:t.buildElapsedMs}}function ie(e,t){const r=e.createBuffer();if(!r)throw new Error("Failed to create WebGL buffer.");return e.bindBuffer(e.ARRAY_BUFFER,r),e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW),r}function sr(e,t,r){const i=performance.now(),s=D(r)?{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}:{x:0,y:0},n=new nr(e,t,r,s);for(const a of e.entities)n.addEntityTracked(a,0);const o=n.finalize();return o.buildElapsedMs=performance.now()-i,o}class nr{constructor(t,r,i,s){f(this,"lineBuckets",new Map);f(this,"triangleBuckets",new Map);f(this,"pointBuckets",new Map);f(this,"textItems",[]);f(this,"imageItems",[]);f(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});f(this,"tileSize");f(this,"maxVerticesPerBatch");f(this,"primitiveCount",0);this.document=t,this.opts=r,this.bounds=i,this.origin=s;const n=D(i)?Math.max(i.maxX-i.minX,i.maxY-i.minY,1e-9):1;this.tileSize=r.enableSpatialIndex?n/Math.max(8,r.spatialIndexCellCount):Number.POSITIVE_INFINITY,this.maxVerticesPerBatch=Math.max(4096,Math.floor(r.maxVerticesPerBatch))}addEntityTracked(t,r){this.stats.total++;const i=String(t.type??"UNKNOWN").toUpperCase();this.stats.byType[i]=(this.stats.byType[i]??0)+1;const s=this.lookupLayer(t.layer);if(t.isVisible===!1||!Zt(s)){this.stats.skipped++;return}this.addEntity(t,i,r)}finalize(){const t=vt(this.lineBuckets,this.maxVerticesPerBatch),r=vt(this.triangleBuckets,this.maxVerticesPerBatch),i=vt(this.pointBuckets,this.maxVerticesPerBatch);return this.stats.primitiveCount=this.primitiveCount,{origin:this.origin,lineBatches:t,triangleBatches:r,pointBatches:i,textItems:this.textItems,imageItems:this.imageItems,stats:this.stats,primitiveCount:this.primitiveCount,buildElapsedMs:0}}addEntity(t,r,i){switch(t.kind??A(r)){case"line":return this.addLineEntity(t);case"circle":return this.addCircleEntity(t);case"arc":return this.addArcEntity(t);case"polyline":return this.addPolylineEntity(t);case"ellipse":return this.addEllipseEntity(t);case"text":return this.addTextEntity(t);case"point":return this.addPointEntity(t);case"insert":return this.addInsertEntity(t,i);case"solid":return this.addSolidEntity(t);case"hatch":return this.addHatchEntity(t);case"spline":return this.addSplineEntity(t);case"path":return this.addPathEntity(t);case"image":return this.addImageEntity(t);case"viewport":return this.markSkipped(r);default:this.stats.unsupported[r]=(this.stats.unsupported[r]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.addUnsupportedMarker(t)}}addLineEntity(t){if(!m(t.startPoint)||!m(t.endPoint))return this.markSkipped("LINE");this.addSegment(t.startPoint,t.endPoint,this.strokeBytes(t)),this.stats.drawn++}addCircleEntity(t){const r=t.center,i=Number(t.radius);if(!m(r)||!Number.isFinite(i))return this.markSkipped("CIRCLE");const s=Math.max(16,Math.min(this.opts.maxCurveSegments,Math.ceil(Math.sqrt(Math.abs(i))*12))),n=J(r,i,0,Math.PI*2,!0,s);this.addPolyline(n,!0,this.strokeBytes(t)),this.stats.drawn++}addArcEntity(t){const r=t.center,i=Number(t.radius),s=Number(t.startAngle),n=Number(t.endAngle);if(!m(r)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(n))return this.markSkipped("ARC");this.addPolyline(J(r,i,s,n,!0,this.opts.maxCurveSegments),!1,this.strokeBytes(t)),this.stats.drawn++}addPolylineEntity(t){const r=t.vertices??t.points;if(!Array.isArray(r)||r.length<2)return this.markSkipped(String(t.type));const i=!!t.isClosed||(Number(t.flag)&1)===1,s=[],n=i?r.length:r.length-1;for(let o=0;o<n;o++){const a=r[o],c=r[(o+1)%r.length];if(!m(a)||!m(c))continue;const l=Ft(a,c,Number(a.bulge??0),Math.max(4,Math.min(24,this.opts.maxCurveSegments/4)));s.length>0&&l.shift(),s.push(...l)}if(s.length<2)return this.markSkipped(String(t.type));this.addPolyline(s,i,this.strokeBytes(t)),this.stats.drawn++}addEllipseEntity(t){if(!m(t.center)||!m(t.majorAxisEndPoint))return this.markSkipped("ELLIPSE");const r=Q(t.center,t.majorAxisEndPoint,Number(t.axisRatio??1),Number(t.startAngle??0),Number(t.endAngle??Math.PI*2),this.opts.maxCurveSegments),i=Math.abs(Number(t.endAngle??Math.PI*2)-Number(t.startAngle??0))>=Math.PI*2-1e-6;this.addPolyline(r,i,this.strokeBytes(t)),this.stats.drawn++}addTextEntity(t){const r=t.insertionPoint??t.startPoint??t.center,i=Wt(String(t.text??t.value??"")),s=Number(t.textHeight??t.height??1);if(!m(r)||!i||!Number.isFinite(s))return this.markSkipped(String(t.type));const n=x(r),o=Math.max(1,i.split(/\r?\n/g).reduce((c,l)=>Math.max(c,l.length),0))*Math.abs(s)*.62,a=Math.max(1,i.split(/\r?\n/g).length)*Math.abs(s)*1.22;this.textItems.push({point:n,text:i,height:s,rotation:Number(t.rotation??0),color:F(t,this.document,this.colorOptions()),opacity:O(Number(t.opacity??1),0,1),bounds:{minX:n.x-o*.1,minY:n.y-a,maxX:n.x+o,maxY:n.y+a}}),this.stats.drawn++}addPointEntity(t){const r=t.point??t.location??t.center??t.insertionPoint;if(!m(r))return this.markSkipped("POINT");this.addPoint(r,this.strokeBytes(t)),this.stats.drawn++}addInsertEntity(t,r){const i=this.lookupBlock(t.blockName??t.name);if(i&&r<this.opts.maxInsertDepth){const n=it(t,i.basePoint??{x:0,y:0});for(const o of i.entities){const a=qt(o,t,this.document,this.colorOptions());this.addEntityTracked(st(a,n),r+1)}return}const s=t.insertionPoint;if(!m(s))return this.markSkipped("INSERT");if(this.addPoint(s,this.strokeBytes(t)),Array.isArray(t.attribs))for(const n of t.attribs)this.addTextEntity(n);this.stats.drawn++}addSolidEntity(t){const r=t.vertices??t.points;if(!Array.isArray(r)||r.length<3)return this.markSkipped(String(t.type));const i=r.filter(m).map(x);if(i.length<3)return this.markSkipped(String(t.type));const s=this.fillBytes(t)??this.strokeBytes(t);this.addTriangleFan(i,s),this.addPolyline(i,!0,this.strokeBytes(t)),this.stats.drawn++}addHatchEntity(t){var o;const r=t.loops;if(!Array.isArray(r)||r.length===0)return this.markSkipped("HATCH");const i=this.strokeBytes(t),s=this.fillBytes(t);let n=!1;for(const a of r){const c=(o=a.commands)!=null&&o.length?se(a.commands,this.opts.maxCurveSegments):(a.vertices??[]).filter(m).map(x);c.length<2||(this.addPolyline(c,!0,i),s&&c.length>=3&&this.addTriangleFan(c,s),n=!0)}if(!n)return this.markSkipped("HATCH");this.stats.drawn++}addSplineEntity(t){var i;const r=(i=t.fitPoints)!=null&&i.length?t.fitPoints:t.controlPoints;if(!r||r.length<2)return this.markSkipped("SPLINE");this.addPolyline(r.filter(m).map(x),!!t.isClosed,this.strokeBytes(t)),this.stats.drawn++}addPathEntity(t){var s;if(!((s=t.commands)!=null&&s.length))return this.markSkipped(String(t.type));const r=se(t.commands,this.opts.maxCurveSegments);if(r.length<2)return this.markSkipped(String(t.type));this.addPolyline(r,!1,this.strokeBytes(t));const i=this.fillBytes(t);i&&r.length>=3&&this.addTriangleFan(r,i),this.stats.drawn++}addImageEntity(t){const r=t.insertionPoint;if(!m(r))return this.markSkipped(String(t.type));const i=Number(t.width??32),s=Number(t.height??32);if(!Number.isFinite(i)||!Number.isFinite(s))return this.markSkipped(String(t.type));const n=x(r),o=yt([n,{x:n.x+i,y:n.y-s}]);this.imageItems.push({point:n,width:i,height:s,source:t.imageDataUrl??t.imageSource,color:F(t,this.document,this.colorOptions()),opacity:O(Number(t.opacity??1),0,1),bounds:o}),this.stats.drawn++}addUnsupportedMarker(t){const r=ne(t);r&&this.addPoint(r,this.strokeBytes(t))}addPolyline(t,r,i){const s=t.filter(m).map(x);if(!(s.length<2)){for(let n=0;n<s.length-1;n++)this.addSegment(s[n],s[n+1],i);r&&this.addSegment(s[s.length-1],s[0],i)}}addSegment(t,r,i){if(!m(t)||!m(r)||Math.hypot(t.x-r.x,t.y-r.y)<=1e-14)return;const s=this.batchFor(this.lineBuckets,yt([t,r]));X(s,t,i,this.origin),X(s,r,i,this.origin),s.primitiveCount++,this.primitiveCount++}addPoint(t,r){const i=this.batchFor(this.pointBuckets,lr(t));X(i,t,r,this.origin),i.primitiveCount++,this.primitiveCount++}addTriangleFan(t,r){const i=t.filter(m).map(x);if(i.length<3)return;const s=yt(i),n=this.batchFor(this.triangleBuckets,s);for(let o=1;o<i.length-1;o++)X(n,i[0],r,this.origin),X(n,i[o],r,this.origin),X(n,i[o+1],r,this.origin),n.primitiveCount++,this.primitiveCount++}batchFor(t,r){const i=this.bucketKey(r);let s=t.get(i);return s||(s=or(),t.set(i,s)),y(s.bounds,{x:r.minX,y:r.minY}),y(s.bounds,{x:r.maxX,y:r.maxY}),s}bucketKey(t){if(!Number.isFinite(this.tileSize))return"all";const r=(t.minX+t.maxX)/2,i=(t.minY+t.maxY)/2,s=Math.floor((r-this.bounds.minX)/this.tileSize),n=Math.floor((i-this.bounds.minY)/this.tileSize);return`${s}:${n}`}strokeBytes(t){return xt(F(t,this.document,this.colorOptions()),[255,255,255,255],O(Number(t.opacity??1),0,1))}fillBytes(t){const r=lt(t,this.document,this.colorOptions());return r?xt(r,[255,255,255,255],O(Number(t.opacity??1),0,1)):void 0}colorOptions(){return{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}}markSkipped(t){this.stats.skipped++,this.stats.unsupported[t]=this.stats.unsupported[t]??0}lookupLayer(t){if(t)return this.document.layers[t]??this.document.layers[t.toLowerCase()]??Object.values(this.document.layers).find(r=>r.name.toLowerCase()===t.toLowerCase())}lookupBlock(t){if(t)return this.document.blocks[t]??this.document.blocks[t.toLowerCase()]??Object.values(this.document.blocks).find(r=>r.name.toLowerCase()===t.toLowerCase())}}function or(){return{positions:[],colors:[],bounds:E(),primitiveCount:0}}function X(e,t,r,i){e.positions.push(t.x-i.x,t.y-i.y),e.colors.push(r[0],r[1],r[2],r[3])}function vt(e,t){const r=[];for(const i of e.values()){const s=i.positions.length/2;if(s<=0||!D(i.bounds))continue;if(s<=t){r.push({positions:new Float32Array(i.positions),colors:new Uint8Array(i.colors),bounds:{...i.bounds},primitiveCount:i.primitiveCount});continue}const n=ar(i),o=Math.max(n,Math.floor(t/n)*n);for(let a=0;a<s;a+=o){const c=Math.min(s,a+o),l=i.positions.slice(a*2,c*2),h=i.colors.slice(a*4,c*4),d=E();for(let u=0;u<l.length;u+=2)y(d,{x:l[u],y:l[u+1]});r.push({positions:new Float32Array(l),colors:new Uint8Array(h),bounds:{...i.bounds},primitiveCount:Math.floor((c-a)/n)})}}return r}function ar(e){const t=e.positions.length/2;return t===e.primitiveCount?1:t===e.primitiveCount*3?3:2}function cr(e,t){var n;const r=E();if((n=e.pages)!=null&&n.length)for(const o of e.pages)y(r,{x:0,y:0}),y(r,{x:o.width,y:o.height});const i=o=>{if(o)return e.blocks[o]??e.blocks[o.toLowerCase()]??Object.values(e.blocks).find(a=>a.name.toLowerCase()===o.toLowerCase())},s=(o,a)=>{const c=String(o.type??"").toUpperCase(),l=o.kind??A(c);if(l==="insert"){const h=i(o.blockName??o.name);if(h&&a<t.maxInsertDepth){const d=it(o,h.basePoint??{x:0,y:0});for(const u of h.entities)s(st(u,d),a+1);return}}if(l==="line")m(o.startPoint)&&y(r,o.startPoint),m(o.endPoint)&&y(r,o.endPoint);else if(l==="circle"||l==="arc")m(o.center)&&Number.isFinite(o.radius)&&At(r,o.center,Number(o.radius));else if(l==="polyline"||l==="solid"||l==="spline")for(const h of[...o.vertices??[],...o.points??[],...o.controlPoints??[],...o.fitPoints??[]])m(h)&&y(r,h);else if(l==="ellipse")m(o.center)&&m(o.majorAxisEndPoint)&&Q(o.center,o.majorAxisEndPoint,Number(o.axisRatio??1),Number(o.startAngle??0),Number(o.endAngle??Math.PI*2),t.maxCurveSegments).forEach(h=>y(r,h));else if(l==="path")for(const h of o.commands??[])for(const d of h.points)y(r,d);else if(l==="hatch")for(const h of o.loops??[]){for(const d of h.vertices??[])y(r,d);for(const d of h.commands??[])for(const u of d.points)y(r,u)}else{const h=ne(o);h&&y(r,h)}};for(const o of e.entities)s(o,0);return Bt(r)}function se(e,t){const r=[];let i,s;const n=o=>{(!r.length||Math.hypot(r[r.length-1].x-o.x,r[r.length-1].y-o.y)>1e-12)&&r.push(x(o)),i=x(o)};for(const o of e)if(o.cmd==="M")i=x(o.points[0]),s=i,n(i);else if(o.cmd==="L")n(o.points[0]);else if(o.cmd==="Q"&&i&&o.points.length>=2){const a=i,[c,l]=o.points,h=Math.max(4,Math.min(t,24));for(let d=1;d<=h;d++){const u=d/h,p=1-u;n({x:p*p*a.x+2*p*u*c.x+u*u*l.x,y:p*p*a.y+2*p*u*c.y+u*u*l.y})}}else if(o.cmd==="C"&&i&&o.points.length>=3){const a=i,[c,l,h]=o.points,d=Math.max(6,Math.min(t,32));for(let u=1;u<=d;u++){const p=u/d,b=1-p;n({x:b**3*a.x+3*b*b*p*c.x+3*b*p*p*l.x+p**3*h.x,y:b**3*a.y+3*b*b*p*c.y+3*b*p*p*l.y+p**3*h.y})}}else o.cmd==="Z"&&s&&n(s);return r}function ne(e){for(const t of["startPoint","insertionPoint","center","point","location"]){const r=e[t];if(m(r))return x(r)}if(Array.isArray(e.vertices)&&m(e.vertices[0]))return x(e.vertices[0]);if(Array.isArray(e.commands)&&e.commands.length){const t=e.commands.find(r=>r.points.length>0);if(t)return x(t.points[0])}}function yt(e){const t=E();for(const r of e)y(t,r);return t}function lr(e){return{minX:e.x,minY:e.y,maxX:e.x,maxY:e.y}}function wt(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function hr(e,t){return t.trueColorByteOrder!==void 0&&t.trueColorByteOrder!==e.trueColorByteOrder||t.contrastMode!==void 0&&t.contrastMode!==e.contrastMode||t.minColorContrast!==void 0&&t.minColorContrast!==e.minColorContrast||t.foreground!==void 0&&t.foreground!==e.foreground||t.background!==void 0&&t.background!==e.background||t.maxInsertDepth!==void 0&&t.maxInsertDepth!==e.maxInsertDepth||t.maxCurveSegments!==void 0&&t.maxCurveSegments!==e.maxCurveSegments||t.spatialIndexCellCount!==void 0&&t.spatialIndexCellCount!==e.spatialIndexCellCount||t.maxVerticesPerBatch!==void 0&&t.maxVerticesPerBatch!==e.maxVerticesPerBatch||t.enableSpatialIndex!==void 0&&t.enableSpatialIndex!==e.enableSpatialIndex}function dr(e,t){return{...e.stats,renderElapsedMs:t,backend:"webgl",primitiveCount:e.primitiveCount,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:e.gpuMemoryBytes,buildElapsedMs:e.buildElapsedMs}}function fr(e){return{total:e.total,drawn:e.drawn,skipped:e.skipped,byType:{...e.byType},unsupported:{...e.unsupported},renderElapsedMs:e.renderElapsedMs,backend:e.backend,primitiveCount:e.primitiveCount,visiblePrimitiveCount:e.visiblePrimitiveCount,culledPrimitiveCount:e.culledPrimitiveCount,gpuMemoryBytes:e.gpuMemoryBytes,buildElapsedMs:e.buildElapsedMs}}function xt(e,t,r=1){const i=e.trim().toLowerCase();let s;if(/^#[0-9a-f]{3}$/i.test(i))s=[parseInt(i[1]+i[1],16),parseInt(i[2]+i[2],16),parseInt(i[3]+i[3],16),255];else if(/^#[0-9a-f]{6}$/i.test(i))s=[parseInt(i.slice(1,3),16),parseInt(i.slice(3,5),16),parseInt(i.slice(5,7),16),255];else{const o=i.match(/^rgba?\(([^)]+)\)$/i);if(o){const a=o[1].split(/[\s,\/]+/).filter(Boolean),c=a.slice(0,3).some(h=>h.includes("%")),l=a.map(h=>Number(h.replace("%","")));l.length>=3&&l.slice(0,3).every(Number.isFinite)&&(s=[V(c?l[0]*2.55:l[0]),V(c?l[1]*2.55:l[1]),V(c?l[2]*2.55:l[2]),V((Number.isFinite(l[3])?l[3]:1)*255)])}}const n=s??t;return[n[0],n[1],n[2],V(n[3]*r)]}function V(e){return Math.max(0,Math.min(255,Math.round(e)))}class oe{constructor(t={}){f(this,"canvas");f(this,"renderer");f(this,"registry");f(this,"nativeHost");f(this,"options");f(this,"lastResult");f(this,"activeNativeLoader");var r;if(this.options={autoFit:!0,...t},this.registry=t.registry??$t(t),t.loaders)for(const i of t.loaders)this.registry.register(i);if(this.canvas=t.canvas??document.createElement("canvas"),this.canvas.classList.add("cad-viewer-canvas"),t.container)t.container.classList.add("cad-viewer-container"),t.canvas||(this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",t.container.appendChild(this.canvas)),this.nativeHost=t.nativeHost??document.createElement("div"),this.nativeHost.classList.add("cad-viewer-native-host"),t.nativeHost||t.container.appendChild(this.nativeHost);else if(t.nativeHost)this.nativeHost=t.nativeHost,this.nativeHost.classList.add("cad-viewer-native-host");else if((r=t.canvas)!=null&&r.parentElement){t.canvas.parentElement.classList.add("cad-viewer-container");const i=document.createElement("div");i.classList.add("cad-viewer-native-host"),t.canvas.parentElement.appendChild(i),this.nativeHost=i}this.renderer=pr(t.renderer??"auto",this.canvas,t.canvasOptions),this.renderer.onStats=i=>{var s,n;return(n=(s=this.options).onRenderStats)==null?void 0:n.call(s,i)},this.renderer.onViewChange=i=>{var s,n;return(n=(s=this.options).onViewChange)==null?void 0:n.call(s,i)}}registerLoader(t){return this.registry.register(t),this}async loadFile(t,r={}){var i,s;return(s=(i=this.options).onLoadStart)==null||s.call(i,t),this.loadThroughRegistry({file:t,fileName:t.name},r,t.name)}async loadBuffer(t,r,i={}){var s,n;return(n=(s=this.options).onLoadStart)==null||n.call(s,t),this.loadThroughRegistry({buffer:t,fileName:r},i,r)}async load(t,r={}){var i,s,n;return(s=(i=this.options).onLoadStart)==null||s.call(i,t),this.loadThroughRegistry(t,r,t.fileName??((n=t.file)==null?void 0:n.name))}setDocument(t,r){var s,n;this.deactivateNativeRenderer();const i={document:t,raw:t.raw,bytes:0,elapsedMs:0,format:t.format,warnings:t.warnings,summary:_(t),fileName:r};return this.renderer.setDocument(t),this.options.autoFit||this.renderer.render(),this.lastResult=i,(n=(s=this.options).onLoad)==null||n.call(s,i),i}fit(){var t,r;this.activeNativeLoader?(r=(t=this.activeNativeLoader).fit)==null||r.call(t):this.renderer.fitToView()}zoomIn(){var t,r;this.activeNativeLoader?(r=(t=this.activeNativeLoader).zoomIn)==null||r.call(t):this.renderer.zoomIn()}zoomOut(){var t,r;this.activeNativeLoader?(r=(t=this.activeNativeLoader).zoomOut)==null||r.call(t):this.renderer.zoomOut()}resize(){var t,r;this.activeNativeLoader?(r=(t=this.activeNativeLoader).resize)==null||r.call(t):this.renderer.resize()}setCanvasOptions(t){var r,i;this.options.canvasOptions={...this.options.canvasOptions??{},...t},this.renderer.setOptions(t),this.activeNativeLoader&&((i=(r=this.activeNativeLoader).setNativeOptions)==null||i.call(r,{...this.mergeLoadOptions({}),dwfBackground:t.background??this.options.dwfBackground}))}async preloadDwg(t={}){const r=this.registry.list().find(i=>i.id==="dwg");if(!(r!=null&&r.preload))throw new Error("The registered DWG loader does not support preload().");return r.preload(this.mergeLoadOptions(t))}clear(){this.lastResult=void 0,this.deactivateNativeRenderer(),this.renderer.clear()}destroy(){var t,r,i;this.deactivateNativeRenderer();for(const s of this.registry.list()){const n=s;(t=n.terminateWorker)==null||t.call(n),(r=n.unmount)==null||r.call(n),(i=n.destroy)==null||i.call(n)}this.renderer.destroy()}getLoadResult(){return this.lastResult}getDocument(){var t;return this.activeNativeLoader?(t=this.lastResult)==null?void 0:t.document:this.renderer.getDocument()}getZoomPercent(){return this.activeNativeLoader?100:this.renderer.getZoomPercent()}isNativeRendererActive(){return!!this.activeNativeLoader}async loadThroughRegistry(t,r,i){var s,n;try{const o=this.mergeLoadOptions(r);Ct(o.signal);const a=await this.registry.detect(t),c={...t,buffer:a.bytes};if(jt(a.loader))return await this.applyNativeLoadResult(a.loader,c,o,i);const l=await a.loader.load(c,o);return this.applyLoadResult(l,i)}catch(o){const a=mr(o);throw(n=(s=this.options).onError)==null||n.call(s,a),a}}applyLoadResult(t,r){var s,n,o,a;this.deactivateNativeRenderer(),(n=(s=this.options).onLoadProgress)==null||n.call(s,{phase:"render",format:t.format,message:"Rendering normalized CAD scene…",percent:96}),this.renderer.setDocument(t.document),this.options.autoFit||this.renderer.render();const i={...t,fileName:r,summary:_(t.document)};return this.lastResult=i,(a=(o=this.options).onLoad)==null||a.call(o,i),i}async applyNativeLoadResult(t,r,i,s){var n,o,a;if(!this.nativeHost)throw new Error("Native DWF rendering requires CadViewerOptions.container, nativeHost, or a canvas parent element.");Ct(i.signal),this.renderer.clear(),(n=this.activeNativeLoader)==null||n.unmount(),this.activeNativeLoader=t,this.canvas.style.display="none",this.nativeHost.classList.add("is-active");try{const c=await t.mount(r,this.nativeHost,i);Ct(i.signal);const l={...c,fileName:s,summary:_(c.document)};return this.lastResult=l,this.emitNativeRenderStats(c),(a=(o=this.options).onLoad)==null||a.call(o,l),l}catch(c){throw this.deactivateNativeRenderer(),c}}deactivateNativeRenderer(){var t,r;if(!this.activeNativeLoader&&!((t=this.nativeHost)!=null&&t.classList.contains("is-active"))){this.canvas.style.display="";return}(r=this.activeNativeLoader)==null||r.unmount(),this.activeNativeLoader=void 0,this.nativeHost&&(this.nativeHost.classList.remove("is-active"),this.nativeHost.replaceChildren()),this.canvas.style.display=""}emitNativeRenderStats(t){var o,a,c,l;const r=t.document.metadata,i=Number(((o=r.nativeRenderStats)==null?void 0:o.commands)??t.document.entities.length??0),n=String(((a=r.nativeRenderStats)==null?void 0:a.backend)??"webgl").includes("webgl")?"webgl":"canvas2d";(l=(c=this.options).onRenderStats)==null||l.call(c,{total:i,drawn:i,skipped:0,byType:_(t.document).byType,unsupported:{},renderElapsedMs:t.elapsedMs,backend:n,primitiveCount:i,visiblePrimitiveCount:i,culledPrimitiveCount:0,gpuMemoryBytes:void 0,buildElapsedMs:t.elapsedMs})}mergeLoadOptions(t){const r=this.options.onProgress,i=t.onProgress;return{...this.options,...t,onProgress:s=>{var n,o;(o=(n=this.options).onLoadProgress)==null||o.call(n,s),r==null||r(s),i&&i!==r&&i(s)}}}}function ur(e={}){return new oe(e)}function mr(e){return e instanceof Error?e:new Error(String(e))}function Ct(e){if(e!=null&&e.aborted)throw new DOMException("Loading cancelled.","AbortError")}function pr(e,t,r={}){if(e==="canvas2d")return new pt(t,r);if(e==="webgl")return new gt(t,r);if(bt())try{return new gt(t,r)}catch{}return new pt(t,r)}g.CadCanvasRenderer=pt,g.CadLoaderRegistry=kt,g.CadViewer=oe,g.CadWebGLRenderer=gt,g.DwfLoader=Yt,g.DwgLoader=It,g.DwgWorkerClient=St,g.DxfLoader=Rt,g.colorFromAci=T,g.colorFromTrueColor=z,g.createCadDocument=nt,g.createCadViewer=ur,g.createDefaultLoaderRegistry=$t,g.detectCadFormat=L,g.inferEntityKind=A,g.isCadNativeRenderableLoader=jt,g.isWebGLAvailable=bt,g.normalizeCadEntity=Tt,g.readInputBytes=W,g.resolveCadColor=F,g.summarizeCadDocument=_,g.supportsDwgWorker=Z,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
30
30
|
//# sourceMappingURL=cad-viewer.umd.cjs.map
|