@mlightcad/cad-simple-viewer 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(w,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("@mlightcad/data-model"),require("three"),require("@mlightcad/mtext-renderer"),require("three/examples/jsm/utils/BufferGeometryUtils.js"),require("three/examples/jsm/controls/OrbitControls"),require("lodash-es"),require("three/examples/jsm/libs/stats.module")):typeof define=="function"&&define.amd?define(["exports","@mlightcad/data-model","three","@mlightcad/mtext-renderer","three/examples/jsm/utils/BufferGeometryUtils.js","three/examples/jsm/controls/OrbitControls","lodash-es","three/examples/jsm/libs/stats.module"],g):(w=typeof globalThis<"u"?globalThis:w||self,g(w["cad-simple-viewer"]={},w.dataModel,w.h,w.mtextRenderer,w.BufferGeometryUtils_js,w.OrbitControls,w.lodashEs,w.Stats))})(this,function(w,g,lt,V,ut,dt,ve,mt){"use strict";function gt(c){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(c){for(const t in c)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(c,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>c[t]})}}return e.default=c,Object.freeze(e)}const u=gt(lt);class Te{constructor(e,t){this._view=e,this._doc=t,t.database.events.entityAppended.addEventListener(i=>{this.view.addEntity(i.entity)}),t.database.events.entityModified.addEventListener(i=>{this.view.updateEntity(i.entity)}),t.database.events.layerModified.addEventListener(i=>{this._view.setLayerVisibility(i.layer.name,!i.layer.isOff)}),t.database.events.headerSysVarChanged.addEventListener(i=>{i.name=="pdmode"&&this._view.rerenderPoints(i.database.pdmode)}),t.database.events.dictObjetSet.addEventListener(i=>{i.object instanceof g.AcDbLayout&&this._view.addLayout(i.object)}),e.selectionSet.events.selectionAdded.addEventListener(i=>{e.highlight(i.ids)}),e.selectionSet.events.selectionRemoved.addEventListener(i=>{e.unhighlight(i.ids)})}get view(){return this._view}get doc(){return this._doc}}class G{constructor(){this.events={commandWillStart:new g.AcCmEventManager,commandEnded:new g.AcCmEventManager},this._globalName="",this._localName=""}get globalName(){return this._globalName}set globalName(e){this._globalName=e}get localName(){return this._localName}set localName(e){this._localName=e}tirgger(e){this.events.commandWillStart.dispatch({command:this}),this.execute(e),this.events.commandEnded.dispatch({command:this})}execute(e){}}class pt{constructor(e){this._index=0,this._commands=[],e.forEach(t=>{const i=t.groupName;t.commandsByGlobalName.forEach(n=>{this._commands.push({command:n,commandGroup:i})})})}[Symbol.iterator](){return this}get command(){return this._index<this._commands.length?this._commands[this._index].command:null}get commandGroup(){return this._index<this._commands.length?this._commands[this._index].commandGroup:null}next(){for(;this._index<this._commands.length;){const e=this._commands[this._index];return this._index+=1,{value:e,done:!1}}return{value:null,done:!0}}}const D=class D{constructor(){this._commandsByGroup=[],this._systemCommandGroup={groupName:D.SYSTEMT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map},this._defaultCommandGroup={groupName:D.DEFAUT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map},this._commandsByGroup.push(this._systemCommandGroup),this._commandsByGroup.push(this._defaultCommandGroup)}static get instance(){return D._instance||(D._instance=new D),D._instance}addCommand(e,t,i,n){if(!t)throw new Error("[AcEdCommandStack] The global name of the command is required!");i||(i=t);let s=this._defaultCommandGroup;if(e){const r=this._commandsByGroup.find(o=>o.groupName==e);r?s=r:s={groupName:e,commandsByGlobalName:new Map,commandsByLocalName:new Map}}if(s.commandsByGlobalName.has(t))throw new Error(`[AcEdCommandStack] The command with global name '${t}' already exists!`);if(s.commandsByLocalName.has(i))throw new Error(`[AcEdCommandStack] The command with local name '${i}' already exists!`);s.commandsByGlobalName.set(t,n),s.commandsByLocalName.set(i,n),n.globalName=t,n.localName=i}iterator(){return new pt(this._commandsByGroup)}lookupGlobalCmd(e){let t;for(const i of this._commandsByGroup)if(t=i.commandsByGlobalName.get(e),t)break;return t}lookupLocalCmd(e){let t;for(const i of this._commandsByGroup)if(t=i.commandsByLocalName.get(e),t)break;return t}removeCmd(e,t){for(const i of this._commandsByGroup)if(i.groupName==e)return i.commandsByGlobalName.delete(t);return!1}removeGroup(e){let t=-1;return this._commandsByGroup.some((i,n)=>(t=n,i.groupName==e)),t>=0?(this._commandsByGroup.splice(t,1),!0):!1}};D.SYSTEMT_COMMAND_GROUP_NAME="ACAD",D.DEFAUT_COMMAND_GROUP_NAME="USER";let C=D;function yt(c){return{all:c=c||new Map,on:function(e,t){var i=c.get(e);i?i.push(t):c.set(e,[t])},off:function(e,t){var i=c.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):c.set(e,[]))},emit:function(e,t){var i=c.get(e);i&&i.slice().map(function(n){n(t)}),(i=c.get("*"))&&i.slice().map(function(n){n(e,t)})}}}const z=yt();function ft(c){z.emit("message",{message:c,type:"warning"})}var j=(c=>(c[c.NoSpecialCursor=-1]="NoSpecialCursor",c[c.Crosshair=0]="Crosshair",c[c.RectCursor=1]="RectCursor",c[c.RubberBand=2]="RubberBand",c[c.NotRotated=3]="NotRotated",c[c.TargetBox=4]="TargetBox",c[c.RotatedCrosshair=5]="RotatedCrosshair",c[c.CrosshairNoRotate=6]="CrosshairNoRotate",c[c.Invisible=7]="Invisible",c[c.EntitySelect=8]="EntitySelect",c[c.Parallelogram=9]="Parallelogram",c[c.EntitySelectNoPersp=10]="EntitySelectNoPersp",c[c.PkfirstOrGrips=11]="PkfirstOrGrips",c[c.CrosshairDashed=12]="CrosshairDashed",c[c.Grab=13]="Grab",c))(j||{});class De{constructor(){this._cursorMap=new Map,this._cursorMap.set(0,this.createRectCrossIcon(10,10))}setCursor(e,t){if(e<=-1)t.style.cursor="default";else if(e==13)t.style.cursor="grab";else{const i=this._cursorMap.get(e);i&&(t.style.cursor=i)}}encodeSvgToCursor(e,t,i){return`url('data:image/svg+xml;base64,${btoa(e)}') ${t} ${i}, auto`}createRectCrossIcon(e,t,i="white"){const n=e/2,s=e+2*t,r=`
1
+ (function(w,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("@mlightcad/data-model"),require("three"),require("@mlightcad/mtext-renderer"),require("three/examples/jsm/utils/BufferGeometryUtils.js"),require("three/examples/jsm/controls/OrbitControls"),require("lodash-es"),require("three/examples/jsm/libs/stats.module")):typeof define=="function"&&define.amd?define(["exports","@mlightcad/data-model","three","@mlightcad/mtext-renderer","three/examples/jsm/utils/BufferGeometryUtils.js","three/examples/jsm/controls/OrbitControls","lodash-es","three/examples/jsm/libs/stats.module"],g):(w=typeof globalThis<"u"?globalThis:w||self,g(w["cad-simple-viewer"]={},w.dataModel,w.h,w.mtextRenderer,w.BufferGeometryUtils_js,w.OrbitControls,w.lodashEs,w.Stats))})(this,function(w,g,lt,V,dt,ut,Se,mt){"use strict";function gt(c){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(c){for(const t in c)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(c,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>c[t]})}}return e.default=c,Object.freeze(e)}const d=gt(lt);class Te{constructor(e,t){this._view=e,this._doc=t,t.database.events.entityAppended.addEventListener(i=>{this.view.addEntity(i.entity)}),t.database.events.entityModified.addEventListener(i=>{this.view.updateEntity(i.entity)}),t.database.events.layerModified.addEventListener(i=>{this._view.updateLayer(i.layer)}),t.database.events.headerSysVarChanged.addEventListener(i=>{i.name=="pdmode"&&this._view.rerenderPoints(i.database.pdmode)}),t.database.events.dictObjetSet.addEventListener(i=>{i.object instanceof g.AcDbLayout&&this._view.addLayout(i.object)}),e.selectionSet.events.selectionAdded.addEventListener(i=>{e.highlight(i.ids)}),e.selectionSet.events.selectionRemoved.addEventListener(i=>{e.unhighlight(i.ids)})}get view(){return this._view}get doc(){return this._doc}}class G{constructor(){this.events={commandWillStart:new g.AcCmEventManager,commandEnded:new g.AcCmEventManager},this._globalName="",this._localName=""}get globalName(){return this._globalName}set globalName(e){this._globalName=e}get localName(){return this._localName}set localName(e){this._localName=e}tirgger(e){this.events.commandWillStart.dispatch({command:this}),this.execute(e),this.events.commandEnded.dispatch({command:this})}execute(e){}}class pt{constructor(e){this._index=0,this._commands=[],e.forEach(t=>{const i=t.groupName;t.commandsByGlobalName.forEach(n=>{this._commands.push({command:n,commandGroup:i})})})}[Symbol.iterator](){return this}get command(){return this._index<this._commands.length?this._commands[this._index].command:null}get commandGroup(){return this._index<this._commands.length?this._commands[this._index].commandGroup:null}next(){for(;this._index<this._commands.length;){const e=this._commands[this._index];return this._index+=1,{value:e,done:!1}}return{value:null,done:!0}}}const D=class D{constructor(){this._commandsByGroup=[],this._systemCommandGroup={groupName:D.SYSTEMT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map},this._defaultCommandGroup={groupName:D.DEFAUT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map},this._commandsByGroup.push(this._systemCommandGroup),this._commandsByGroup.push(this._defaultCommandGroup)}static get instance(){return D._instance||(D._instance=new D),D._instance}addCommand(e,t,i,n){if(!t)throw new Error("[AcEdCommandStack] The global name of the command is required!");i||(i=t);let s=this._defaultCommandGroup;if(e){const r=this._commandsByGroup.find(o=>o.groupName==e);r?s=r:s={groupName:e,commandsByGlobalName:new Map,commandsByLocalName:new Map}}if(s.commandsByGlobalName.has(t))throw new Error(`[AcEdCommandStack] The command with global name '${t}' already exists!`);if(s.commandsByLocalName.has(i))throw new Error(`[AcEdCommandStack] The command with local name '${i}' already exists!`);s.commandsByGlobalName.set(t,n),s.commandsByLocalName.set(i,n),n.globalName=t,n.localName=i}iterator(){return new pt(this._commandsByGroup)}lookupGlobalCmd(e){let t;for(const i of this._commandsByGroup)if(t=i.commandsByGlobalName.get(e),t)break;return t}lookupLocalCmd(e){let t;for(const i of this._commandsByGroup)if(t=i.commandsByLocalName.get(e),t)break;return t}removeCmd(e,t){for(const i of this._commandsByGroup)if(i.groupName==e)return i.commandsByGlobalName.delete(t);return!1}removeGroup(e){let t=-1;return this._commandsByGroup.some((i,n)=>(t=n,i.groupName==e)),t>=0?(this._commandsByGroup.splice(t,1),!0):!1}};D.SYSTEMT_COMMAND_GROUP_NAME="ACAD",D.DEFAUT_COMMAND_GROUP_NAME="USER";let C=D;function yt(c){return{all:c=c||new Map,on:function(e,t){var i=c.get(e);i?i.push(t):c.set(e,[t])},off:function(e,t){var i=c.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):c.set(e,[]))},emit:function(e,t){var i=c.get(e);i&&i.slice().map(function(n){n(t)}),(i=c.get("*"))&&i.slice().map(function(n){n(e,t)})}}}const z=yt();function ft(c){z.emit("message",{message:c,type:"warning"})}var j=(c=>(c[c.NoSpecialCursor=-1]="NoSpecialCursor",c[c.Crosshair=0]="Crosshair",c[c.RectCursor=1]="RectCursor",c[c.RubberBand=2]="RubberBand",c[c.NotRotated=3]="NotRotated",c[c.TargetBox=4]="TargetBox",c[c.RotatedCrosshair=5]="RotatedCrosshair",c[c.CrosshairNoRotate=6]="CrosshairNoRotate",c[c.Invisible=7]="Invisible",c[c.EntitySelect=8]="EntitySelect",c[c.Parallelogram=9]="Parallelogram",c[c.EntitySelectNoPersp=10]="EntitySelectNoPersp",c[c.PkfirstOrGrips=11]="PkfirstOrGrips",c[c.CrosshairDashed=12]="CrosshairDashed",c[c.Grab=13]="Grab",c))(j||{});class De{constructor(){this._cursorMap=new Map,this._cursorMap.set(0,this.createRectCrossIcon(10,10))}setCursor(e,t){if(e<=-1)t.style.cursor="default";else if(e==13)t.style.cursor="grab";else{const i=this._cursorMap.get(e);i&&(t.style.cursor=i)}}encodeSvgToCursor(e,t,i){return`url('data:image/svg+xml;base64,${btoa(e)}') ${t} ${i}, auto`}createRectCrossIcon(e,t,i="white"){const n=e/2,s=e+2*t,r=`
2
2
  <svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${s}" viewBox="0 0 ${s} ${s}">
3
3
  <rect x="${t}" y="${t}" width="${e}" height="${e}" fill="none" stroke="${i}" />
4
4
  <line x1="${n+t}" y1="0" x2="${n+t}" y2="${t}" stroke="${i}" />
@@ -6,11 +6,11 @@
6
6
  <line x1="${n+t}" y1="${e+t}" x2="${n+t}" y2="${e+2*t}" stroke="${i}" />
7
7
  <line x1="0" y1="${n+t}" x2="${t}" y2="${n+t}" stroke="${i}" />
8
8
  </svg>
9
- `;return this.encodeSvgToCursor(r,n+t,n+t)}}class Se{constructor(e){this.active=!1,this.isResolvedOrRejected=!1,this.onKeyDown=t=>{t.code==="Escape"&&this.reject("Canceled by user!")},this.view=e}get isActive(){return this.active}activate(){this.isActive&&console.warn("Something wrong here!"),this.active=!0,this.view.canvas.addEventListener("keydown",this.onKeyDown)}deactivate(){this.active=!1,this.view.canvas.removeEventListener("keydown",this.onKeyDown)}resolve(e){this.deactivate(),this._resolve&&!this.isResolvedOrRejected&&(this._resolve(e),this.isResolvedOrRejected=!0)}reject(e){this.deactivate(),this._reject&&!this.isResolvedOrRejected&&(this._reject(e),this.isResolvedOrRejected=!0)}async start(){return this.isResolvedOrRejected=!1,new Promise((e,t)=>{this._resolve=e,this._reject=t,this.activate()})}}class xt extends Se{constructor(e){super(e),this.events={update:new g.AcCmEventManager},this.onMouseMove=t=>{this.curPos.set(t.clientX,t.clientY),this.events.update.dispatch()},this.curPos=new g.AcGePoint2d}activate(){super.activate(),this.view.canvas.addEventListener("mousemove",this.onMouseMove)}deactivate(){super.deactivate(),this.view.canvas.removeEventListener("mousemove",this.onMouseMove)}}class ze{constructor(e){this.onUpdate=()=>{this.update()},this._view=e,this._jigLoop=new xt(e),this._jigLoop.events.update.addEventListener(this.onUpdate)}get view(){return this._view}resolve(e){this._jigLoop.events.update.removeEventListener(this.onUpdate),this._jigLoop.resolve(e)}reject(e){this._jigLoop.events.update.removeEventListener(this.onUpdate),this._jigLoop.reject(e)}async drag(){const e=this._jigLoop.start(),t=this.sampler();await Promise.allSettled([e,t])}async sampler(){}update(){}}const _t=16777215,bt="1px";class wt extends Se{constructor(e){super(e),this.mouseDown=!1,this.mouseMove=!1,this.mouseDownPositionX=-1,this.mouseDownPositionY=-1,this.mousedown=t=>{if(t.button===0){this.mouseDown=!0;const i=new g.AcGePoint2d(t.x,t.y);this.mouseDownPositionX=i.x,this.mouseDownPositionY=i.y}},this.mousemove=t=>{if(!this.mouseDown)return;const i=new g.AcGePoint2d(t.x,t.y);if(this.mouseDownPositionX>=0&&this.mouseDownPositionY>=0&&(Math.abs(i.x-this.mouseDownPositionX)>=5||Math.abs(i.y-this.mouseDownPositionY)>=5)){this.mouseMove=!0;const s=new g.AcGePoint2d(Math.min(this.mouseDownPositionX,i.x),Math.min(this.mouseDownPositionY,i.y)),r=new g.AcGePoint2d(Math.max(this.mouseDownPositionX,i.x),Math.max(this.mouseDownPositionY,i.y));this.drawRect(s,r)}},this.mouseup=t=>{if(this.mouseDown&&this.mouseMove){const i=new g.AcGePoint2d(t.x,t.y),n=new g.AcGePoint2d(Math.min(this.mouseDownPositionX,i.x),Math.min(this.mouseDownPositionY,i.y)),s=new g.AcGePoint2d(Math.max(this.mouseDownPositionX,i.x),Math.max(this.mouseDownPositionY,i.y)),r=new g.AcGeBox2d(n,s);this.resolve(this.toWcs(r))}this.mouseDown=!1,this.mouseMove=!1,this.mouseDownPositionX=-1,this.mouseDownPositionY=-1},this.container=e.canvas,this.color=_t}activate(){super.activate(),this.active=!0,this.container.addEventListener("pointerdown",this.mousedown),this.container.addEventListener("pointermove",this.mousemove),this.container.addEventListener("pointerup",this.mouseup)}deactivate(){super.deactivate(),this.container.removeEventListener("pointerdown",this.mousedown),this.container.removeEventListener("pointermove",this.mousemove),this.container.removeEventListener("pointerup",this.mouseup),this.setRectDomVisible(!1)}reject(e){var t;super.reject(e),(t=this.boxDom)==null||t.remove(),this.boxDom=void 0}drawRect(e,t){if(!this.boxDom){const s=new g.AcCmColor;s.color=this.color,this.boxDom=document.createElement("div"),this.boxDom.style.cssText=`position: absolute;border: ${bt} solid ${s.cssColor};`,document.body.appendChild(this.boxDom)}this.setRectDomVisible(!0),e.x<=0&&(e.x=0),e.y<=0&&(e.y=0),t.x>=this.container.clientWidth-2&&(t.x=this.container.clientWidth-2),t.y>=this.container.clientHeight-2&&(t.y=this.container.clientHeight-2),this.boxDom.style.left=`${e.x}px`,this.boxDom.style.top=`${e.y}px`;const i=Math.abs(t.x-e.x),n=Math.abs(t.y-e.y);this.boxDom.style.width=`${i}px`,this.boxDom.style.height=`${n}px`}setRectDomVisible(e){this.boxDom&&(this.boxDom.style.display=e?"inline-block":"none")}toWcs(e){const t=new g.AcGeBox2d,i=new g.AcGePoint2d(e.min.x,e.min.y),n=new g.AcGePoint2d(e.max.x,e.max.y);return t.expandByPoint(this.view.cwcs2Wcs(i)),t.expandByPoint(this.view.cwcs2Wcs(n)),t}}class vt extends Se{constructor(e){super(e),this.onClick=t=>{this.resolve(this.view.cwcs2Wcs({x:t.clientX,y:t.clientY}))}}activate(){super.activate(),this.view.canvas.addEventListener("click",this.onClick)}deactivate(){super.deactivate(),this.view.canvas.removeEventListener("click",this.onClick)}}class Pe{constructor(e){this._view=e,this._cursorManager=new De}get currentCursor(){return this._currentCursor}restoreCursor(){this._previousCursor!=null&&this.setCursor(this._previousCursor)}setCursor(e){this._cursorManager.setCursor(e,this._view.canvas),this._previousCursor=this._currentCursor,this._currentCursor=e}async getPoint(){return await new vt(this._view).start()}async getSelection(){return await new wt(this._view).start()}}class Oe{constructor(e=[]){this.events={selectionAdded:new g.AcCmEventManager,selectionRemoved:new g.AcCmEventManager},this._ids=new Set(e)}get ids(){return Array.from(this._ids)}get count(){return this._ids.size}add(e){Array.isArray(e)?(e.forEach(t=>this._ids.add(t)),this.events.selectionAdded.dispatch({ids:e})):(this._ids.add(e),this.events.selectionAdded.dispatch({ids:[e]}))}delete(e){Array.isArray(e)?(e.forEach(t=>this._ids.delete(t)),this.events.selectionRemoved.dispatch({ids:e})):(this._ids.delete(e),this.events.selectionRemoved.dispatch({ids:[e]}))}has(e){return this._ids.has(e)}clear(){if(this._ids.size>0){const e=Array.from(this._ids);this._ids.clear(),this.events.selectionRemoved.dispatch({ids:e})}}}var P=(c=>(c[c.SELECTION=0]="SELECTION",c[c.PAN=1]="PAN",c))(P||{});class Ge{constructor(e){this.events={mouseMove:new g.AcCmEventManager,viewResize:new g.AcCmEventManager,hover:new g.AcCmEventManager,unhover:new g.AcCmEventManager},this._canvas=e;const t=e.getBoundingClientRect();this._bbox=new g.AcGeBox3d,this._width=t.width,this._height=t.height,this._curPos=new g.AcGePoint2d,this._curScreenPos=new g.AcGePoint2d,this._selectionSet=new Oe,this._editor=new Pe(this),this._canvas.addEventListener("mousemove",i=>this.onMouseMove(i)),this._canvas.addEventListener("mousedown",i=>{i.button===1&&this._editor.setCursor(j.Grab)}),this._canvas.addEventListener("mouseup",i=>{i.button===1&&this._editor.restoreCursor()}),window.addEventListener("resize",this.onWindowResize.bind(this)),this._selectionBoxSize=4,this._hoverTimer=null,this._pauseTimer=null,this._hoveredObjectId=null}get editor(){return this._editor}get selectionBoxSize(){return this._selectionBoxSize}set selectionBoxSize(e){this._selectionBoxSize=e}setCursor(e){this._editor.setCursor(e)}setCalculateSizeCallback(e){this._calculateSizeCallback=e}get width(){return this._width}set width(e){this._width=e}get height(){return this._height}set height(e){this._height=e}get bbox(){return this._bbox}get canvas(){return this._canvas}get aspect(){return this._width/this._height}get curPos(){return this._curPos}get curScreenPos(){return this._curScreenPos}get selectionSet(){return this._selectionSet}onWindowResize(){if(this._calculateSizeCallback){const{width:e,height:t}=this._calculateSizeCallback();this._width=e,this._height=t}else this._width=this._canvas.clientWidth,this._height=this._canvas.clientHeight;this.events.viewResize.dispatch({width:this._width,height:this._height})}onMouseMove(e){this._curScreenPos=new g.AcGePoint2d(e.clientX,e.clientY);const t=this.cwcs2Wcs(this._curScreenPos);this._curPos.copy(t),this.events.mouseMove.dispatch({x:t.x,y:t.y}),this.mode==0&&this.startHoverTimer(t.x,t.y)}setHoveredObjectId(e){this._hoveredObjectId&&(this.events.unhover.dispatch({id:this._hoveredObjectId,x:this.curScreenPos.x,y:this.curScreenPos.y}),this.onUnhover(this._hoveredObjectId)),this._hoveredObjectId=e,e&&(this.startPauseTimer(e),this.onHover(e))}hoverAt(e,t){const i=this.pick({x:e,y:t});i.length>0?this.setHoveredObjectId(i[0]):(this.setHoveredObjectId(null),this.clearPauseTimer())}clearHoverTimer(){this._hoverTimer&&clearTimeout(this._hoverTimer)}clearPauseTimer(){this._pauseTimer&&clearTimeout(this._pauseTimer)}startHoverTimer(e,t){this.clearHoverTimer(),this._hoverTimer=setTimeout(()=>{this.hoverAt(e,t)},50)}startPauseTimer(e){this._pauseTimer=setTimeout(()=>{this.events.hover.dispatch({id:e,x:this.curScreenPos.x,y:this.curScreenPos.y})},500)}}class Re{constructor(){this._fileName="",this._docTitle="",this._isReadOnly=!0,this._database=new g.AcDbDatabase,this.docTitle="Untitled"}async openUri(e,t){this._uri=e,this._isReadOnly=t&&t.readOnly||!1,this._fileName=this.getFileNameFromUri(e);let i=!0;try{await this._database.openUri(e,t),this.docTitle=this._fileName}catch{i=!1,z.emit("failed-to-open-file",{fileName:e})}return i}async openDocument(e,t,i){var s;let n=!0;this._fileName=e;try{const r=(s=e.split(".").pop())==null?void 0:s.toLocaleLowerCase();await this._database.read(t,i,r=="dwg"?g.AcDbFileType.DWG:g.AcDbFileType.DXF),this.docTitle=this._fileName}catch(r){n=!1,z.emit("failed-to-open-file",{fileName:e}),console.error(r)}return n}get uri(){return this._uri}get database(){return this._database}get docTitle(){return this._docTitle}set docTitle(e){this._docTitle=e,typeof document<"u"&&(document.title=e)}get isReadOnly(){return this._isReadOnly}getFileNameFromUri(e){try{const i=new URL(e).pathname.split("/");return i[i.length-1]||""}catch(t){return console.error("Invalid URI:",t),""}}}class he{constructor(){this._objectId="",this._ownerId="",this._layerName="",this._visible=!0,this._userData={},this._box=new g.AcGeBox2d,this._svg=""}get box(){return this._box}set box(e){this._box.copy(e)}get svg(){return this._svg}set svg(e){this._svg=e}get objectId(){return this._objectId}set objectId(e){this._objectId=e}get ownerId(){return this._ownerId}set ownerId(e){this._ownerId=e}get layerName(){return this._layerName}set layerName(e){this._layerName=e}get visible(){return this._visible}set visible(e){this._visible=e}get userData(){return this._userData}set userData(e){this._userData=e}applyMatrix(e){}recomputeBoundingBox(){}highlight(){}unhighlight(){}fastDeepClone(){return this}}class St extends he{constructor(e){if(super(),e.closed)this.svg=`
9
+ `;return this.encodeSvgToCursor(r,n+t,n+t)}}class Ie{constructor(e){this.active=!1,this.isResolvedOrRejected=!1,this.onKeyDown=t=>{t.code==="Escape"&&this.reject("Canceled by user!")},this.view=e}get isActive(){return this.active}activate(){this.isActive&&console.warn("Something wrong here!"),this.active=!0,this.view.canvas.addEventListener("keydown",this.onKeyDown)}deactivate(){this.active=!1,this.view.canvas.removeEventListener("keydown",this.onKeyDown)}resolve(e){this.deactivate(),this._resolve&&!this.isResolvedOrRejected&&(this._resolve(e),this.isResolvedOrRejected=!0)}reject(e){this.deactivate(),this._reject&&!this.isResolvedOrRejected&&(this._reject(e),this.isResolvedOrRejected=!0)}async start(){return this.isResolvedOrRejected=!1,new Promise((e,t)=>{this._resolve=e,this._reject=t,this.activate()})}}class xt extends Ie{constructor(e){super(e),this.events={update:new g.AcCmEventManager},this.onMouseMove=t=>{this.curPos.set(t.clientX,t.clientY),this.events.update.dispatch()},this.curPos=new g.AcGePoint2d}activate(){super.activate(),this.view.canvas.addEventListener("mousemove",this.onMouseMove)}deactivate(){super.deactivate(),this.view.canvas.removeEventListener("mousemove",this.onMouseMove)}}class ze{constructor(e){this.onUpdate=()=>{this.update()},this._view=e,this._jigLoop=new xt(e),this._jigLoop.events.update.addEventListener(this.onUpdate)}get view(){return this._view}resolve(e){this._jigLoop.events.update.removeEventListener(this.onUpdate),this._jigLoop.resolve(e)}reject(e){this._jigLoop.events.update.removeEventListener(this.onUpdate),this._jigLoop.reject(e)}async drag(){const e=this._jigLoop.start(),t=this.sampler();await Promise.allSettled([e,t])}async sampler(){}update(){}}const _t=16777215,bt="1px";class wt extends Ie{constructor(e){super(e),this.mouseDown=!1,this.mouseMove=!1,this.mouseDownPositionX=-1,this.mouseDownPositionY=-1,this.mousedown=t=>{if(t.button===0){this.mouseDown=!0;const i=new g.AcGePoint2d(t.x,t.y);this.mouseDownPositionX=i.x,this.mouseDownPositionY=i.y}},this.mousemove=t=>{if(!this.mouseDown)return;const i=new g.AcGePoint2d(t.x,t.y);if(this.mouseDownPositionX>=0&&this.mouseDownPositionY>=0&&(Math.abs(i.x-this.mouseDownPositionX)>=5||Math.abs(i.y-this.mouseDownPositionY)>=5)){this.mouseMove=!0;const s=new g.AcGePoint2d(Math.min(this.mouseDownPositionX,i.x),Math.min(this.mouseDownPositionY,i.y)),r=new g.AcGePoint2d(Math.max(this.mouseDownPositionX,i.x),Math.max(this.mouseDownPositionY,i.y));this.drawRect(s,r)}},this.mouseup=t=>{if(this.mouseDown&&this.mouseMove){const i=new g.AcGePoint2d(t.x,t.y),n=new g.AcGePoint2d(Math.min(this.mouseDownPositionX,i.x),Math.min(this.mouseDownPositionY,i.y)),s=new g.AcGePoint2d(Math.max(this.mouseDownPositionX,i.x),Math.max(this.mouseDownPositionY,i.y)),r=new g.AcGeBox2d(n,s);this.resolve(this.toWcs(r))}this.mouseDown=!1,this.mouseMove=!1,this.mouseDownPositionX=-1,this.mouseDownPositionY=-1},this.container=e.canvas,this.color=_t}activate(){super.activate(),this.active=!0,this.container.addEventListener("pointerdown",this.mousedown),this.container.addEventListener("pointermove",this.mousemove),this.container.addEventListener("pointerup",this.mouseup)}deactivate(){super.deactivate(),this.container.removeEventListener("pointerdown",this.mousedown),this.container.removeEventListener("pointermove",this.mousemove),this.container.removeEventListener("pointerup",this.mouseup),this.setRectDomVisible(!1)}reject(e){var t;super.reject(e),(t=this.boxDom)==null||t.remove(),this.boxDom=void 0}drawRect(e,t){if(!this.boxDom){const s=new g.AcCmColor;s.color=this.color,this.boxDom=document.createElement("div"),this.boxDom.style.cssText=`position: absolute;border: ${bt} solid ${s.cssColor};`,document.body.appendChild(this.boxDom)}this.setRectDomVisible(!0),e.x<=0&&(e.x=0),e.y<=0&&(e.y=0),t.x>=this.container.clientWidth-2&&(t.x=this.container.clientWidth-2),t.y>=this.container.clientHeight-2&&(t.y=this.container.clientHeight-2),this.boxDom.style.left=`${e.x}px`,this.boxDom.style.top=`${e.y}px`;const i=Math.abs(t.x-e.x),n=Math.abs(t.y-e.y);this.boxDom.style.width=`${i}px`,this.boxDom.style.height=`${n}px`}setRectDomVisible(e){this.boxDom&&(this.boxDom.style.display=e?"inline-block":"none")}toWcs(e){const t=new g.AcGeBox2d,i=new g.AcGePoint2d(e.min.x,e.min.y),n=new g.AcGePoint2d(e.max.x,e.max.y);return t.expandByPoint(this.view.cwcs2Wcs(i)),t.expandByPoint(this.view.cwcs2Wcs(n)),t}}class vt extends Ie{constructor(e){super(e),this.onClick=t=>{this.resolve(this.view.cwcs2Wcs({x:t.clientX,y:t.clientY}))}}activate(){super.activate(),this.view.canvas.addEventListener("click",this.onClick)}deactivate(){super.deactivate(),this.view.canvas.removeEventListener("click",this.onClick)}}class Pe{constructor(e){this._view=e,this._cursorManager=new De}get currentCursor(){return this._currentCursor}restoreCursor(){this._previousCursor!=null&&this.setCursor(this._previousCursor)}setCursor(e){this._cursorManager.setCursor(e,this._view.canvas),this._previousCursor=this._currentCursor,this._currentCursor=e}async getPoint(){return await new vt(this._view).start()}async getSelection(){return await new wt(this._view).start()}}class Oe{constructor(e=[]){this.events={selectionAdded:new g.AcCmEventManager,selectionRemoved:new g.AcCmEventManager},this._ids=new Set(e)}get ids(){return Array.from(this._ids)}get count(){return this._ids.size}add(e){Array.isArray(e)?(e.forEach(t=>this._ids.add(t)),this.events.selectionAdded.dispatch({ids:e})):(this._ids.add(e),this.events.selectionAdded.dispatch({ids:[e]}))}delete(e){Array.isArray(e)?(e.forEach(t=>this._ids.delete(t)),this.events.selectionRemoved.dispatch({ids:e})):(this._ids.delete(e),this.events.selectionRemoved.dispatch({ids:[e]}))}has(e){return this._ids.has(e)}clear(){if(this._ids.size>0){const e=Array.from(this._ids);this._ids.clear(),this.events.selectionRemoved.dispatch({ids:e})}}}var P=(c=>(c[c.SELECTION=0]="SELECTION",c[c.PAN=1]="PAN",c))(P||{});class Ge{constructor(e){this.events={mouseMove:new g.AcCmEventManager,viewResize:new g.AcCmEventManager,hover:new g.AcCmEventManager,unhover:new g.AcCmEventManager},this._canvas=e;const t=e.getBoundingClientRect();this._bbox=new g.AcGeBox3d,this._width=t.width,this._height=t.height,this._curPos=new g.AcGePoint2d,this._curScreenPos=new g.AcGePoint2d,this._selectionSet=new Oe,this._editor=new Pe(this),this._canvas.addEventListener("mousemove",i=>this.onMouseMove(i)),this._canvas.addEventListener("mousedown",i=>{i.button===1&&this._editor.setCursor(j.Grab)}),this._canvas.addEventListener("mouseup",i=>{i.button===1&&this._editor.restoreCursor()}),window.addEventListener("resize",this.onWindowResize.bind(this)),this._selectionBoxSize=4,this._hoverTimer=null,this._pauseTimer=null,this._hoveredObjectId=null}get editor(){return this._editor}get selectionBoxSize(){return this._selectionBoxSize}set selectionBoxSize(e){this._selectionBoxSize=e}setCursor(e){this._editor.setCursor(e)}setCalculateSizeCallback(e){this._calculateSizeCallback=e}get width(){return this._width}set width(e){this._width=e}get height(){return this._height}set height(e){this._height=e}get bbox(){return this._bbox}get canvas(){return this._canvas}get aspect(){return this._width/this._height}get curPos(){return this._curPos}get curScreenPos(){return this._curScreenPos}get selectionSet(){return this._selectionSet}onWindowResize(){if(this._calculateSizeCallback){const{width:e,height:t}=this._calculateSizeCallback();this._width=e,this._height=t}else this._width=this._canvas.clientWidth,this._height=this._canvas.clientHeight;this.events.viewResize.dispatch({width:this._width,height:this._height})}onMouseMove(e){this._curScreenPos=new g.AcGePoint2d(e.clientX,e.clientY);const t=this.cwcs2Wcs(this._curScreenPos);this._curPos.copy(t),this.events.mouseMove.dispatch({x:t.x,y:t.y}),this.mode==0&&this.startHoverTimer(t.x,t.y)}setHoveredObjectId(e){this._hoveredObjectId&&(this.events.unhover.dispatch({id:this._hoveredObjectId,x:this.curScreenPos.x,y:this.curScreenPos.y}),this.onUnhover(this._hoveredObjectId)),this._hoveredObjectId=e,e&&(this.startPauseTimer(e),this.onHover(e))}hoverAt(e,t){const i=this.pick({x:e,y:t});i.length>0?this.setHoveredObjectId(i[0]):(this.setHoveredObjectId(null),this.clearPauseTimer())}clearHoverTimer(){this._hoverTimer&&clearTimeout(this._hoverTimer)}clearPauseTimer(){this._pauseTimer&&clearTimeout(this._pauseTimer)}startHoverTimer(e,t){this.clearHoverTimer(),this._hoverTimer=setTimeout(()=>{this.hoverAt(e,t)},50)}startPauseTimer(e){this._pauseTimer=setTimeout(()=>{this.events.hover.dispatch({id:e,x:this.curScreenPos.x,y:this.curScreenPos.y})},500)}}class Re{constructor(){this._fileName="",this._docTitle="",this._isReadOnly=!0,this._database=new g.AcDbDatabase,this.docTitle="Untitled"}async openUri(e,t){this._uri=e,this._isReadOnly=t&&t.readOnly||!1,this._fileName=this.getFileNameFromUri(e);let i=!0;try{await this._database.openUri(e,t),this.docTitle=this._fileName}catch{i=!1,z.emit("failed-to-open-file",{fileName:e})}return i}async openDocument(e,t,i){var s;let n=!0;this._fileName=e;try{const r=(s=e.split(".").pop())==null?void 0:s.toLocaleLowerCase();await this._database.read(t,i,r=="dwg"?g.AcDbFileType.DWG:g.AcDbFileType.DXF),this.docTitle=this._fileName}catch(r){n=!1,z.emit("failed-to-open-file",{fileName:e}),console.error(r)}return n}get uri(){return this._uri}get database(){return this._database}get docTitle(){return this._docTitle}set docTitle(e){this._docTitle=e,typeof document<"u"&&(document.title=e)}get isReadOnly(){return this._isReadOnly}getFileNameFromUri(e){try{const i=new URL(e).pathname.split("/");return i[i.length-1]||""}catch(t){return console.error("Invalid URI:",t),""}}}class he{constructor(){this._objectId="",this._ownerId="",this._layerName="",this._visible=!0,this._userData={},this._box=new g.AcGeBox2d,this._svg=""}get box(){return this._box}set box(e){this._box.copy(e)}get svg(){return this._svg}set svg(e){this._svg=e}get objectId(){return this._objectId}set objectId(e){this._objectId=e}get ownerId(){return this._ownerId}set ownerId(e){this._ownerId=e}get layerName(){return this._layerName}set layerName(e){this._layerName=e}get visible(){return this._visible}set visible(e){this._visible=e}get userData(){return this._userData}set userData(e){this._userData=e}applyMatrix(e){}recomputeBoundingBox(){}highlight(){}unhighlight(){}fastDeepClone(){return this}}class St extends he{constructor(e){if(super(),e.closed)this.svg=`
10
10
  <circle cx="${e.center.x}" cy="${e.center.y}" r="${e.radius}"/>`;else{const i=e.startPoint,n=e.endPoint,s=e.clockwise?0:1;this.svg=`
11
11
  <path d="M${i.x},${i.y} A${e.radius},${e.radius} 0 ${e.isLargeArc},${s} ${n.x},${n.y}"/>`}const t=e.box;this._box.min.copy(t.min),this._box.max.copy(t.max)}}class It extends he{constructor(e){if(super(),e.closed)this.svg=`
12
12
  <epllise cx="${e.center.x}" cy="${e.center.y}" rx="${e.majorAxisRadius}" ry="${e.minorAxisRadius}"/>`;else{const i=e.startPoint,n=e.endPoint,s=g.AcGeMathUtil.radToDeg(e.majorAxis.angleTo(g.AcGeVector3d.X_AXIS)),r=e.clockwise?0:1;this.svg=`
13
- <path d="M${i.x},${i.y} A${e.majorAxisRadius},${e.minorAxisRadius} ${s} ${e.isLargeArc},${r} ${n.x},${n.y}"/>`}const t=e.box;this._box.min.copy(t.min),this._box.max.copy(t.max)}}class At extends he{constructor(e){super();const t=e.reduce((i,n,s)=>(i+=s===0?"M":"L",i+=n.x+","+n.y,this.box.expandByPoint(n),i),"");t&&(this.svg=`<path d="${t}" />`)}}class Bt{constructor(){this._container=new Array,this._bbox=new g.AcGeBox2d}setFontMapping(e){}group(e){return k}point(e){return k}circularArc(e){const t=new St(e);return this._container.push(t.svg),this._bbox.union(t.box),t}ellipticalArc(e){const t=new It(e);return this._container.push(t.svg),this._bbox.union(t.box),t}lines(e,t){const i=new At(e);return this._container.push(i.svg),this._bbox.union(i.box),i}lineSegments(e,t,i,n){return k}area(e){return k}mtext(e,t){return k}image(e,t){return k}export(){const e=this._container.join(`
13
+ <path d="M${i.x},${i.y} A${e.majorAxisRadius},${e.minorAxisRadius} ${s} ${e.isLargeArc},${r} ${n.x},${n.y}"/>`}const t=e.box;this._box.min.copy(t.min),this._box.max.copy(t.max)}}class At extends he{constructor(e){super();const t=e.reduce((i,n,s)=>(i+=s===0?"M":"L",i+=n.x+","+n.y,this.box.expandByPoint(n),i),"");t&&(this.svg=`<path d="${t}" />`)}}class Bt{constructor(){this._container=new Array,this._bbox=new g.AcGeBox2d}setFontMapping(e){}group(e){return k}point(e){return k}circularArc(e){const t=new St(e);return this._container.push(t.svg),this._bbox.union(t.box),t}ellipticalArc(e){const t=new It(e);return this._container.push(t.svg),this._bbox.union(t.box),t}lines(e,t){const i=new At(e);return this._container.push(i.svg),this._bbox.union(i.box),i}lineSegments(e,t,i,n){return k}area(e){return k}mtext(e,t,i){return k}image(e,t){return k}export(){const e=this._container.join(`
14
14
  `),t=this._bbox.isEmpty()?{x:0,y:0,width:0,height:0}:{x:this._bbox.min.x,y:-this._bbox.max.y,width:this._bbox.max.x-this._bbox.min.x,height:this._bbox.max.y-this._bbox.min.y};return`<?xml version="1.0"?>
15
15
  <svg
16
16
  xmlns="http://www.w3.org/2000/svg"
@@ -22,8 +22,9 @@
22
22
  <g stroke="#000000" stroke-width="0.1%" fill="none" transform="matrix(1,0,0,-1,0,0)">
23
23
  ${e}
24
24
  </g>
25
- </svg>`}}const k=new he;class Ct{convert(){const e=M.instance.curDocument.database.tables.blockTable.modelSpace.newIterator(),t=new Bt;for(const i of e)i.draw(t);this.createFileAndDownloadIt(t.export())}createFileAndDownloadIt(e){const t=new Blob([e],{type:"image/svg+xml;charset=utf-8"}),i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download="example.svg",document.body.appendChild(n),n.click()}}class Ve extends G{execute(e){new Ct().convert()}}class je extends G{execute(e){z.emit("open-file",{})}}class ke extends G{execute(e){M.instance.openUrl("https://cdn.jsdelivr.net/gh/mlight-lee/cad-data/templates/"+"acadiso.dxf")}}class Fe extends G{execute(e){e.view.mode=P.SELECTION,e.view.setCursor(j.Crosshair)}}class Ne extends G{execute(e){const t=e.doc.database;e.view.zoomTo(new g.AcGeBox2d(t.extmin,t.extmax),1.1)}}class Ue extends ze{constructor(e){super(e)}async sampler(){await M.instance.editor.getSelection().then(e=>this.view.zoomTo(e,1))}}class We extends G{async execute(e){await new Ue(e.view).drag()}}class Xe extends G{execute(e){e.view.mode=P.PAN,e.view.setCursor(j.Grab)}}var B;(function(c){c[c.BeforeStart=0]="BeforeStart",c[c.EqualStart=1]="EqualStart",c[c.BetweenStartAndEnd=2]="BetweenStartAndEnd",c[c.EqualEnd=3]="EqualEnd",c[c.AfterEnd=4]="AfterEnd"})(B||(B={}));class Mt{pointsSame(e,t){return this.pointsSameX(e,t)&&this.pointsSameY(e,t)}pointsCompare(e,t){return this.pointsSameX(e,t)?this.pointsSameY(e,t)?0:e[1]<t[1]?-1:1:e[0]<t[0]?-1:1}}class $e extends Mt{constructor(e=1e-10){super(),this.epsilon=e}pointAboveOrOnLine(e,t,i){const n=t[0],s=t[1],r=i[0],o=i[1],a=e[0],h=e[1];return(r-n)*(h-s)-(o-s)*(a-n)>=-this.epsilon}pointBetween(e,t,i){const n=e[1]-t[1],s=i[0]-t[0],r=e[0]-t[0],o=i[1]-t[1],a=r*s+n*o;if(a<this.epsilon)return!1;const h=s*s+o*o;return!(a-h>-this.epsilon)}pointsSameX(e,t){return Math.abs(e[0]-t[0])<this.epsilon}pointsSameY(e,t){return Math.abs(e[1]-t[1])<this.epsilon}pointsCollinear(e,t,i){const n=e[0]-t[0],s=e[1]-t[1],r=t[0]-i[0],o=t[1]-i[1];return Math.abs(n*o-r*s)<this.epsilon}linesIntersect(e,t,i,n){const s=t[0]-e[0],r=t[1]-e[1],o=n[0]-i[0],a=n[1]-i[1],h=s*a-r*o;if(Math.abs(h)<this.epsilon)return null;const l=e[0]-i[0],m=e[1]-i[1],d=(o*m-a*l)/h,y=(s*m-r*l)/h,p=x=>x<=-this.epsilon?B.BeforeStart:x<this.epsilon?B.EqualStart:x-1<=-this.epsilon?B.BetweenStartAndEnd:x-1<this.epsilon?B.EqualEnd:B.AfterEnd,f=[e[0]+d*s,e[1]+d*r];return{alongA:p(d),alongB:p(y),p:f}}}class Ye{constructor(){this.nodes=[]}remove(e){const t=this.nodes.indexOf(e);t>=0&&this.nodes.splice(t,1)}getIndex(e){return this.nodes.indexOf(e)}isEmpty(){return this.nodes.length<=0}getHead(){return this.nodes[0]}removeHead(){this.nodes.shift()}insertBefore(e,t){this.findTransition(e,t).insert(e)}findTransition(e,t){var i,n;const s=(a,h)=>t(h)-t(a);let r=0,o=this.nodes.length;for(;r<o;){const a=r+o>>1;s(this.nodes[a],e)>0?o=a:r=a+1}return{before:r<=0?null:(i=this.nodes[r-1])!==null&&i!==void 0?i:null,after:(n=this.nodes[r])!==null&&n!==void 0?n:null,insert:a=>(this.nodes.splice(r,0,a),a)}}}class F{constructor(e,t,i,n){var s;this.otherFill=null,this.id=(s=n==null?void 0:n.segmentId())!==null&&s!==void 0?s:-1,this.start=e,this.end=t,this.myFill={above:i?i.myFill.above:null,below:i?i.myFill.below:null}}}class He{constructor(e,t,i,n){this.status=null,this.isStart=e,this.p=t,this.seg=i,this.primary=n}}class qe{constructor(e,t,i=null){this.events=new Ye,this.status=new Ye,this.selfIntersection=e,this.geo=t,this.log=i}compareEvents(e,t,i,n,s,r){const o=this.geo.pointsCompare(t,s);return o!==0?o:this.geo.pointsSame(i,r)?0:e!==n?e?1:-1:this.geo.pointAboveOrOnLine(i,n?s:r,n?r:s)?1:-1}addEvent(e){this.events.insertBefore(e,t=>t===e?0:this.compareEvents(e.isStart,e.p,e.other.p,t.isStart,t.p,t.other.p))}divideEvent(e,t){var i;const n=new F(t,e.seg.end,e.seg,this.log);return(i=this.log)===null||i===void 0||i.segmentChop(e.seg,t),this.events.remove(e.other),e.seg.end=t,e.other.p=t,this.addEvent(e.other),this.addSegment(n,e.primary)}newSegment(e,t){const i=this.geo.pointsCompare(e,t);return i===0?null:i<0?new F(e,t,null,this.log):new F(t,e,null,this.log)}addSegment(e,t){const i=new He(!0,e.start,e,t),n=new He(!1,e.end,e,t);return i.other=n,n.other=i,this.addEvent(i),this.addEvent(n),i}addRegion(e){let t,i=e[e.length-1];for(let n=0;n<e.length;n++){t=i,i=e[n];const s=this.newSegment(t,i);s&&this.addSegment(s,!0)}}compareStatus(e,t){const i=e.seg.start,n=e.seg.end,s=t.seg.start,r=t.seg.end;return this.geo.pointsCollinear(i,s,r)?this.geo.pointsCollinear(n,s,r)||this.geo.pointAboveOrOnLine(n,s,r)?1:-1:this.geo.pointAboveOrOnLine(i,s,r)?1:-1}statusFindSurrounding(e){return this.status.findTransition(e,t=>t===e?0:-this.compareStatus(e,t))}checkIntersection(e,t){var i;const n=e.seg,s=t.seg,r=n.start,o=n.end,a=s.start,h=s.end;(i=this.log)===null||i===void 0||i.checkIntersection(n,s);const l=this.geo.linesIntersect(r,o,a,h);if(l===null){if(!this.geo.pointsCollinear(r,o,a)||this.geo.pointsSame(r,h)||this.geo.pointsSame(o,a))return null;const m=this.geo.pointsSame(r,a),d=this.geo.pointsSame(o,h);if(m&&d)return t;const y=!m&&this.geo.pointBetween(r,a,h),p=!d&&this.geo.pointBetween(o,a,h);if(m)return p?this.divideEvent(t,o):this.divideEvent(e,h),t;y&&(d||(p?this.divideEvent(t,o):this.divideEvent(e,h)),this.divideEvent(t,r))}else l.alongA===B.BetweenStartAndEnd&&(l.alongB===B.EqualStart?this.divideEvent(e,a):l.alongB===B.BetweenStartAndEnd?this.divideEvent(e,l.p):l.alongB===B.EqualEnd&&this.divideEvent(e,h)),l.alongB===B.BetweenStartAndEnd&&(l.alongA===B.EqualStart?this.divideEvent(t,r):l.alongA===B.BetweenStartAndEnd?this.divideEvent(t,l.p):l.alongA===B.EqualEnd&&this.divideEvent(t,o));return null}calculate(e,t){var i,n,s,r,o,a,h,l;const m=[];for(;!this.events.isEmpty();){const d=this.events.getHead();if((i=this.log)===null||i===void 0||i.vert(d.p[0]),d.isStart){(n=this.log)===null||n===void 0||n.segmentNew(d.seg,d.primary);const y=this.statusFindSurrounding(d),p=y.before,f=y.after;(s=this.log)===null||s===void 0||s.tempStatus(d.seg,p?p.seg:!1,f?f.seg:!1);const b=(()=>{if(p){const _=this.checkIntersection(d,p);if(_)return _}return f?this.checkIntersection(d,f):null})();if(b){if(this.selfIntersection){let _;d.seg.myFill.below===null?_=!0:_=d.seg.myFill.above!==d.seg.myFill.below,_&&(b.seg.myFill.above=!b.seg.myFill.above)}else b.seg.otherFill=d.seg.myFill;(r=this.log)===null||r===void 0||r.segmentUpdate(b.seg),this.events.remove(d.other),this.events.remove(d)}if(this.events.getHead()!==d){(o=this.log)===null||o===void 0||o.rewind(d.seg);continue}if(this.selfIntersection){let _;d.seg.myFill.below===null?_=!0:_=d.seg.myFill.above!==d.seg.myFill.below,f?d.seg.myFill.below=f.seg.myFill.above:d.seg.myFill.below=e,_?d.seg.myFill.above=!d.seg.myFill.below:d.seg.myFill.above=d.seg.myFill.below}else if(d.seg.otherFill===null){let _;if(!f)_=d.primary?t:e;else if(d.primary===f.primary){if(f.seg.otherFill===null)throw new Error("otherFill is null");_=f.seg.otherFill.above}else _=f.seg.myFill.above;d.seg.otherFill={above:_,below:_}}(a=this.log)===null||a===void 0||a.status(d.seg,p?p.seg:!1,f?f.seg:!1),d.other.status=y.insert(d)}else{const y=d.status;if(y===null)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");const p=this.status.getIndex(y);if(p>0&&p<this.status.nodes.length-1){const f=this.status.nodes[p-1],x=this.status.nodes[p+1];this.checkIntersection(f,x)}if((h=this.log)===null||h===void 0||h.statusRemove(y.seg),this.status.remove(y),!d.primary){if(!d.seg.otherFill)throw new Error("otherFill is null");const f=d.seg.myFill;d.seg.myFill=d.seg.otherFill,d.seg.otherFill=f}m.push(d.seg)}this.events.removeHead()}return(l=this.log)===null||l===void 0||l.done(),m}}function ee(c,e,t){const i=[];for(const n of c){const s=(n.myFill.above?8:0)+(n.myFill.below?4:0)+(n.otherFill&&n.otherFill.above?2:0)+(n.otherFill&&n.otherFill.below?1:0);if(e[s]!==0){const r=new F(n.start,n.end,null,t);r.myFill.above=e[s]===1,r.myFill.below=e[s]===2,i.push(r)}}return t==null||t.selected(i),i}class te{static union(e,t){return ee(e,[0,2,1,0,2,2,0,0,1,0,1,0,0,0,0,0],t)}static intersect(e,t){return ee(e,[0,0,0,0,0,2,0,2,0,0,1,1,0,2,1,0],t)}static difference(e,t){return ee(e,[0,0,0,0,2,0,2,0,1,1,0,0,0,1,2,0],t)}static differenceRev(e,t){return ee(e,[0,2,1,0,0,0,1,1,0,2,0,2,0,0,0,0],t)}static xor(e,t){return ee(e,[0,2,1,0,2,0,0,1,1,0,0,2,0,1,2,0],t)}}function Et(c,e,t){const i=[],n=[];for(const s of c){let m=function(b,_,S){return l&&(l.index=b,l.matches_head=_,l.matches_pt1=S),l===a?(l=h,!1):(l=null,!0)},d=function(b){t==null||t.chainReverse(b),i[b].reverse()},y=function(b,_){const S=i[b],v=i[_];let A=S[S.length-1];const O=S[S.length-2],I=v[0],J=v[1];e.pointsCollinear(O,A,I)&&(t==null||t.chainRemoveTail(b,A),S.pop(),A=O),e.pointsCollinear(A,I,J)&&(t==null||t.chainRemoveHead(_,I),v.shift()),t==null||t.chainJoin(b,_),i[b]=S.concat(v),i.splice(_,1)};const r=s.start,o=s.end;if(e.pointsSame(r,o)){console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large");continue}t==null||t.chainStart(s);const a={index:0,matches_head:!1,matches_pt1:!1},h={index:0,matches_head:!1,matches_pt1:!1};let l=a;for(let b=0;b<i.length;b++){const _=i[b],S=_[0],v=_[_.length-1];if(e.pointsSame(S,r)){if(m(b,!0,!0))break}else if(e.pointsSame(S,o)){if(m(b,!0,!1))break}else if(e.pointsSame(v,r)){if(m(b,!1,!0))break}else if(e.pointsSame(v,o)&&m(b,!1,!1))break}if(l===a){i.push([r,o]),t==null||t.chainNew(r,o);continue}if(l===h){t==null||t.chainMatch(a.index);const b=a.index,_=a.matches_pt1?o:r,S=a.matches_head,v=i[b];let A=S?v[0]:v[v.length-1];const O=S?v[1]:v[v.length-2],I=S?v[v.length-1]:v[0],J=S?v[v.length-2]:v[1];if(e.pointsCollinear(O,A,_)&&(S?(t==null||t.chainRemoveHead(a.index,_),v.shift()):(t==null||t.chainRemoveTail(a.index,_),v.pop()),A=O),e.pointsSame(I,_)){i.splice(b,1),e.pointsCollinear(J,I,A)&&(S?(t==null||t.chainRemoveTail(a.index,A),v.pop()):(t==null||t.chainRemoveHead(a.index,A),v.shift())),t==null||t.chainClose(a.index),n.push(v);continue}S?(t==null||t.chainAddHead(a.index,_),v.unshift(_)):(t==null||t.chainAddTail(a.index,_),v.push(_));continue}const p=a.index,f=h.index;t==null||t.chainConnect(p,f);const x=i[p].length<i[f].length;a.matches_head?h.matches_head?x?(d(p),y(p,f)):(d(f),y(f,p)):y(f,p):h.matches_head?y(p,f):x?(d(p),y(f,p)):(d(f),y(p,f))}return n}class Lt{constructor(){this.list=[],this.nextSegmentId=0,this.curVert=NaN}push(e,t){this.list.push({type:e,data:JSON.parse(JSON.stringify(t))})}segmentId(){return this.nextSegmentId++}checkIntersection(e,t){this.push("check",{seg1:e,seg2:t})}segmentChop(e,t){this.push("div_seg",{seg:e,p:t}),this.push("chop",{seg:e,p:t})}statusRemove(e){this.push("pop_seg",{seg:e})}segmentUpdate(e){this.push("seg_update",{seg:e})}segmentNew(e,t){this.push("new_seg",{seg:e,primary:t})}tempStatus(e,t,i){this.push("temp_status",{seg:e,above:t,below:i})}rewind(e){this.push("rewind",{seg:e})}status(e,t,i){this.push("status",{seg:e,above:t,below:i})}vert(e){e!==this.curVert&&(this.push("vert",{x:e}),this.curVert=e)}selected(e){this.push("selected",{segs:e})}chainStart(e){this.push("chain_start",{seg:e})}chainRemoveHead(e,t){this.push("chain_rem_head",{index:e,p:t})}chainRemoveTail(e,t){this.push("chain_rem_tail",{index:e,p:t})}chainNew(e,t){this.push("chain_new",{p1:e,p2:t})}chainMatch(e){this.push("chain_match",{index:e})}chainClose(e){this.push("chain_close",{index:e})}chainAddHead(e,t){this.push("chain_add_head",{index:e,p:t})}chainAddTail(e,t){this.push("chain_add_tail",{index:e,p:t})}chainConnect(e,t){this.push("chain_con",{index1:e,index2:t})}chainReverse(e){this.push("chain_rev",{index:e})}chainJoin(e,t){this.push("chain_join",{index1:e,index2:t})}done(){this.push("done",null)}}class Qe{constructor(e){this.log=null,this.geo=e}buildLog(e){var t;return this.log=e?new Lt:null,(t=this.log)===null||t===void 0?void 0:t.list}segments(e){const t=new qe(!0,this.geo,this.log);for(const i of e.regions)t.addRegion(i);return{segments:t.calculate(e.inverted,!1),inverted:e.inverted}}combine(e,t){const i=new qe(!1,this.geo,this.log);for(const n of e.segments)i.addSegment(new F(n.start,n.end,n,this.log),!0);for(const n of t.segments)i.addSegment(new F(n.start,n.end,n,this.log),!1);return{combined:i.calculate(e.inverted,t.inverted),inverted1:e.inverted,inverted2:t.inverted}}selectUnion(e){return{segments:te.union(e.combined,this.log),inverted:e.inverted1||e.inverted2}}selectIntersect(e){return{segments:te.intersect(e.combined,this.log),inverted:e.inverted1&&e.inverted2}}selectDifference(e){return{segments:te.difference(e.combined,this.log),inverted:e.inverted1&&!e.inverted2}}selectDifferenceRev(e){return{segments:te.differenceRev(e.combined,this.log),inverted:!e.inverted1&&e.inverted2}}selectXor(e){return{segments:te.xor(e.combined,this.log),inverted:e.inverted1!==e.inverted2}}polygon(e){return{regions:Et(e.segments,this.geo,this.log),inverted:e.inverted}}union(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectUnion(s);return this.polygon(r)}intersect(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectIntersect(s);return this.polygon(r)}difference(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectDifference(s);return this.polygon(r)}differenceRev(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectDifferenceRev(s);return this.polygon(r)}xor(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectXor(s);return this.polygon(r)}}new Qe(new $e);class le extends u.Object3D{static flattenObject(e){const t=[];function i(s){s.position.set(0,0,0),s.rotation.set(0,0,0),s.scale.set(1,1,1),s.matrix.identity()}function n(s,r){const o=[...s.children];for(const a of o)a.applyMatrix4(r),i(a),a.children.length>0?n(a,a.matrixWorld):t.push(a);s.children=[]}e.updateMatrixWorld(!0),n(e,e.matrixWorld);for(const s of t)"geometry"in s&&(s.geometry.applyMatrix4(s.matrixWorld),s.matrixWorld.identity(),s.matrixWorldNeedsUpdate=!1,e.add(s));i(e),e.matrixWorld.identity(),e.matrixWorldNeedsUpdate=!1}static disposeObject(e,t=!0){t&&e.removeFromParent(),(e instanceof u.Mesh||e instanceof u.Line||e instanceof u.Points)&&e.geometry&&e.geometry.dispose(),(e instanceof u.Mesh||e instanceof u.Line||e instanceof u.Points)&&(Array.isArray(e.material)?e.material:[e.material]).forEach(i=>{var n,s,r,o,a,h,l,m;i.dispose(),(n=i.map)==null||n.dispose(),(s=i.envMap)==null||s.dispose(),(r=i.lightMap)==null||r.dispose(),(o=i.bumpMap)==null||o.dispose(),(a=i.normalMap)==null||a.dispose(),(h=i.roughnessMap)==null||h.dispose(),(l=i.metalnessMap)==null||l.dispose(),(m=i.alphaMap)==null||m.dispose()}),e.children.forEach(i=>this.disposeObject(i)),"geometry"in e&&(e.geometry=null),"material"in e&&(e.material=null),e.children=[]}flatten(){le.flattenObject(this)}dispose(){le.disposeObject(this)}}const L=[.5,0,0,.48429158056431554,-.1243449435824274,0,.4381533400219318,-.24087683705085766,0,.3644843137107058,-.3422735529643443,0,.2679133974894983,-.42216396275100754,0,.15450849718747373,-.47552825814757677,0,.03139525976465676,-.4990133642141358,0,-.09369065729286241,-.4911436253643443,0,-.21288964578253636,-.45241352623300973,0,-.3187119948743449,-.3852566213878946,0,-.40450849718747367,-.2938926261462366,0,-.4648882429441257,-.18406227634233907,0,-.4960573506572389,-.06266661678215227,0,-.49605735065723894,.06266661678215214,0,-.4648882429441256,.18406227634233915,0,-.4045084971874738,.2938926261462365,0,-.31871199487434476,.3852566213878947,0,-.21288964578253608,.4524135262330099,0,-.09369065729286231,.49114362536434436,0,.031395259764656416,.4990133642141358,0,.15450849718747361,.4755282581475768,0,.267913397489498,.42216396275100776,0,.3644843137107056,.3422735529643445,0,.4381533400219318,.24087683705085766,0,.4842915805643155,.12434494358242767,0,.5,0,0],T=[0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25],Tt=new Map([[2,{position:new Float32Array([-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([0,1,2,3])}],[3,{position:new Float32Array([-Math.SQRT1_2,Math.SQRT1_2,0,Math.SQRT1_2,-Math.SQRT1_2,0,-Math.SQRT1_2,-Math.SQRT1_2,0,Math.SQRT1_2,Math.SQRT1_2,0]),indices:new Uint16Array([0,1,2,3])}],[4,{position:new Float32Array([0,0,0,0,.5,0]),indices:new Uint16Array([0,1,2,3])}],[32,{position:new Float32Array(L),indices:new Uint16Array(T)}],[33,{position:new Float32Array(L),indices:new Uint16Array(T)}],[34,{position:new Float32Array([...L,-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([...T,26,27,28,29])}],[35,{position:new Float32Array([...L,-Math.SQRT1_2,Math.SQRT1_2,0,Math.SQRT1_2,-Math.SQRT1_2,0,-Math.SQRT1_2,-Math.SQRT1_2,0,Math.SQRT1_2,Math.SQRT1_2,0]),indices:new Uint16Array([...T,26,27,28,29])}],[36,{position:new Float32Array([...L,0,0,0,0,.5,0]),indices:new Uint16Array([...T,26,27])}],[64,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0]),indices:new Uint16Array([0,1,1,2,2,3,3,4])}],[65,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0]),indices:new Uint16Array([0,1,1,2,2,3,3,4])}],[66,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([0,1,1,2,2,3,3,4,5,6,7,8])}],[67,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-Math.SQRT1_2,Math.SQRT1_2,0,Math.SQRT1_2,-Math.SQRT1_2,0,-Math.SQRT1_2,-Math.SQRT1_2,0,Math.SQRT1_2,Math.SQRT1_2,0]),indices:new Uint16Array([0,1,1,2,2,3,3,0,4,5,6,7])}],[68,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,0,0,0,0,.5,0]),indices:new Uint16Array([0,1,1,2,2,3,3,4,5,6])}],[96,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,26])}],[97,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,30])}],[98,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,30,31,32,33,34])}],[99,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-Math.SQRT1_2,Math.SQRT1_2,0,Math.SQRT1_2,-Math.SQRT1_2,0,-Math.SQRT1_2,-Math.SQRT1_2,0,Math.SQRT1_2,Math.SQRT1_2,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,26,30,31,32,33])}],[100,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,0,0,0,0,.5,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,30,31,32])}]]);class R{constructor(){this._symbols=this.initialize()}static get instance(){return R._instance||(R._instance=new R),R._instance}isShowPoint(e=null){return e==null||e==0||e==32||e==64||e==96}create(e=null,t={x:0,y:0,z:0}){const i={};if(e==null||e==0)ie.copy(t),i.point=new u.BufferGeometry().setFromPoints([ie]);else if(e!=1){const n=this._symbols.get(e);if(n==null)throw new Error(`[AcTrPointSymbolCreator] Invalid point type value: '${e}'!`);ie.copy(t),Ze.identity().makeTranslation(ie),i.line=n.clone().applyMatrix4(Ze),(e==32||e==64||e==96)&&(i.point=new u.BufferGeometry().setFromPoints([ie]))}return i}initialize(){const e=new Map;return Tt.forEach((t,i)=>{const n=new u.BufferGeometry;n.setAttribute("position",new u.BufferAttribute(t.position,3)),n.setIndex(new u.BufferAttribute(t.indices,1)),e.set(i,n)}),e}}const Ze=new u.Matrix4,ie=new u.Vector3,Dt=new u.Color(583902);class ue{static cloneMaterial(e){if(!e)return e;if(Array.isArray(e)){const t=[];return e.forEach(i=>{t.push(i.clone())}),t}return e.clone()}static setMaterialColor(e,t=Dt){if(Array.isArray(e)){e.forEach(i=>this.setMaterialColor(i,t));return}this.hasColorProperty(e)&&(e.color.set(t),this.hasEmissiveProperty(e)&&e.emissive.set(t)),this.hasUniformsProperty(e)&&e.uniforms.u_color&&e.uniforms.u_color.value.set(t)}static hasColorProperty(e){return"color"in e&&e.color instanceof u.Color}static hasEmissiveProperty(e){return"emissive"in e&&e.emissive instanceof u.Color}static hasUniformsProperty(e){return"uniforms"in e&&e.uniforms!==void 0}}class ne{static getExtension(e){return e.substring(e.lastIndexOf(".")+1)}static estimateObjectSize(e){const t=new WeakSet;function i(n){if(n==null)return 0;const s=typeof n;if(s==="boolean")return 4;if(s==="number")return 8;if(s==="string")return n.length*2;if(s==="symbol"||s==="function"||t.has(n))return 0;if(t.add(n),Array.isArray(n))return n.map(i).reduce((r,o)=>r+o,0);if(s==="object"){let r=0;for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r+=o.length*2,r+=i(n[o]));return r}return 0}return i(e)}static getFileName(e){return e.split("/").pop()}static getFileNameWithoutExtension(e){const t=ne.getFileName(e);if(t){const i=t.lastIndexOf(".");return i===-1?t:t.substring(0,i)}return e}}function Ie(c,e){return c-e}function Ae(c,e,t=0){const i=e.itemSize;if(c.isInterleavedBufferAttribute||c.array.constructor!==e.array.constructor){const n=c.count;for(let s=0;s<n;s++)for(let r=0;r<i;r++)e.setComponent(s+t,r,c.getComponent(s,r))}else e.array.set(c.array,t*i);e.needsUpdate=!0}function N(c,e){if(c.constructor!==e.constructor){const t=Math.min(c.length,e.length);for(let i=0;i<t;i++)e[i]=c[i]}else{const t=Math.min(c.length,e.length);e.set(new c.constructor(c.buffer,0,t))}}const Je=new u.Box3,U=new u.Vector3,W=new u.LineSegments,de=[];class zt extends u.LineSegments{constructor(e=1e3,t=e*2,i){super(new u.BufferGeometry,i),this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxVertexCount=e,this._maxIndexCount=t}get geometryCount(){return this._geometryCount}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}get mappingStats(){const e=this._geometryInfo.length;let t=0;return e>0&&(t=ne.estimateObjectSize(this._geometryInfo[0])),{count:e,size:e*t}}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount,n=this._maxIndexCount;if(this._geometryInitialized===!1){for(const s in e.attributes){const r=e.getAttribute(s),{array:o,itemSize:a,normalized:h}=r,l=new o.constructor(i*a),m=new u.BufferAttribute(l,a,h);t.setAttribute(s,m)}if(e.getIndex()!==null){const s=i>65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new u.BufferAttribute(s,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('AcTrBatchedLine: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`AcTrBatchedLine: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),s=t.getAttribute(i);if(n.itemSize!==s.itemSize||n.normalized!==s.normalized)throw new Error("AcTrBatchedLine: All attributes must have a consistent itemSize and normalized value.")}}_resizeSpaceIfNeeded(e){const t=e.getIndex(),i=t!==null;let n=this._maxIndexCount;i&&this.unusedIndexCount<t.count&&(n=(this._maxIndexCount+t.count)*1.5);const s=e.getAttribute("position");let r=this._maxVertexCount;s&&this.unusedVertexCount<s.count&&(r=(this._maxVertexCount+s.count)*1.5),(n>this._maxIndexCount||r>this._maxVertexCount)&&this.setGeometrySize(r,n)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`AcTrBatchedLine: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}reset(){this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._geometryInfo.length=0,this._geometryInitialized=!1,this.geometry.dispose()}getUserData(){const e=[];return this._geometryInfo.forEach(t=>{e.push({position:t.position,objectId:t.objectId,bboxIntersectionCheck:t.bboxIntersectionCheck})}),e}resetGeometry(e){const t=this.getUserData();this.reset();const i=R.instance;t.forEach(n=>{if(n.position){const s=i.create(e,n.position);if(s.line){const r=this.addGeometry(s.line);this.setGeometryInfo(r,n)}}})}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new u.Box3);const e=this.boundingBox,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingBox!=null&&e.union(s.boundingBox)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new u.Sphere);const e=this.boundingSphere,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingSphere!=null&&e.union(s.boundingSphere)}}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e),e.boundingBox==null&&e.computeBoundingBox(),e.boundingSphere==null&&e.computeBoundingSphere(),this._resizeSpaceIfNeeded(e);const n={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:e.boundingBox,boundingSphere:e.boundingSphere,active:!0,visible:!0},s=this._geometryInfo;n.vertexStart=this._nextVertexStart,n.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(n.indexStart=this._nextIndexStart,n.reservedIndexCount=i===-1?r.count:i),n.indexStart!==-1&&n.indexStart+n.reservedIndexCount>this._maxIndexCount||n.vertexStart+n.reservedVertexCount>this._maxVertexCount)throw new Error("AcTrBatchedLine: Reserved space request exceeds the maximum buffer size.");let o;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Ie),o=this._availableGeometryIds.shift(),s[o]=n):(o=this._geometryCount,this._geometryCount++,s.push(n)),this.setGeometryAt(o,e),this._nextIndexStart=n.indexStart+n.reservedIndexCount,this._nextVertexStart=n.vertexStart+n.reservedVertexCount,o}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine: Maximum geometry count reached.");const i=this._geometryInfo[e],n=t.position;n&&(i.position={...n}),i.objectId=t.objectId,i.bboxIntersectionCheck=t.bboxIntersectionCheck}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=i.getIndex()!==null,s=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(n&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("AcTrBatchedLine: Reserved space not large enough for provided geometry.");const a=o.vertexStart,h=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const l in i.attributes){const m=t.getAttribute(l),d=i.getAttribute(l);Ae(m,d,a);const y=m.itemSize;for(let p=m.count,f=h;p<f;p++){const x=a+p;for(let b=0;b<y;b++)d.setComponent(x,b,0)}d.needsUpdate=!0,d.addUpdateRange(a*y,h*y)}if(n&&s){const l=o.indexStart,m=o.reservedIndexCount;o.indexCount=t.getIndex().count;for(let d=0;d<r.count;d++)s.setX(l+d,a+r.getX(d));for(let d=r.count,y=m;d<y;d++)s.setX(l+d,a);s.needsUpdate=!0,s.addUpdateRange(l,o.reservedIndexCount)}return o.start=n?o.indexStart:o.vertexStart,o.count=n?o.indexCount:o.vertexCount,o.boundingBox=null,t.boundingBox!==null&&(o.boundingBox=t.boundingBox.clone()),o.boundingSphere=null,t.boundingSphere!==null&&(o.boundingSphere=t.boundingSphere.clone()),e}deleteGeometry(e){const t=this._geometryInfo;return e>=t.length||t[e].active===!1?this:(t[e].active=!1,this._availableGeometryIds.push(e),this)}optimize(){let e=0,t=0;const i=this._geometryInfo,n=i.map((r,o)=>o).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),s=this.geometry;for(let r=0,o=i.length;r<o;r++){const a=n[r],h=i[a];if(h.active!==!1){if(s.index!==null){if(h.indexStart!==t){const{indexStart:l,vertexStart:m,reservedIndexCount:d}=h,y=s.index,p=y.array,f=e-m;for(let x=l;x<l+d;x++)p[x]=p[x]+f;y.array.copyWithin(t,l,l+d),y.addUpdateRange(t,d),h.indexStart=t}t+=h.reservedIndexCount}if(h.vertexStart!==e){const{vertexStart:l,reservedVertexCount:m}=h,d=s.attributes;for(const y in d){const p=d[y],{array:f,itemSize:x}=p;f.copyWithin(e*x,l*x,(l+m)*x),p.addUpdateRange(e*x,m*x)}h.vertexStart=e}e+=h.reservedVertexCount,h.start=s.index?h.indexStart:h.vertexStart,this._nextIndexStart=s.index?h.indexStart+h.reservedIndexCount:0,this._nextVertexStart=h.vertexStart+h.reservedVertexCount}}return this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingBox===null){const s=new u.Box3,r=i.index,o=i.attributes.position;for(let a=n.start,h=n.start+n.count;a<h;a++){let l=a;r&&(l=r.getX(l)),s.expandByPoint(U.fromBufferAttribute(o,l))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingSphere===null){const s=new u.Sphere;this.getBoundingBoxAt(e,Je),Je.getCenter(s.center);const r=i.index,o=i.attributes.position;let a=0;for(let h=n.start,l=n.start+n.count;h<l;h++){let m=h;r&&(m=r.getX(m)),U.fromBufferAttribute(o,m),a=Math.max(a,s.center.distanceToSquared(U))}s.radius=Math.sqrt(a),n.boundingSphere=s}return t.copy(n.boundingSphere),t}setVisibleAt(e,t){return this.validateGeometryId(e),this._geometryInfo[e].visible===t?this:(this._geometryInfo[e].visible=t,this)}getVisibleAt(e){return this.validateGeometryId(e),this._geometryInfo[e].visible}getGeometryAt(e){return this.validateGeometryId(e),this._geometryInfo[e]}setGeometrySize(e,t){const i=this.geometry;i.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new u.BufferGeometry,this._initializeGeometry(i));const n=this.geometry;i.index&&N(i.index.array,n.index.array);for(const s in i.attributes)N(i.attributes[s].array,n.attributes[s].array)}getObjectAt(e){const t=new u.LineSegments;this._initializeRaycastObject(t);const i=this._geometryInfo[e];return this._setRaycastObjectInfo(t,e,i.start,i.count),t}_initializeRaycastObject(e){const t=this.geometry;return e.material=this.material,e.geometry.index=t.index,e.geometry.attributes=t.attributes,e.geometry.boundingBox===null&&(e.geometry.boundingBox=new u.Box3),e.geometry.boundingSphere===null&&(e.geometry.boundingSphere=new u.Sphere),e}_setRaycastObjectInfo(e,t,i,n){e.geometry.setDrawRange(i,n),this.getBoundingBoxAt(t,e.geometry.boundingBox),this.getBoundingSphereAt(t,e.geometry.boundingSphere)}_resetRaycastObjectInfo(e){e.geometry.index=null,e.geometry.attributes={},e.geometry.setDrawRange(0,1/0)}intersectWith(e,t,i){this._initializeRaycastObject(W),this._intersectWith(e,t,i),this._resetRaycastObjectInfo(W)}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!(!n.visible||!n.active))if(n.bboxIntersectionCheck){const s=n.boundingBox;if(t.ray.intersectBox(s,U)){const r=t.ray.origin.distanceTo(U);i.push({distance:r,point:U.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}}else{this._setRaycastObjectInfo(W,e,n.start,n.count),W.raycast(t,de);for(let s=0,r=de.length;s<r;s++){const o=de[s];o.object=this,o.batchId=e,o.objectId=n.objectId,i.push(o)}de.length=0}}raycast(e,t){const i=this._geometryInfo;this._initializeRaycastObject(W);for(let n=0,s=i.length;n<s;n++)this._intersectWith(n,e,t);this._resetRaycastObjectInfo(W)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this}dispose(){return this.geometry.dispose(),this}}const Ke=new u.Box3,X=new u.Vector3,$=new u.Mesh,me=[];class Pt extends u.Mesh{constructor(e=1e3,t=e*2,i){super(new u.BufferGeometry,i),this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxVertexCount=e,this._maxIndexCount=t}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}get mappingStats(){const e=this._geometryInfo.length;let t=0;return e>0&&(t=ne.estimateObjectSize(this._geometryInfo[0])),{count:e,size:e*t}}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount,n=this._maxIndexCount;if(this._geometryInitialized===!1){for(const s in e.attributes){const r=e.getAttribute(s),{array:o,itemSize:a,normalized:h}=r,l=new o.constructor(i*a),m=new u.BufferAttribute(l,a,h);t.setAttribute(s,m)}if(e.getIndex()!==null){const s=i>65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new u.BufferAttribute(s,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('AcTrBatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`AcTrBatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),s=t.getAttribute(i);if(n.itemSize!==s.itemSize||n.normalized!==s.normalized)throw new Error("AcTrBatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}_resizeSpaceIfNeeded(e){const t=e.getIndex(),i=t!==null;let n=this._maxIndexCount;i&&this.unusedIndexCount<t.count&&(n=(this._maxIndexCount+t.count)*1.5);const s=e.getAttribute("position");let r=this._maxVertexCount;s&&this.unusedVertexCount<s.count&&(r=(this._maxVertexCount+s.count)*1.5),(n>this._maxIndexCount||r>this._maxVertexCount)&&this.setGeometrySize(r,n)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`AcTrBatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new u.Box3);const e=this.boundingBox,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingBox!=null&&e.union(s.boundingBox)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new u.Sphere);const e=this.boundingSphere,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingSphere!=null&&e.union(s.boundingSphere)}}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e),e.boundingBox==null&&e.computeBoundingBox(),e.boundingSphere==null&&e.computeBoundingSphere(),this._resizeSpaceIfNeeded(e);const n={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:e.boundingBox,boundingSphere:e.boundingSphere,active:!0,visible:!0},s=this._geometryInfo;n.vertexStart=this._nextVertexStart,n.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(n.indexStart=this._nextIndexStart,n.reservedIndexCount=i===-1?r.count:i),n.indexStart!==-1&&n.indexStart+n.reservedIndexCount>this._maxIndexCount||n.vertexStart+n.reservedVertexCount>this._maxVertexCount)throw new Error("AcTrBatchedMesh: Reserved space request exceeds the maximum buffer size.");let o;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Ie),o=this._availableGeometryIds.shift(),s[o]=n):(o=this._geometryCount,this._geometryCount++,s.push(n)),this.setGeometryAt(o,e),this._nextIndexStart=n.indexStart+n.reservedIndexCount,this._nextVertexStart=n.vertexStart+n.reservedVertexCount,o}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedMesh: Maximum geometry count reached.");const i=this._geometryInfo[e];i.objectId=t.objectId,i.bboxIntersectionCheck=t.bboxIntersectionCheck}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=i.getIndex()!==null,s=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(n&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("AcTrBatchedMesh: Reserved space not large enough for provided geometry.");const a=o.vertexStart,h=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const l in i.attributes){const m=t.getAttribute(l),d=i.getAttribute(l);Ae(m,d,a);const y=m.itemSize;for(let p=m.count,f=h;p<f;p++){const x=a+p;for(let b=0;b<y;b++)d.setComponent(x,b,0)}d.needsUpdate=!0,d.addUpdateRange(a*y,h*y)}if(n&&s){const l=o.indexStart,m=o.reservedIndexCount;o.indexCount=t.getIndex().count;for(let d=0;d<r.count;d++)s.setX(l+d,a+r.getX(d));for(let d=r.count,y=m;d<y;d++)s.setX(l+d,a);s.needsUpdate=!0,s.addUpdateRange(l,o.reservedIndexCount)}return o.start=n?o.indexStart:o.vertexStart,o.count=n?o.indexCount:o.vertexCount,o.boundingBox=null,t.boundingBox!==null&&(o.boundingBox=t.boundingBox.clone()),o.boundingSphere=null,t.boundingSphere!==null&&(o.boundingSphere=t.boundingSphere.clone()),e}deleteGeometry(e){const t=this._geometryInfo;return e>=t.length||t[e].active===!1?this:(t[e].active=!1,this._availableGeometryIds.push(e),this)}optimize(){let e=0,t=0;const i=this._geometryInfo,n=i.map((r,o)=>o).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),s=this.geometry;for(let r=0,o=i.length;r<o;r++){const a=n[r],h=i[a];if(h.active!==!1){if(s.index!==null){if(h.indexStart!==t){const{indexStart:l,vertexStart:m,reservedIndexCount:d}=h,y=s.index,p=y.array,f=e-m;for(let x=l;x<l+d;x++)p[x]=p[x]+f;y.array.copyWithin(t,l,l+d),y.addUpdateRange(t,d),h.indexStart=t}t+=h.reservedIndexCount}if(h.vertexStart!==e){const{vertexStart:l,reservedVertexCount:m}=h,d=s.attributes;for(const y in d){const p=d[y],{array:f,itemSize:x}=p;f.copyWithin(e*x,l*x,(l+m)*x),p.addUpdateRange(e*x,m*x)}h.vertexStart=e}e+=h.reservedVertexCount,h.start=s.index?h.indexStart:h.vertexStart,this._nextIndexStart=s.index?h.indexStart+h.reservedIndexCount:0,this._nextVertexStart=h.vertexStart+h.reservedVertexCount}}return this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingBox===null){const s=new u.Box3,r=i.index,o=i.attributes.position;for(let a=n.start,h=n.start+n.count;a<h;a++){let l=a;r&&(l=r.getX(l)),s.expandByPoint(X.fromBufferAttribute(o,l))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingSphere===null){const s=new u.Sphere;this.getBoundingBoxAt(e,Ke),Ke.getCenter(s.center);const r=i.index,o=i.attributes.position;let a=0;for(let h=n.start,l=n.start+n.count;h<l;h++){let m=h;r&&(m=r.getX(m)),X.fromBufferAttribute(o,m),a=Math.max(a,s.center.distanceToSquared(X))}s.radius=Math.sqrt(a),n.boundingSphere=s}return t.copy(n.boundingSphere),t}setVisibleAt(e,t){return this.validateGeometryId(e),this._geometryInfo[e].visible===t?this:(this._geometryInfo[e].visible=t,this)}getVisibleAt(e){return this.validateGeometryId(e),this._geometryInfo[e].visible}getGeometryRangeAt(e){return this.validateGeometryId(e),this._geometryInfo[e]}setGeometrySize(e,t){const i=this.geometry;i.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new u.BufferGeometry,this._initializeGeometry(i));const n=this.geometry;i.index&&N(i.index.array,n.index.array);for(const s in i.attributes)N(i.attributes[s].array,n.attributes[s].array)}getObjectAt(e){const t=new u.Mesh;this._initializeRaycastObject(t);const i=this._geometryInfo[e];return this._setRaycastObjectInfo(t,e,i.start,i.count),t}_initializeRaycastObject(e){const t=this.geometry;return e.material=this.material,e.geometry.index=t.index,e.geometry.attributes=t.attributes,e.geometry.boundingBox===null&&(e.geometry.boundingBox=new u.Box3),e.geometry.boundingSphere===null&&(e.geometry.boundingSphere=new u.Sphere),e}_setRaycastObjectInfo(e,t,i,n){e.geometry.setDrawRange(i,n),this.getBoundingBoxAt(t,e.geometry.boundingBox),this.getBoundingSphereAt(t,e.geometry.boundingSphere)}_resetRaycastObjectInfo(e){e.geometry.index=null,e.geometry.attributes={},e.geometry.setDrawRange(0,1/0)}intersectWith(e,t,i){this._initializeRaycastObject($),this._intersectWith(e,t,i),this._resetRaycastObjectInfo($)}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!(!n.visible||!n.active))if(n.bboxIntersectionCheck){const s=n.boundingBox;if(t.ray.intersectBox(s,X)){const r=t.ray.origin.distanceTo(X);i.push({distance:r,point:X.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}}else{this._setRaycastObjectInfo($,e,n.start,n.count),$.raycast(t,me);for(let s=0,r=me.length;s<r;s++){const o=me[s];o.object=this,o.batchId=e,o.objectId=n.objectId,i.push(o)}me.length=0}}raycast(e,t){const i=this._geometryInfo;this._initializeRaycastObject($);for(let n=0,s=i.length;n<s;n++)this._intersectWith(n,e,t);this._resetRaycastObjectInfo($)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this}dispose(){return this.geometry.dispose(),this}}const et=new u.Box3,Y=new u.Vector3,H=new u.Points,ge=[];class Ot extends u.Points{constructor(e=1e3,t){super(new u.BufferGeometry,t),this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextVertexStart=0,this._geometryCount=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxVertexCount=e}get geometryCount(){return this._geometryCount}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get mappingStats(){const e=this._geometryInfo.length;let t=0;return e>0&&(t=ne.estimateObjectSize(this._geometryInfo[0])),{count:e,size:e*t}}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount;if(this._geometryInitialized===!1){for(const n in e.attributes){const s=e.getAttribute(n),{array:r,itemSize:o,normalized:a}=s,h=new r.constructor(i*o),l=new u.BufferAttribute(h,o,a);t.setAttribute(n,l)}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`AcTrBatchedLine: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),s=t.getAttribute(i);if(n.itemSize!==s.itemSize||n.normalized!==s.normalized)throw new Error("AcTrBatchedLine: All attributes must have a consistent itemSize and normalized value.")}}_resizeSpaceIfNeeded(e){const t=e.getAttribute("position");let i=this._maxVertexCount;t&&this.unusedVertexCount<t.count&&(i=(this._maxVertexCount+t.count)*1.5),i>this._maxVertexCount&&this.setGeometrySize(i)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`AcTrBatchedLine: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}reset(){this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextVertexStart=0,this._geometryCount=0,this._geometryInfo.length=0,this._geometryInitialized=!1,this.geometry.dispose()}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new u.Box3);const e=this.boundingBox,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingBox!=null&&e.union(s.boundingBox)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new u.Sphere);const e=this.boundingSphere,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingSphere!=null&&e.union(s.boundingSphere)}}addGeometry(e,t=-1){this._initializeGeometry(e),this._validateGeometry(e),e.boundingBox==null&&e.computeBoundingBox(),e.boundingSphere==null&&e.computeBoundingSphere(),this._resizeSpaceIfNeeded(e);const i={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,boundingBox:e.boundingBox,boundingSphere:e.boundingSphere,active:!0,visible:!0},n=this._geometryInfo;i.vertexStart=this._nextVertexStart,i.reservedVertexCount=t===-1?e.getAttribute("position").count:t;let s;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Ie),s=this._availableGeometryIds.shift(),n[s]=i):(s=this._geometryCount,this._geometryCount++,n.push(i)),this.setGeometryAt(s,e),this._nextVertexStart=i.vertexStart+i.reservedVertexCount,this.geometry.setDrawRange(0,this._nextVertexStart),s}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine: Maximum geometry count reached.");const i=this._geometryInfo[e],n=t.position;n&&(i.position={...n}),i.objectId=t.objectId,i.bboxIntersectionCheck=t.bboxIntersectionCheck}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=this._geometryInfo[e],s=n.vertexStart,r=n.reservedVertexCount;n.vertexCount=t.getAttribute("position").count;for(const o in i.attributes){const a=t.getAttribute(o),h=i.getAttribute(o);Ae(a,h,s);const l=a.itemSize;for(let m=a.count,d=r;m<d;m++){const y=s+m;for(let p=0;p<l;p++)h.setComponent(y,p,0)}h.needsUpdate=!0,h.addUpdateRange(s*l,r*l)}return n.boundingBox=null,t.boundingBox!==null&&(n.boundingBox=t.boundingBox.clone()),n.boundingSphere=null,t.boundingSphere!==null&&(n.boundingSphere=t.boundingSphere.clone()),e}deleteGeometry(e){const t=this._geometryInfo;return e>=t.length||t[e].active===!1?this:(t[e].active=!1,this._availableGeometryIds.push(e),this)}optimize(){let e=0;const t=this._geometryInfo,i=t.map((s,r)=>r).sort((s,r)=>t[s].vertexStart-t[r].vertexStart),n=this.geometry;for(let s=0,r=t.length;s<r;s++){const o=i[s],a=t[o];if(a.active!==!1){if(a.vertexStart!==e){const{vertexStart:h,reservedVertexCount:l}=a,m=n.attributes;for(const d in m){const y=m[d],{array:p,itemSize:f}=y;p.copyWithin(e*f,h*f,(h+l)*f),y.addUpdateRange(e*f,l*f)}a.vertexStart=e}e+=a.reservedVertexCount,this._nextVertexStart=a.vertexStart+a.reservedVertexCount}}return this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingBox===null){const s=new u.Box3,r=i.index,o=i.attributes.position;for(let a=n.vertexStart,h=n.vertexStart+n.vertexCount;a<h;a++){let l=a;r&&(l=r.getX(l)),s.expandByPoint(Y.fromBufferAttribute(o,l))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingSphere===null){const s=new u.Sphere;this.getBoundingBoxAt(e,et),et.getCenter(s.center);const r=i.index,o=i.attributes.position;let a=0;for(let h=n.vertexStart,l=n.vertexStart+n.vertexCount;h<l;h++){let m=h;r&&(m=r.getX(m)),Y.fromBufferAttribute(o,m),a=Math.max(a,s.center.distanceToSquared(Y))}s.radius=Math.sqrt(a),n.boundingSphere=s}return t.copy(n.boundingSphere),t}setVisibleAt(e,t){return this.validateGeometryId(e),this._geometryInfo[e].visible===t?this:(this._geometryInfo[e].visible=t,this)}getVisibleAt(e){return this.validateGeometryId(e),this._geometryInfo[e].visible}getGeometryAt(e){return this.validateGeometryId(e),this._geometryInfo[e]}setGeometrySize(e){const t=this.geometry;t.dispose(),this._maxVertexCount=e,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new u.BufferGeometry,this._initializeGeometry(t));const i=this.geometry;t.index&&N(t.index.array,i.index.array);for(const n in t.attributes)N(t.attributes[n].array,i.attributes[n].array)}getObjectAt(e){const t=new u.Points;this._initializeRaycastObject(t);const i=this._geometryInfo[e];return this._setRaycastObjectInfo(t,e,i.vertexStart,i.vertexCount),t}_initializeRaycastObject(e){const t=this.geometry;return e.material=this.material,e.geometry.index=t.index,e.geometry.attributes=t.attributes,e.geometry.boundingBox===null&&(e.geometry.boundingBox=new u.Box3),e.geometry.boundingSphere===null&&(e.geometry.boundingSphere=new u.Sphere),e}_setRaycastObjectInfo(e,t,i,n){e.geometry.setDrawRange(i,n),this.getBoundingBoxAt(t,e.geometry.boundingBox),this.getBoundingSphereAt(t,e.geometry.boundingSphere)}_resetRaycastObjectInfo(e){e.geometry.index=null,e.geometry.attributes={},e.geometry.setDrawRange(0,1/0)}intersectWith(e,t,i){this._initializeRaycastObject(H),this._intersectWith(e,t,i),this._resetRaycastObjectInfo(H)}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!(!n.visible||!n.active))if(n.bboxIntersectionCheck){const s=n.boundingBox;if(t.ray.intersectBox(s,Y)){const r=t.ray.origin.distanceTo(Y);i.push({distance:r,point:Y.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}}else{this._setRaycastObjectInfo(H,e,n.vertexStart,n.vertexCount),H.raycast(t,ge);for(let s=0,r=ge.length;s<r;s++){const o=ge[s];o.object=this,o.batchId=e,o.objectId=n.objectId,i.push(o)}ge.length=0}}raycast(e,t){const i=this._geometryInfo;this._initializeRaycastObject(H);for(let n=0,s=i.length;n<s;n++)this._intersectWith(n,e,t);this._resetRaycastObjectInfo(H)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._maxVertexCount=e._maxVertexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this}dispose(){return this.geometry.dispose(),this}}class Gt extends u.Group{constructor(){super(),this._pointBatches=new Map,this._pointSymbolBatches=new Map,this._lineBatches=new Map,this._lineWithIndexBatches=new Map,this._meshBatches=new Map,this._meshWithIndexBatches=new Map,this._entitiesMap=new Map,this._selectedObjects=new u.Group,this._hoverObjects=new u.Group,this.add(this._selectedObjects),this.add(this._hoverObjects)}get entityCount(){return this._entitiesMap.size}get stats(){const e={summary:{entityCount:this._entitiesMap.size,totalGeometrySize:0,totalMappingSize:0},mesh:{indexed:{count:this._meshWithIndexBatches.size,geometrySize:this.getBatchedGeometrySize(this._meshWithIndexBatches),mappingSize:this.getBatchedGeometryMappingSize(this._meshWithIndexBatches)},nonIndexed:{count:this._meshBatches.size,geometrySize:this.getBatchedGeometrySize(this._meshBatches),mappingSize:this.getBatchedGeometryMappingSize(this._meshBatches)}},line:{indexed:{count:this._lineWithIndexBatches.size,geometrySize:this.getBatchedGeometrySize(this._lineWithIndexBatches),mappingSize:this.getBatchedGeometryMappingSize(this._lineWithIndexBatches)},nonIndexed:{count:this._lineBatches.size,geometrySize:this.getBatchedGeometrySize(this._lineBatches),mappingSize:this.getBatchedGeometryMappingSize(this._lineBatches)}},point:{indexed:{count:this._pointSymbolBatches.size,geometrySize:this.getBatchedGeometrySize(this._pointSymbolBatches),mappingSize:this.getBatchedGeometryMappingSize(this._pointSymbolBatches)},nonIndexed:{count:this._pointBatches.size,geometrySize:this.getBatchedGeometrySize(this._pointBatches),mappingSize:this.getBatchedGeometryMappingSize(this._pointBatches)}}};return e.summary.totalGeometrySize=e.line.indexed.geometrySize+e.line.nonIndexed.geometrySize+e.mesh.indexed.geometrySize+e.mesh.nonIndexed.geometrySize+e.point.indexed.geometrySize+e.point.nonIndexed.geometrySize,e.summary.totalMappingSize=e.line.indexed.mappingSize+e.line.nonIndexed.mappingSize+e.mesh.indexed.mappingSize+e.mesh.nonIndexed.mappingSize+e.point.indexed.mappingSize+e.point.nonIndexed.mappingSize,e}rerenderPoints(e){const t=R.instance.create(e);t.line&&this._pointSymbolBatches.forEach(n=>{n.resetGeometry(e)});const i=t.point!=null;this._pointBatches.forEach(n=>{n.visible=i})}clear(){return this.clearPoint(),this.clearLine(),this.clearMesh(),this}clearPoint(){this.clearBatch(this._pointBatches),this.clearBatch(this._pointSymbolBatches)}clearLine(){this.clearBatch(this._lineBatches),this.clearBatch(this._lineWithIndexBatches)}clearMesh(){this.clearBatch(this._meshBatches),this.clearBatch(this._meshWithIndexBatches)}hasEntity(e){return this._entitiesMap.has(e)}addEntity(e){const t=[];this._entitiesMap.set(e.objectId,t),e.updateMatrixWorld(!0),e.traverse(i=>{const n=!!i.userData.bboxIntersectionCheck;i instanceof u.LineSegments?t.push(this.addLine(i,{position:i.userData.position,objectId:e.objectId,bboxIntersectionCheck:n})):i instanceof u.Mesh?t.push(this.addMesh(i,{objectId:e.objectId,bboxIntersectionCheck:n})):i instanceof u.Points&&t.push(this.addPoint(i,{objectId:e.objectId,bboxIntersectionCheck:n}))})}isIntersectWith(e,t){const i=this._entitiesMap.get(e);if(i){const n=[];for(let s=0,r=i.length;s<r;s++){const o=i[s];if(this.getObjectById(o.batchedObjectId).intersectWith(o.batchId,t,n),n.length>0)return!0}}return!1}hover(e){this.highlight(e,this._hoverObjects)}unhover(e){this.unhighlight(e,this._hoverObjects)}select(e){this.highlight(e,this._selectedObjects)}unselect(e){this.unhighlight(e,this._selectedObjects)}highlight(e,t){const i=this._entitiesMap.get(e);i&&i.forEach(n=>{const s=this.getObjectById(n.batchedObjectId).getObjectAt(n.batchId),r=ue.cloneMaterial(s.material);ue.setMaterialColor(r),s.material=r,s.userData.objectId=e,t.add(s)})}unhighlight(e,t){const i=[];t.children.forEach(n=>{n.userData.objectId===e&&i.push(n)}),t.remove(...i)}addLine(e,t){const i=e.material,n=this.getMatchedLineBatches(e);let s=n.get(i.id);s==null&&(s=new zt(1e3,2e3,i),n.set(i.id,s),this.add(s)),e.geometry.applyMatrix4(e.matrixWorld);const r=s.addGeometry(e.geometry);return s.setGeometryInfo(r,t),{batchedObjectId:s.id,batchId:r}}addMesh(e,t){const i=e.material,n=this.getMatchedMeshBatches(e);let s=n.get(i.id);s==null&&(s=new Pt(1e3,2e3,i),n.set(i.id,s),this.add(s)),e.geometry.applyMatrix4(e.matrixWorld);const r=s.addGeometry(e.geometry);return s.setGeometryInfo(r,t),{batchedObjectId:s.id,batchId:r}}addPoint(e,t){const i=e.material;let n=this._pointBatches.get(i.id);n==null&&(n=new Ot(100,i),n.visible=e.visible,this._pointBatches.set(i.id,n),this.add(n)),e.geometry.applyMatrix4(e.matrixWorld);const s=n.addGeometry(e.geometry);return n.setGeometryInfo(s,t),{batchedObjectId:n.id,batchId:s}}getMatchedLineBatches(e){if(e.userData.isPoint)return this._pointSymbolBatches;{const t=e.geometry.getIndex()!==null;let i=this._lineBatches;return t&&(i=this._lineWithIndexBatches),i}}getMatchedMeshBatches(e){const t=e.geometry.getIndex()!==null;let i=this._meshBatches;return t&&(i=this._meshWithIndexBatches),i}clearBatch(e){e.forEach(t=>{t.dispose()}),e.clear()}getBatchedGeometrySize(e){let t=0;return e.forEach(i=>{t+=this.getGeometrySize(i)}),t}getBatchedGeometryMappingSize(e){let t=0;return e.forEach(i=>{t+=i.mappingStats.size}),t}getGeometrySize(e){let t=0;if("geometry"in e){const i=e.geometry;i.attributes.position&&(t+=i.attributes.position.array.byteLength),i.attributes.normal&&(t+=i.attributes.normal.array.byteLength),i.attributes.uv&&(t+=i.attributes.uv.array.byteLength),i.index&&(t+=i.index.array.byteLength)}return t}}class tt extends le{constructor(e){super(),this._styleManager=e}get styleManager(){return this._styleManager}copy(e,t){return this._styleManager=e._styleManager,super.copy(e,t)}}class E extends tt{constructor(e){super(e),this._objectId="",this._ownerId="",this._layerName="",this._box=new u.Box3}get box(){return this._box}set box(e){this._box.copy(e)}get objectId(){return this._objectId}set objectId(e){this._objectId=e}get ownerId(){return this._ownerId}set ownerId(e){this._ownerId=e}get layerName(){return this._layerName}set layerName(e){this._layerName=e}async draw(){}applyMatrix(e){const t=e.elements,i=new u.Matrix4(t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13],t[2],t[6],t[10],t[14],t[3],t[7],t[11],t[15]);this.applyMatrix4(i),this.updateMatrixWorld(!0),this._box.applyMatrix4(i)}highlight(){this.highlightObject(this)}highlightObject(e){if("material"in e){const t=e.material;if(e.userData.originalMaterial==null){const i=ue.cloneMaterial(t);ue.setMaterialColor(i),e.userData.originalMaterial=e.material,e.material=i}}else e.children.length>0&&e.children.forEach(t=>{this.highlightObject(t)})}unhighlight(){this.unhighlightObject(this)}fastDeepClone(){const e=new E(this.styleManager);return e.copy(this,!1),this.copyGeometry(this,e),e}copy(e,t){return this.objectId=e.objectId,this.ownerId=e.ownerId,this.layerName=e.layerName,this.box=e.box,super.copy(e,t)}copyGeometry(e,t){for(let i=0;i<e.children.length;i++){const n=e.children[i].clone(!1);"geometry"in n&&(n.geometry=n.geometry.clone()),t.add(n)}}unhighlightObject(e){if("material"in e){const t=e.material;e.material=e.userData.originalMaterial,delete e.userData.originalMaterial,Array.isArray(t)?t.forEach(i=>i.dispose()):t instanceof u.Material&&t.dispose()}else e.children.length>0&&e.children.forEach(t=>{this.unhighlightObject(t)})}createColorArray(e,t){const i=(e>>16&255)/256,n=(e>>8&255)/256,s=(e&255)/256,r=new Float32Array(t*3);for(let o=0,a=0;o<t;o++)r[a]=i,r[a+1]=n,r[a+2]=s,a+=3;return r}}const it=class K{constructor(){}static getInstance(){return K._instance||(K._instance=new K),K._instance}async renderMText(e,t,i={byLayerColor:16777215,byBlockColor:16777215}){if(!this._renderer)throw new Error("AcTrMTextRenderer not initialized!");return await this._renderer.renderMText(e,t,i)}initialize(e){this._renderer=new V.UnifiedRenderer("worker",{workerUrl:e})}dispose(){this._renderer&&(this._renderer.destroy(),this._renderer=void 0),K._instance=null}};it._instance=null;let Be=it;class Rt extends E{constructor(e,t){super(t),e.forEach(i=>{if(Array.isArray(i)){const n=new E(t);this.add(n),this.box.union(n.box)}else this.add(i),this.box.union(i.box)}),this.flatten()}}class Vt extends E{constructor(e,t,i){super(i);const n=URL.createObjectURL(e),s=new u.TextureLoader().load(n);s.colorSpace=u.SRGBColorSpace;const r=new u.MeshBasicMaterial({side:u.DoubleSide,map:s}),o=new u.Shape(t.boundary),a=new u.ShapeGeometry(o);this.generateUVs(a);const h=new u.Mesh(a,r);this.add(h)}generateUVs(e){const t=e.attributes.position.array,i=new Float32Array(t.length/3*2),n=Math.min(...t.filter((l,m)=>m%3===0)),s=Math.max(...t.filter((l,m)=>m%3===0)),r=Math.min(...t.filter((l,m)=>m%3===1)),o=Math.max(...t.filter((l,m)=>m%3===1)),a=s-n,h=o-r;for(let l=0;l<t.length;l+=3){const m=t[l],d=t[l+1];i[l/3*2]=(m-n)/a,i[l/3*2+1]=(d-r)/h}e.setAttribute("uv",new u.BufferAttribute(i,2))}}const pe=new u.Vector3,ye=new u.Vector3;class se{static release(e){e.index=null,e.attributes={}}static toNonIndexed(e){if(!e.index)return e;const t=new u.BufferGeometry,i=e.index;for(const n in e.attributes)t.setAttribute(n,se.createGeometryAttributeByIndex(e.attributes[n],i));return t}static createGeometryAttributeByIndex(e,t){const i=t.count,n=e.itemSize,s=e.array.constructor,r=new s(i*n);for(let o=0;o<i;o++){const a=t.getX(o)*n;for(let h=0;h<n;h++)r[o*n+h]=e.array[a+h]}return new u.BufferAttribute(r,n,e.normalized)}static tryConvertInterleavedBufferAttributes(e){!e||!e.attributes||Object.keys(e.attributes).forEach(t=>{const i=e.attributes[t];if(i instanceof u.InterleavedBufferAttribute){const n=i.clone();e.attributes[t]=n}})}static createBufferGeometryByPoints(e){const t=new u.BufferGeometry,i=new Float32Array(e.length*3),n=new Uint16Array((e.length-1)*2);return e.forEach((s,r)=>{let o=r*3;i[o]=s.x,i[o+1]=s.y,i[o+2]=s.z,r>0&&(o=(r-1)*2,n[o]=r-1,n[o+1]=r)}),t.setAttribute("position",new u.Float32BufferAttribute(i,3)),t.setIndex(new u.Uint16BufferAttribute(n,1)),t}static computeLineDistance(e){const t=e.isLineSegments===!0;let i=e.geometry;const n=e.matrixWorld;if(i.index&&(i=se.toNonIndexed(i)),i.index===null){const s=i.attributes.position;if(!s||s.count===0)return;const r=[];if(t)for(let o=0,a=s.count;o<a;o+=2)pe.fromBufferAttribute(s,o).applyMatrix4(n),ye.fromBufferAttribute(s,o+1).applyMatrix4(n),r[o]=o===0?0:r[o-1],r[o+1]=r[o]+pe.distanceTo(ye);else{r[0]=0;for(let o=1,a=s.count;o<a;o++)pe.fromBufferAttribute(s,o-1).applyMatrix4(n),ye.fromBufferAttribute(s,o).applyMatrix4(n),r[o]=r[o-1],r[o]+=pe.distanceTo(ye)}i.setAttribute("lineDistance",new u.Float32BufferAttribute(r,1)),e.geometry.dispose(),e.geometry=i}}static computeLineDistances(e){e.traverse(t=>{let i=t;i.isLine&&i.material instanceof u.ShaderMaterial&&this.computeLineDistance(i)})}static apply2dTransform(e,t,i=0,n=1){const s=e.attributes.position,r=s.itemSize,o=s.array;if(i!=0){const a=Math.cos(i),h=Math.sin(i);for(let l=0;l<o.length;l+=r){const m=o[l],d=o[l+1],y=m*a-d*h,p=m*h+d*a;o[l]=y*n+t.x,o[l+1]=p*n+t.y}}else for(let a=0;a<o.length;a+=r)o[a]=o[a]*n+t.x,o[a+1]+=o[a+1]*n+t.y;return s.needsUpdate=!0,e}static apply3dTransform(e,t,i){const n=e.attributes.position,s=n.itemSize,r=n.array,o=Math.cos(i.x),a=Math.sin(i.x),h=Math.cos(i.y),l=Math.sin(i.y),m=Math.cos(i.z),d=Math.sin(i.z);for(let y=0;y<r.length;y+=s){let p=r[y],f=r[y+1],x=r[y+2],b=f*o-x*a,_=f*a+x*o;f=b,x=_;let S=p*h+x*l;_=-p*l+x*h,p=S,x=_,S=p*m-f*d,b=p*d+f*m,p=S,f=b,r[y]=p+t.x,r[y+1]=f+t.y,r[y+2]=x+t.z}return n.needsUpdate=!0,e}}class jt extends E{constructor(e,t,i){super(i);let n;const s=t?t.color:16777215;t?n=this.styleManager.getLineShaderMaterial(t,1):n=new u.LineBasicMaterial({color:s});const r=e.length,o=new Float32Array(r*3),a=r*2>65535?new Uint32Array(r*2):new Uint16Array(r*2);for(let m=0,d=0;m<r;m++){const y=e[m];o[d++]=y.x,o[d++]=y.y,o[d++]=y.z??0}for(let m=0,d=0;m<r-1;m++)a[d++]=m,a[d++]=m+1;const h=new u.BufferGeometry;h.setAttribute("position",new u.BufferAttribute(o,3)),h.setIndex(new u.BufferAttribute(a,1)),this.setBoundingBox(h),this.geometry=h;const l=new u.LineSegments(h,n);se.computeLineDistances(l),this.add(l)}setBoundingBox(e){e.computeBoundingBox(),this.box=e.boundingBox}}class kt extends E{constructor(e,t,i,n,s){super(s);let r;n?r=this.styleManager.getLineShaderMaterial(n,1):r=new u.LineBasicMaterial({color:16777215});const o=new u.BufferGeometry;o.setAttribute("position",new u.BufferAttribute(e,t)),o.setIndex(new u.BufferAttribute(i,1)),o.computeBoundingBox(),this.box=o.boundingBox;const a=new u.LineSegments(o,r);se.computeLineDistances(a),this.add(a)}}class Ft extends E{constructor(e,t,i){super(i),this._text=e,this._style=t}async draw(){const e=Be.getInstance();if(e)try{const t=this._style;this._mtext=await e.renderMText(this._text,t,{byLayerColor:t.byLayerColor,byBlockColor:t.byBlockColor}),this._mtext&&(this.add(this._mtext),this.flatten(),this.traverse(i=>{i.userData.bboxIntersectionCheck=!0}))}catch(t){console.log(`Failed to render mtext '${this._text.text}' with the following error:
26
- `,t)}}raycast(e,t){var i;(i=this._mtext)==null||i.raycast(e,t)}getTextEncoding(e){return e!=null&&e.bigFont&&e.bigFont.toUpperCase().startsWith("GB")?"gbk":"utf8"}}const Nt=new u.Vector3;class Ut extends E{constructor(e,t,i){super(i);const n=R.instance.create(t.displayMode,e);this.isShowPoint=n.point!=null;const s=n.point??new u.BufferGeometry().setFromPoints([Nt.copy(e)]);s.computeBoundingBox(),s.boundingBox&&this.box.union(s.boundingBox);const r=this.styleManager.getPointsMaterial(t.color),o=new u.Points(s,r);if(o.userData.bboxIntersectionCheck=!0,o.visible=this.isShowPoint,this.add(o),n.line){const a=n.line;a.computeBoundingBox(),a.boundingBox&&this.box.union(a.boundingBox);const h=this.styleManager.getLineBasicMaterial(t.color),l=new u.LineSegments(a,h);l.userData.bboxIntersectionCheck=!0,l.userData.isPoint=!0,l.userData.position={x:e.x,y:e.y,z:e.z},this.add(l)}}}class Wt extends E{constructor(e,t,i){var n;super(i);const s=e.getPoints(100),r=e.buildHierarchy(),o=[];this.buildHatchGeometry(s,r,o);let a;if(o.length>0&&(a=ut.mergeGeometries(o)),!a||!a.getIndex()||((n=a.getIndex())==null?void 0:n.count)===0)console.warn("Failed to convert hatch boundaries!");else{a.computeBoundingBox(),this.box=a.boundingBox;const h=this.styleManager.getHatchShaderMaterial(t,new u.Vector2(0,0));this.add(new u.Mesh(a,h))}}buildHatchGeometry(e,t,i){if(t.children.length===0)return;const n=[],s=new Map;t.children.forEach(a=>{a.children.length===0?n.push(a.index):s.set(a.index,a.children.map(h=>h.index))});const r=a=>{try{const h=new u.ShapeGeometry(a);h.hasAttribute("uv")&&h.deleteAttribute("uv"),h.hasAttribute("normal")&&h.deleteAttribute("normal"),i.push(h)}catch{console.warn(`Triangulate shape error: ${a.getPoints().map(h=>h.toArray()).toString()}`)}};n.forEach(a=>{const h=e[a];if(h.length===0)return;const l=new u.Shape(h);r(l)});const o=a=>a.map(h=>h.toArray());for(const a of s){const h=new u.Shape(e[a[0]]);let l={regions:[],inverted:!1};const m=this.findIntersectHole(e,a[1]);m.forEach(y=>{let p={segments:[],inverted:!1},f=1e-6;try{y.forEach((x,b)=>{f=Math.min(e[x][0].relativeEps(),1e-6);const _=new Qe(new $e(f));if(b===0)p=_.segments({regions:[o(e[x])],inverted:!1});else{const S=_.segments({regions:[o(e[x])],inverted:!1}),v=_.combine(p,S);l=_.polygon(_.selectUnion(v)),l.regions.length>0?l.regions.forEach(A=>{if(A.length===0)return;const O=A.map(I=>new u.Vector2(I[0],I[1]));h.holes.push(new u.Path(O))}):console.warn("mergedHoles.regions is empty!")}})}catch(x){console.warn(`Polybool error: ${x}, epsilon is ${f}`)}});const d=m.flat(2);for(let y=0;y<a[1].length;y++){const p=a[1][y];d.includes(p)||h.holes.push(new u.Path(e[p]))}r(h)}t.children.forEach(a=>{a.children.forEach(h=>{this.buildHatchGeometry(e,h,i)})})}findIntersectHole(e,t){const i=t.length,n=[];for(let s=0;s<i;s++){const r=e[t[s]];let o=!1;const a=[];for(let h=s+1;h<i;h++){const l=e[t[h]];g.AcGeGeometryUtil.isPolygonIntersect(r,l)&&(o=!0,a.push(t[h]))}o&&(a.push(t[s]),n.push(a))}return n}}function Xt(c,e,t,i,n=0){const s={u_cameraZoom:t,u_patternLines:{value:c},u_patternAngle:{value:e},u_color:{value:i}},r=`
25
+ </svg>`}}const k=new he;class Ct{convert(){const e=M.instance.curDocument.database.tables.blockTable.modelSpace.newIterator(),t=new Bt;for(const i of e)i.draw(t);this.createFileAndDownloadIt(t.export())}createFileAndDownloadIt(e){const t=new Blob([e],{type:"image/svg+xml;charset=utf-8"}),i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download="example.svg",document.body.appendChild(n),n.click()}}class Ve extends G{execute(e){new Ct().convert()}}class je extends G{execute(e){z.emit("open-file",{})}}class ke extends G{execute(e){M.instance.openUrl("https://cdn.jsdelivr.net/gh/mlight-lee/cad-data/templates/"+"acadiso.dxf")}}class Fe extends G{execute(e){e.view.mode=P.SELECTION,e.view.setCursor(j.Crosshair)}}class Ne extends G{execute(e){const t=e.doc.database;e.view.zoomTo(new g.AcGeBox2d(t.extmin,t.extmax),1.1)}}class Ue extends ze{constructor(e){super(e)}async sampler(){await M.instance.editor.getSelection().then(e=>this.view.zoomTo(e,1))}}class We extends G{async execute(e){await new Ue(e.view).drag()}}class Xe extends G{execute(e){e.view.mode=P.PAN,e.view.setCursor(j.Grab)}}var B;(function(c){c[c.BeforeStart=0]="BeforeStart",c[c.EqualStart=1]="EqualStart",c[c.BetweenStartAndEnd=2]="BetweenStartAndEnd",c[c.EqualEnd=3]="EqualEnd",c[c.AfterEnd=4]="AfterEnd"})(B||(B={}));class Mt{pointsSame(e,t){return this.pointsSameX(e,t)&&this.pointsSameY(e,t)}pointsCompare(e,t){return this.pointsSameX(e,t)?this.pointsSameY(e,t)?0:e[1]<t[1]?-1:1:e[0]<t[0]?-1:1}}class $e extends Mt{constructor(e=1e-10){super(),this.epsilon=e}pointAboveOrOnLine(e,t,i){const n=t[0],s=t[1],r=i[0],o=i[1],a=e[0],h=e[1];return(r-n)*(h-s)-(o-s)*(a-n)>=-this.epsilon}pointBetween(e,t,i){const n=e[1]-t[1],s=i[0]-t[0],r=e[0]-t[0],o=i[1]-t[1],a=r*s+n*o;if(a<this.epsilon)return!1;const h=s*s+o*o;return!(a-h>-this.epsilon)}pointsSameX(e,t){return Math.abs(e[0]-t[0])<this.epsilon}pointsSameY(e,t){return Math.abs(e[1]-t[1])<this.epsilon}pointsCollinear(e,t,i){const n=e[0]-t[0],s=e[1]-t[1],r=t[0]-i[0],o=t[1]-i[1];return Math.abs(n*o-r*s)<this.epsilon}linesIntersect(e,t,i,n){const s=t[0]-e[0],r=t[1]-e[1],o=n[0]-i[0],a=n[1]-i[1],h=s*a-r*o;if(Math.abs(h)<this.epsilon)return null;const l=e[0]-i[0],m=e[1]-i[1],u=(o*m-a*l)/h,y=(s*m-r*l)/h,p=x=>x<=-this.epsilon?B.BeforeStart:x<this.epsilon?B.EqualStart:x-1<=-this.epsilon?B.BetweenStartAndEnd:x-1<this.epsilon?B.EqualEnd:B.AfterEnd,f=[e[0]+u*s,e[1]+u*r];return{alongA:p(u),alongB:p(y),p:f}}}class Ye{constructor(){this.nodes=[]}remove(e){const t=this.nodes.indexOf(e);t>=0&&this.nodes.splice(t,1)}getIndex(e){return this.nodes.indexOf(e)}isEmpty(){return this.nodes.length<=0}getHead(){return this.nodes[0]}removeHead(){this.nodes.shift()}insertBefore(e,t){this.findTransition(e,t).insert(e)}findTransition(e,t){var i,n;const s=(a,h)=>t(h)-t(a);let r=0,o=this.nodes.length;for(;r<o;){const a=r+o>>1;s(this.nodes[a],e)>0?o=a:r=a+1}return{before:r<=0?null:(i=this.nodes[r-1])!==null&&i!==void 0?i:null,after:(n=this.nodes[r])!==null&&n!==void 0?n:null,insert:a=>(this.nodes.splice(r,0,a),a)}}}class F{constructor(e,t,i,n){var s;this.otherFill=null,this.id=(s=n==null?void 0:n.segmentId())!==null&&s!==void 0?s:-1,this.start=e,this.end=t,this.myFill={above:i?i.myFill.above:null,below:i?i.myFill.below:null}}}class He{constructor(e,t,i,n){this.status=null,this.isStart=e,this.p=t,this.seg=i,this.primary=n}}class qe{constructor(e,t,i=null){this.events=new Ye,this.status=new Ye,this.selfIntersection=e,this.geo=t,this.log=i}compareEvents(e,t,i,n,s,r){const o=this.geo.pointsCompare(t,s);return o!==0?o:this.geo.pointsSame(i,r)?0:e!==n?e?1:-1:this.geo.pointAboveOrOnLine(i,n?s:r,n?r:s)?1:-1}addEvent(e){this.events.insertBefore(e,t=>t===e?0:this.compareEvents(e.isStart,e.p,e.other.p,t.isStart,t.p,t.other.p))}divideEvent(e,t){var i;const n=new F(t,e.seg.end,e.seg,this.log);return(i=this.log)===null||i===void 0||i.segmentChop(e.seg,t),this.events.remove(e.other),e.seg.end=t,e.other.p=t,this.addEvent(e.other),this.addSegment(n,e.primary)}newSegment(e,t){const i=this.geo.pointsCompare(e,t);return i===0?null:i<0?new F(e,t,null,this.log):new F(t,e,null,this.log)}addSegment(e,t){const i=new He(!0,e.start,e,t),n=new He(!1,e.end,e,t);return i.other=n,n.other=i,this.addEvent(i),this.addEvent(n),i}addRegion(e){let t,i=e[e.length-1];for(let n=0;n<e.length;n++){t=i,i=e[n];const s=this.newSegment(t,i);s&&this.addSegment(s,!0)}}compareStatus(e,t){const i=e.seg.start,n=e.seg.end,s=t.seg.start,r=t.seg.end;return this.geo.pointsCollinear(i,s,r)?this.geo.pointsCollinear(n,s,r)||this.geo.pointAboveOrOnLine(n,s,r)?1:-1:this.geo.pointAboveOrOnLine(i,s,r)?1:-1}statusFindSurrounding(e){return this.status.findTransition(e,t=>t===e?0:-this.compareStatus(e,t))}checkIntersection(e,t){var i;const n=e.seg,s=t.seg,r=n.start,o=n.end,a=s.start,h=s.end;(i=this.log)===null||i===void 0||i.checkIntersection(n,s);const l=this.geo.linesIntersect(r,o,a,h);if(l===null){if(!this.geo.pointsCollinear(r,o,a)||this.geo.pointsSame(r,h)||this.geo.pointsSame(o,a))return null;const m=this.geo.pointsSame(r,a),u=this.geo.pointsSame(o,h);if(m&&u)return t;const y=!m&&this.geo.pointBetween(r,a,h),p=!u&&this.geo.pointBetween(o,a,h);if(m)return p?this.divideEvent(t,o):this.divideEvent(e,h),t;y&&(u||(p?this.divideEvent(t,o):this.divideEvent(e,h)),this.divideEvent(t,r))}else l.alongA===B.BetweenStartAndEnd&&(l.alongB===B.EqualStart?this.divideEvent(e,a):l.alongB===B.BetweenStartAndEnd?this.divideEvent(e,l.p):l.alongB===B.EqualEnd&&this.divideEvent(e,h)),l.alongB===B.BetweenStartAndEnd&&(l.alongA===B.EqualStart?this.divideEvent(t,r):l.alongA===B.BetweenStartAndEnd?this.divideEvent(t,l.p):l.alongA===B.EqualEnd&&this.divideEvent(t,o));return null}calculate(e,t){var i,n,s,r,o,a,h,l;const m=[];for(;!this.events.isEmpty();){const u=this.events.getHead();if((i=this.log)===null||i===void 0||i.vert(u.p[0]),u.isStart){(n=this.log)===null||n===void 0||n.segmentNew(u.seg,u.primary);const y=this.statusFindSurrounding(u),p=y.before,f=y.after;(s=this.log)===null||s===void 0||s.tempStatus(u.seg,p?p.seg:!1,f?f.seg:!1);const b=(()=>{if(p){const _=this.checkIntersection(u,p);if(_)return _}return f?this.checkIntersection(u,f):null})();if(b){if(this.selfIntersection){let _;u.seg.myFill.below===null?_=!0:_=u.seg.myFill.above!==u.seg.myFill.below,_&&(b.seg.myFill.above=!b.seg.myFill.above)}else b.seg.otherFill=u.seg.myFill;(r=this.log)===null||r===void 0||r.segmentUpdate(b.seg),this.events.remove(u.other),this.events.remove(u)}if(this.events.getHead()!==u){(o=this.log)===null||o===void 0||o.rewind(u.seg);continue}if(this.selfIntersection){let _;u.seg.myFill.below===null?_=!0:_=u.seg.myFill.above!==u.seg.myFill.below,f?u.seg.myFill.below=f.seg.myFill.above:u.seg.myFill.below=e,_?u.seg.myFill.above=!u.seg.myFill.below:u.seg.myFill.above=u.seg.myFill.below}else if(u.seg.otherFill===null){let _;if(!f)_=u.primary?t:e;else if(u.primary===f.primary){if(f.seg.otherFill===null)throw new Error("otherFill is null");_=f.seg.otherFill.above}else _=f.seg.myFill.above;u.seg.otherFill={above:_,below:_}}(a=this.log)===null||a===void 0||a.status(u.seg,p?p.seg:!1,f?f.seg:!1),u.other.status=y.insert(u)}else{const y=u.status;if(y===null)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");const p=this.status.getIndex(y);if(p>0&&p<this.status.nodes.length-1){const f=this.status.nodes[p-1],x=this.status.nodes[p+1];this.checkIntersection(f,x)}if((h=this.log)===null||h===void 0||h.statusRemove(y.seg),this.status.remove(y),!u.primary){if(!u.seg.otherFill)throw new Error("otherFill is null");const f=u.seg.myFill;u.seg.myFill=u.seg.otherFill,u.seg.otherFill=f}m.push(u.seg)}this.events.removeHead()}return(l=this.log)===null||l===void 0||l.done(),m}}function ee(c,e,t){const i=[];for(const n of c){const s=(n.myFill.above?8:0)+(n.myFill.below?4:0)+(n.otherFill&&n.otherFill.above?2:0)+(n.otherFill&&n.otherFill.below?1:0);if(e[s]!==0){const r=new F(n.start,n.end,null,t);r.myFill.above=e[s]===1,r.myFill.below=e[s]===2,i.push(r)}}return t==null||t.selected(i),i}class te{static union(e,t){return ee(e,[0,2,1,0,2,2,0,0,1,0,1,0,0,0,0,0],t)}static intersect(e,t){return ee(e,[0,0,0,0,0,2,0,2,0,0,1,1,0,2,1,0],t)}static difference(e,t){return ee(e,[0,0,0,0,2,0,2,0,1,1,0,0,0,1,2,0],t)}static differenceRev(e,t){return ee(e,[0,2,1,0,0,0,1,1,0,2,0,2,0,0,0,0],t)}static xor(e,t){return ee(e,[0,2,1,0,2,0,0,1,1,0,0,2,0,1,2,0],t)}}function Et(c,e,t){const i=[],n=[];for(const s of c){let m=function(b,_,S){return l&&(l.index=b,l.matches_head=_,l.matches_pt1=S),l===a?(l=h,!1):(l=null,!0)},u=function(b){t==null||t.chainReverse(b),i[b].reverse()},y=function(b,_){const S=i[b],v=i[_];let A=S[S.length-1];const O=S[S.length-2],I=v[0],J=v[1];e.pointsCollinear(O,A,I)&&(t==null||t.chainRemoveTail(b,A),S.pop(),A=O),e.pointsCollinear(A,I,J)&&(t==null||t.chainRemoveHead(_,I),v.shift()),t==null||t.chainJoin(b,_),i[b]=S.concat(v),i.splice(_,1)};const r=s.start,o=s.end;if(e.pointsSame(r,o)){console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large");continue}t==null||t.chainStart(s);const a={index:0,matches_head:!1,matches_pt1:!1},h={index:0,matches_head:!1,matches_pt1:!1};let l=a;for(let b=0;b<i.length;b++){const _=i[b],S=_[0],v=_[_.length-1];if(e.pointsSame(S,r)){if(m(b,!0,!0))break}else if(e.pointsSame(S,o)){if(m(b,!0,!1))break}else if(e.pointsSame(v,r)){if(m(b,!1,!0))break}else if(e.pointsSame(v,o)&&m(b,!1,!1))break}if(l===a){i.push([r,o]),t==null||t.chainNew(r,o);continue}if(l===h){t==null||t.chainMatch(a.index);const b=a.index,_=a.matches_pt1?o:r,S=a.matches_head,v=i[b];let A=S?v[0]:v[v.length-1];const O=S?v[1]:v[v.length-2],I=S?v[v.length-1]:v[0],J=S?v[v.length-2]:v[1];if(e.pointsCollinear(O,A,_)&&(S?(t==null||t.chainRemoveHead(a.index,_),v.shift()):(t==null||t.chainRemoveTail(a.index,_),v.pop()),A=O),e.pointsSame(I,_)){i.splice(b,1),e.pointsCollinear(J,I,A)&&(S?(t==null||t.chainRemoveTail(a.index,A),v.pop()):(t==null||t.chainRemoveHead(a.index,A),v.shift())),t==null||t.chainClose(a.index),n.push(v);continue}S?(t==null||t.chainAddHead(a.index,_),v.unshift(_)):(t==null||t.chainAddTail(a.index,_),v.push(_));continue}const p=a.index,f=h.index;t==null||t.chainConnect(p,f);const x=i[p].length<i[f].length;a.matches_head?h.matches_head?x?(u(p),y(p,f)):(u(f),y(f,p)):y(f,p):h.matches_head?y(p,f):x?(u(p),y(f,p)):(u(f),y(p,f))}return n}class Lt{constructor(){this.list=[],this.nextSegmentId=0,this.curVert=NaN}push(e,t){this.list.push({type:e,data:JSON.parse(JSON.stringify(t))})}segmentId(){return this.nextSegmentId++}checkIntersection(e,t){this.push("check",{seg1:e,seg2:t})}segmentChop(e,t){this.push("div_seg",{seg:e,p:t}),this.push("chop",{seg:e,p:t})}statusRemove(e){this.push("pop_seg",{seg:e})}segmentUpdate(e){this.push("seg_update",{seg:e})}segmentNew(e,t){this.push("new_seg",{seg:e,primary:t})}tempStatus(e,t,i){this.push("temp_status",{seg:e,above:t,below:i})}rewind(e){this.push("rewind",{seg:e})}status(e,t,i){this.push("status",{seg:e,above:t,below:i})}vert(e){e!==this.curVert&&(this.push("vert",{x:e}),this.curVert=e)}selected(e){this.push("selected",{segs:e})}chainStart(e){this.push("chain_start",{seg:e})}chainRemoveHead(e,t){this.push("chain_rem_head",{index:e,p:t})}chainRemoveTail(e,t){this.push("chain_rem_tail",{index:e,p:t})}chainNew(e,t){this.push("chain_new",{p1:e,p2:t})}chainMatch(e){this.push("chain_match",{index:e})}chainClose(e){this.push("chain_close",{index:e})}chainAddHead(e,t){this.push("chain_add_head",{index:e,p:t})}chainAddTail(e,t){this.push("chain_add_tail",{index:e,p:t})}chainConnect(e,t){this.push("chain_con",{index1:e,index2:t})}chainReverse(e){this.push("chain_rev",{index:e})}chainJoin(e,t){this.push("chain_join",{index1:e,index2:t})}done(){this.push("done",null)}}class Qe{constructor(e){this.log=null,this.geo=e}buildLog(e){var t;return this.log=e?new Lt:null,(t=this.log)===null||t===void 0?void 0:t.list}segments(e){const t=new qe(!0,this.geo,this.log);for(const i of e.regions)t.addRegion(i);return{segments:t.calculate(e.inverted,!1),inverted:e.inverted}}combine(e,t){const i=new qe(!1,this.geo,this.log);for(const n of e.segments)i.addSegment(new F(n.start,n.end,n,this.log),!0);for(const n of t.segments)i.addSegment(new F(n.start,n.end,n,this.log),!1);return{combined:i.calculate(e.inverted,t.inverted),inverted1:e.inverted,inverted2:t.inverted}}selectUnion(e){return{segments:te.union(e.combined,this.log),inverted:e.inverted1||e.inverted2}}selectIntersect(e){return{segments:te.intersect(e.combined,this.log),inverted:e.inverted1&&e.inverted2}}selectDifference(e){return{segments:te.difference(e.combined,this.log),inverted:e.inverted1&&!e.inverted2}}selectDifferenceRev(e){return{segments:te.differenceRev(e.combined,this.log),inverted:!e.inverted1&&e.inverted2}}selectXor(e){return{segments:te.xor(e.combined,this.log),inverted:e.inverted1!==e.inverted2}}polygon(e){return{regions:Et(e.segments,this.geo,this.log),inverted:e.inverted}}union(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectUnion(s);return this.polygon(r)}intersect(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectIntersect(s);return this.polygon(r)}difference(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectDifference(s);return this.polygon(r)}differenceRev(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectDifferenceRev(s);return this.polygon(r)}xor(e,t){const i=this.segments(e),n=this.segments(t),s=this.combine(i,n),r=this.selectXor(s);return this.polygon(r)}}new Qe(new $e);class le extends d.Object3D{static flattenObject(e){const t=[];function i(s){s.position.set(0,0,0),s.rotation.set(0,0,0),s.scale.set(1,1,1),s.matrix.identity()}function n(s,r){const o=[...s.children];for(const a of o)a.applyMatrix4(r),i(a),a.children.length>0?n(a,a.matrixWorld):t.push(a);s.children=[]}e.updateMatrixWorld(!0),n(e,e.matrixWorld);for(const s of t)"geometry"in s&&(s.geometry.applyMatrix4(s.matrixWorld),s.matrixWorld.identity(),s.matrixWorldNeedsUpdate=!1,e.add(s));i(e),e.matrixWorld.identity(),e.matrixWorldNeedsUpdate=!1}static disposeObject(e,t=!0){t&&e.removeFromParent(),(e instanceof d.Mesh||e instanceof d.Line||e instanceof d.Points)&&e.geometry&&e.geometry.dispose(),(e instanceof d.Mesh||e instanceof d.Line||e instanceof d.Points)&&(Array.isArray(e.material)?e.material:[e.material]).forEach(i=>{var n,s,r,o,a,h,l,m;i.dispose(),(n=i.map)==null||n.dispose(),(s=i.envMap)==null||s.dispose(),(r=i.lightMap)==null||r.dispose(),(o=i.bumpMap)==null||o.dispose(),(a=i.normalMap)==null||a.dispose(),(h=i.roughnessMap)==null||h.dispose(),(l=i.metalnessMap)==null||l.dispose(),(m=i.alphaMap)==null||m.dispose()}),e.children.forEach(i=>this.disposeObject(i)),"geometry"in e&&(e.geometry=null),"material"in e&&(e.material=null),e.children=[]}flatten(){le.flattenObject(this)}dispose(){le.disposeObject(this)}}const L=[.5,0,0,.48429158056431554,-.1243449435824274,0,.4381533400219318,-.24087683705085766,0,.3644843137107058,-.3422735529643443,0,.2679133974894983,-.42216396275100754,0,.15450849718747373,-.47552825814757677,0,.03139525976465676,-.4990133642141358,0,-.09369065729286241,-.4911436253643443,0,-.21288964578253636,-.45241352623300973,0,-.3187119948743449,-.3852566213878946,0,-.40450849718747367,-.2938926261462366,0,-.4648882429441257,-.18406227634233907,0,-.4960573506572389,-.06266661678215227,0,-.49605735065723894,.06266661678215214,0,-.4648882429441256,.18406227634233915,0,-.4045084971874738,.2938926261462365,0,-.31871199487434476,.3852566213878947,0,-.21288964578253608,.4524135262330099,0,-.09369065729286231,.49114362536434436,0,.031395259764656416,.4990133642141358,0,.15450849718747361,.4755282581475768,0,.267913397489498,.42216396275100776,0,.3644843137107056,.3422735529643445,0,.4381533400219318,.24087683705085766,0,.4842915805643155,.12434494358242767,0,.5,0,0],T=[0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25],Tt=new Map([[2,{position:new Float32Array([-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([0,1,2,3])}],[3,{position:new Float32Array([-Math.SQRT1_2,Math.SQRT1_2,0,Math.SQRT1_2,-Math.SQRT1_2,0,-Math.SQRT1_2,-Math.SQRT1_2,0,Math.SQRT1_2,Math.SQRT1_2,0]),indices:new Uint16Array([0,1,2,3])}],[4,{position:new Float32Array([0,0,0,0,.5,0]),indices:new Uint16Array([0,1,2,3])}],[32,{position:new Float32Array(L),indices:new Uint16Array(T)}],[33,{position:new Float32Array(L),indices:new Uint16Array(T)}],[34,{position:new Float32Array([...L,-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([...T,26,27,28,29])}],[35,{position:new Float32Array([...L,-Math.SQRT1_2,Math.SQRT1_2,0,Math.SQRT1_2,-Math.SQRT1_2,0,-Math.SQRT1_2,-Math.SQRT1_2,0,Math.SQRT1_2,Math.SQRT1_2,0]),indices:new Uint16Array([...T,26,27,28,29])}],[36,{position:new Float32Array([...L,0,0,0,0,.5,0]),indices:new Uint16Array([...T,26,27])}],[64,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0]),indices:new Uint16Array([0,1,1,2,2,3,3,4])}],[65,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0]),indices:new Uint16Array([0,1,1,2,2,3,3,4])}],[66,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([0,1,1,2,2,3,3,4,5,6,7,8])}],[67,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-Math.SQRT1_2,Math.SQRT1_2,0,Math.SQRT1_2,-Math.SQRT1_2,0,-Math.SQRT1_2,-Math.SQRT1_2,0,Math.SQRT1_2,Math.SQRT1_2,0]),indices:new Uint16Array([0,1,1,2,2,3,3,0,4,5,6,7])}],[68,{position:new Float32Array([-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,0,0,0,0,.5,0]),indices:new Uint16Array([0,1,1,2,2,3,3,4,5,6])}],[96,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,26])}],[97,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,30])}],[98,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,30,31,32,33,34])}],[99,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-Math.SQRT1_2,Math.SQRT1_2,0,Math.SQRT1_2,-Math.SQRT1_2,0,-Math.SQRT1_2,-Math.SQRT1_2,0,Math.SQRT1_2,Math.SQRT1_2,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,26,30,31,32,33])}],[100,{position:new Float32Array([...L,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,0,0,0,0,.5,0]),indices:new Uint16Array([...T,26,27,27,28,28,29,29,30,31,32])}]]);class R{constructor(){this._symbols=this.initialize()}static get instance(){return R._instance||(R._instance=new R),R._instance}isShowPoint(e=null){return e==null||e==0||e==32||e==64||e==96}create(e=null,t={x:0,y:0,z:0}){const i={};if(e==null||e==0)ie.copy(t),i.point=new d.BufferGeometry().setFromPoints([ie]);else if(e!=1){const n=this._symbols.get(e);if(n==null)throw new Error(`[AcTrPointSymbolCreator] Invalid point type value: '${e}'!`);ie.copy(t),Ze.identity().makeTranslation(ie),i.line=n.clone().applyMatrix4(Ze),(e==32||e==64||e==96)&&(i.point=new d.BufferGeometry().setFromPoints([ie]))}return i}initialize(){const e=new Map;return Tt.forEach((t,i)=>{const n=new d.BufferGeometry;n.setAttribute("position",new d.BufferAttribute(t.position,3)),n.setIndex(new d.BufferAttribute(t.indices,1)),e.set(i,n)}),e}}const Ze=new d.Matrix4,ie=new d.Vector3,Dt=new d.Color(583902);class de{static cloneMaterial(e){if(!e)return e;if(Array.isArray(e)){const t=[];return e.forEach(i=>{t.push(i.clone())}),t}return e.clone()}static setMaterialColor(e,t=Dt){if(Array.isArray(e)){e.forEach(i=>this.setMaterialColor(i,t));return}this.hasColorProperty(e)&&(e.color.set(t),this.hasEmissiveProperty(e)&&e.emissive.set(t)),this.hasUniformsProperty(e)&&e.uniforms.u_color&&e.uniforms.u_color.value.set(t)}static hasColorProperty(e){return"color"in e&&e.color instanceof d.Color}static hasEmissiveProperty(e){return"emissive"in e&&e.emissive instanceof d.Color}static hasUniformsProperty(e){return"uniforms"in e&&e.uniforms!==void 0}}class ne{static getExtension(e){return e.substring(e.lastIndexOf(".")+1)}static estimateObjectSize(e){const t=new WeakSet;function i(n){if(n==null)return 0;const s=typeof n;if(s==="boolean")return 4;if(s==="number")return 8;if(s==="string")return n.length*2;if(s==="symbol"||s==="function"||t.has(n))return 0;if(t.add(n),Array.isArray(n))return n.map(i).reduce((r,o)=>r+o,0);if(s==="object"){let r=0;for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r+=o.length*2,r+=i(n[o]));return r}return 0}return i(e)}static getFileName(e){return e.split("/").pop()}static getFileNameWithoutExtension(e){const t=ne.getFileName(e);if(t){const i=t.lastIndexOf(".");return i===-1?t:t.substring(0,i)}return e}}function Ae(c,e){return c-e}function Be(c,e,t=0){const i=e.itemSize;if(c.isInterleavedBufferAttribute||c.array.constructor!==e.array.constructor){const n=c.count;for(let s=0;s<n;s++)for(let r=0;r<i;r++)e.setComponent(s+t,r,c.getComponent(s,r))}else e.array.set(c.array,t*i);e.needsUpdate=!0}function N(c,e){if(c.constructor!==e.constructor){const t=Math.min(c.length,e.length);for(let i=0;i<t;i++)e[i]=c[i]}else{const t=Math.min(c.length,e.length);e.set(new c.constructor(c.buffer,0,t))}}const Je=new d.Box3,U=new d.Vector3,W=new d.LineSegments,ue=[];class zt extends d.LineSegments{constructor(e=1e3,t=e*2,i){super(new d.BufferGeometry,i),this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxVertexCount=e,this._maxIndexCount=t}get geometryCount(){return this._geometryCount}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}get mappingStats(){const e=this._geometryInfo.length;let t=0;return e>0&&(t=ne.estimateObjectSize(this._geometryInfo[0])),{count:e,size:e*t}}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount,n=this._maxIndexCount;if(this._geometryInitialized===!1){for(const s in e.attributes){const r=e.getAttribute(s),{array:o,itemSize:a,normalized:h}=r,l=new o.constructor(i*a),m=new d.BufferAttribute(l,a,h);t.setAttribute(s,m)}if(e.getIndex()!==null){const s=i>65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new d.BufferAttribute(s,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('AcTrBatchedLine: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`AcTrBatchedLine: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),s=t.getAttribute(i);if(n.itemSize!==s.itemSize||n.normalized!==s.normalized)throw new Error("AcTrBatchedLine: All attributes must have a consistent itemSize and normalized value.")}}_resizeSpaceIfNeeded(e){const t=e.getIndex(),i=t!==null;let n=this._maxIndexCount;i&&this.unusedIndexCount<t.count&&(n=(this._maxIndexCount+t.count)*1.5);const s=e.getAttribute("position");let r=this._maxVertexCount;s&&this.unusedVertexCount<s.count&&(r=(this._maxVertexCount+s.count)*1.5),(n>this._maxIndexCount||r>this._maxVertexCount)&&this.setGeometrySize(r,n)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`AcTrBatchedLine: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}reset(){this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._geometryInfo.length=0,this._geometryInitialized=!1,this.geometry.dispose()}getUserData(){const e=[];return this._geometryInfo.forEach(t=>{e.push({position:t.position,objectId:t.objectId,bboxIntersectionCheck:t.bboxIntersectionCheck})}),e}resetGeometry(e){const t=this.getUserData();this.reset();const i=R.instance;t.forEach(n=>{if(n.position){const s=i.create(e,n.position);if(s.line){const r=this.addGeometry(s.line);this.setGeometryInfo(r,n)}}})}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new d.Box3);const e=this.boundingBox,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingBox!=null&&e.union(s.boundingBox)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new d.Sphere);const e=this.boundingSphere,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingSphere!=null&&e.union(s.boundingSphere)}}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e),e.boundingBox==null&&e.computeBoundingBox(),e.boundingSphere==null&&e.computeBoundingSphere(),this._resizeSpaceIfNeeded(e);const n={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:e.boundingBox,boundingSphere:e.boundingSphere,active:!0,visible:!0},s=this._geometryInfo;n.vertexStart=this._nextVertexStart,n.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(n.indexStart=this._nextIndexStart,n.reservedIndexCount=i===-1?r.count:i),n.indexStart!==-1&&n.indexStart+n.reservedIndexCount>this._maxIndexCount||n.vertexStart+n.reservedVertexCount>this._maxVertexCount)throw new Error("AcTrBatchedLine: Reserved space request exceeds the maximum buffer size.");let o;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Ae),o=this._availableGeometryIds.shift(),s[o]=n):(o=this._geometryCount,this._geometryCount++,s.push(n)),this.setGeometryAt(o,e),this._nextIndexStart=n.indexStart+n.reservedIndexCount,this._nextVertexStart=n.vertexStart+n.reservedVertexCount,o}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine: Maximum geometry count reached.");const i=this._geometryInfo[e],n=t.position;n&&(i.position={...n}),i.objectId=t.objectId,i.bboxIntersectionCheck=t.bboxIntersectionCheck}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=i.getIndex()!==null,s=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(n&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("AcTrBatchedLine: Reserved space not large enough for provided geometry.");const a=o.vertexStart,h=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const l in i.attributes){const m=t.getAttribute(l),u=i.getAttribute(l);Be(m,u,a);const y=m.itemSize;for(let p=m.count,f=h;p<f;p++){const x=a+p;for(let b=0;b<y;b++)u.setComponent(x,b,0)}u.needsUpdate=!0,u.addUpdateRange(a*y,h*y)}if(n&&s){const l=o.indexStart,m=o.reservedIndexCount;o.indexCount=t.getIndex().count;for(let u=0;u<r.count;u++)s.setX(l+u,a+r.getX(u));for(let u=r.count,y=m;u<y;u++)s.setX(l+u,a);s.needsUpdate=!0,s.addUpdateRange(l,o.reservedIndexCount)}return o.start=n?o.indexStart:o.vertexStart,o.count=n?o.indexCount:o.vertexCount,o.boundingBox=null,t.boundingBox!==null&&(o.boundingBox=t.boundingBox.clone()),o.boundingSphere=null,t.boundingSphere!==null&&(o.boundingSphere=t.boundingSphere.clone()),e}deleteGeometry(e){const t=this._geometryInfo;return e>=t.length||t[e].active===!1?this:(t[e].active=!1,this._availableGeometryIds.push(e),this)}optimize(){let e=0,t=0;const i=this._geometryInfo,n=i.map((r,o)=>o).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),s=this.geometry;for(let r=0,o=i.length;r<o;r++){const a=n[r],h=i[a];if(h.active!==!1){if(s.index!==null){if(h.indexStart!==t){const{indexStart:l,vertexStart:m,reservedIndexCount:u}=h,y=s.index,p=y.array,f=e-m;for(let x=l;x<l+u;x++)p[x]=p[x]+f;y.array.copyWithin(t,l,l+u),y.addUpdateRange(t,u),h.indexStart=t}t+=h.reservedIndexCount}if(h.vertexStart!==e){const{vertexStart:l,reservedVertexCount:m}=h,u=s.attributes;for(const y in u){const p=u[y],{array:f,itemSize:x}=p;f.copyWithin(e*x,l*x,(l+m)*x),p.addUpdateRange(e*x,m*x)}h.vertexStart=e}e+=h.reservedVertexCount,h.start=s.index?h.indexStart:h.vertexStart,this._nextIndexStart=s.index?h.indexStart+h.reservedIndexCount:0,this._nextVertexStart=h.vertexStart+h.reservedVertexCount}}return this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingBox===null){const s=new d.Box3,r=i.index,o=i.attributes.position;for(let a=n.start,h=n.start+n.count;a<h;a++){let l=a;r&&(l=r.getX(l)),s.expandByPoint(U.fromBufferAttribute(o,l))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingSphere===null){const s=new d.Sphere;this.getBoundingBoxAt(e,Je),Je.getCenter(s.center);const r=i.index,o=i.attributes.position;let a=0;for(let h=n.start,l=n.start+n.count;h<l;h++){let m=h;r&&(m=r.getX(m)),U.fromBufferAttribute(o,m),a=Math.max(a,s.center.distanceToSquared(U))}s.radius=Math.sqrt(a),n.boundingSphere=s}return t.copy(n.boundingSphere),t}setVisibleAt(e,t){return this.validateGeometryId(e),this._geometryInfo[e].visible===t?this:(this._geometryInfo[e].visible=t,this)}getVisibleAt(e){return this.validateGeometryId(e),this._geometryInfo[e].visible}getGeometryAt(e){return this.validateGeometryId(e),this._geometryInfo[e]}setGeometrySize(e,t){const i=this.geometry;i.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new d.BufferGeometry,this._initializeGeometry(i));const n=this.geometry;i.index&&N(i.index.array,n.index.array);for(const s in i.attributes)N(i.attributes[s].array,n.attributes[s].array)}getObjectAt(e){const t=new d.LineSegments;this._initializeRaycastObject(t);const i=this._geometryInfo[e];return this._setRaycastObjectInfo(t,e,i.start,i.count),t}_initializeRaycastObject(e){const t=this.geometry;return e.material=this.material,e.geometry.index=t.index,e.geometry.attributes=t.attributes,e.geometry.boundingBox===null&&(e.geometry.boundingBox=new d.Box3),e.geometry.boundingSphere===null&&(e.geometry.boundingSphere=new d.Sphere),e}_setRaycastObjectInfo(e,t,i,n){e.geometry.setDrawRange(i,n),this.getBoundingBoxAt(t,e.geometry.boundingBox),this.getBoundingSphereAt(t,e.geometry.boundingSphere)}_resetRaycastObjectInfo(e){e.geometry.index=null,e.geometry.attributes={},e.geometry.setDrawRange(0,1/0)}intersectWith(e,t,i){this._initializeRaycastObject(W),this._intersectWith(e,t,i),this._resetRaycastObjectInfo(W)}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!(!n.visible||!n.active))if(n.bboxIntersectionCheck){const s=n.boundingBox;if(t.ray.intersectBox(s,U)){const r=t.ray.origin.distanceTo(U);i.push({distance:r,point:U.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}}else{this._setRaycastObjectInfo(W,e,n.start,n.count),W.raycast(t,ue);for(let s=0,r=ue.length;s<r;s++){const o=ue[s];o.object=this,o.batchId=e,o.objectId=n.objectId,i.push(o)}ue.length=0}}raycast(e,t){const i=this._geometryInfo;this._initializeRaycastObject(W);for(let n=0,s=i.length;n<s;n++)this._intersectWith(n,e,t);this._resetRaycastObjectInfo(W)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this}dispose(){return this.geometry.dispose(),this}}const Ke=new d.Box3,X=new d.Vector3,$=new d.Mesh,me=[];class Pt extends d.Mesh{constructor(e=1e3,t=e*2,i){super(new d.BufferGeometry,i),this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxVertexCount=e,this._maxIndexCount=t}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}get mappingStats(){const e=this._geometryInfo.length;let t=0;return e>0&&(t=ne.estimateObjectSize(this._geometryInfo[0])),{count:e,size:e*t}}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount,n=this._maxIndexCount;if(this._geometryInitialized===!1){for(const s in e.attributes){const r=e.getAttribute(s),{array:o,itemSize:a,normalized:h}=r,l=new o.constructor(i*a),m=new d.BufferAttribute(l,a,h);t.setAttribute(s,m)}if(e.getIndex()!==null){const s=i>65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new d.BufferAttribute(s,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('AcTrBatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`AcTrBatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),s=t.getAttribute(i);if(n.itemSize!==s.itemSize||n.normalized!==s.normalized)throw new Error("AcTrBatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}_resizeSpaceIfNeeded(e){const t=e.getIndex(),i=t!==null;let n=this._maxIndexCount;i&&this.unusedIndexCount<t.count&&(n=(this._maxIndexCount+t.count)*1.5);const s=e.getAttribute("position");let r=this._maxVertexCount;s&&this.unusedVertexCount<s.count&&(r=(this._maxVertexCount+s.count)*1.5),(n>this._maxIndexCount||r>this._maxVertexCount)&&this.setGeometrySize(r,n)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`AcTrBatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new d.Box3);const e=this.boundingBox,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingBox!=null&&e.union(s.boundingBox)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new d.Sphere);const e=this.boundingSphere,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingSphere!=null&&e.union(s.boundingSphere)}}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e),e.boundingBox==null&&e.computeBoundingBox(),e.boundingSphere==null&&e.computeBoundingSphere(),this._resizeSpaceIfNeeded(e);const n={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:e.boundingBox,boundingSphere:e.boundingSphere,active:!0,visible:!0},s=this._geometryInfo;n.vertexStart=this._nextVertexStart,n.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(n.indexStart=this._nextIndexStart,n.reservedIndexCount=i===-1?r.count:i),n.indexStart!==-1&&n.indexStart+n.reservedIndexCount>this._maxIndexCount||n.vertexStart+n.reservedVertexCount>this._maxVertexCount)throw new Error("AcTrBatchedMesh: Reserved space request exceeds the maximum buffer size.");let o;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Ae),o=this._availableGeometryIds.shift(),s[o]=n):(o=this._geometryCount,this._geometryCount++,s.push(n)),this.setGeometryAt(o,e),this._nextIndexStart=n.indexStart+n.reservedIndexCount,this._nextVertexStart=n.vertexStart+n.reservedVertexCount,o}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedMesh: Maximum geometry count reached.");const i=this._geometryInfo[e];i.objectId=t.objectId,i.bboxIntersectionCheck=t.bboxIntersectionCheck}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=i.getIndex()!==null,s=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(n&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("AcTrBatchedMesh: Reserved space not large enough for provided geometry.");const a=o.vertexStart,h=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const l in i.attributes){const m=t.getAttribute(l),u=i.getAttribute(l);Be(m,u,a);const y=m.itemSize;for(let p=m.count,f=h;p<f;p++){const x=a+p;for(let b=0;b<y;b++)u.setComponent(x,b,0)}u.needsUpdate=!0,u.addUpdateRange(a*y,h*y)}if(n&&s){const l=o.indexStart,m=o.reservedIndexCount;o.indexCount=t.getIndex().count;for(let u=0;u<r.count;u++)s.setX(l+u,a+r.getX(u));for(let u=r.count,y=m;u<y;u++)s.setX(l+u,a);s.needsUpdate=!0,s.addUpdateRange(l,o.reservedIndexCount)}return o.start=n?o.indexStart:o.vertexStart,o.count=n?o.indexCount:o.vertexCount,o.boundingBox=null,t.boundingBox!==null&&(o.boundingBox=t.boundingBox.clone()),o.boundingSphere=null,t.boundingSphere!==null&&(o.boundingSphere=t.boundingSphere.clone()),e}deleteGeometry(e){const t=this._geometryInfo;return e>=t.length||t[e].active===!1?this:(t[e].active=!1,this._availableGeometryIds.push(e),this)}optimize(){let e=0,t=0;const i=this._geometryInfo,n=i.map((r,o)=>o).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),s=this.geometry;for(let r=0,o=i.length;r<o;r++){const a=n[r],h=i[a];if(h.active!==!1){if(s.index!==null){if(h.indexStart!==t){const{indexStart:l,vertexStart:m,reservedIndexCount:u}=h,y=s.index,p=y.array,f=e-m;for(let x=l;x<l+u;x++)p[x]=p[x]+f;y.array.copyWithin(t,l,l+u),y.addUpdateRange(t,u),h.indexStart=t}t+=h.reservedIndexCount}if(h.vertexStart!==e){const{vertexStart:l,reservedVertexCount:m}=h,u=s.attributes;for(const y in u){const p=u[y],{array:f,itemSize:x}=p;f.copyWithin(e*x,l*x,(l+m)*x),p.addUpdateRange(e*x,m*x)}h.vertexStart=e}e+=h.reservedVertexCount,h.start=s.index?h.indexStart:h.vertexStart,this._nextIndexStart=s.index?h.indexStart+h.reservedIndexCount:0,this._nextVertexStart=h.vertexStart+h.reservedVertexCount}}return this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingBox===null){const s=new d.Box3,r=i.index,o=i.attributes.position;for(let a=n.start,h=n.start+n.count;a<h;a++){let l=a;r&&(l=r.getX(l)),s.expandByPoint(X.fromBufferAttribute(o,l))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingSphere===null){const s=new d.Sphere;this.getBoundingBoxAt(e,Ke),Ke.getCenter(s.center);const r=i.index,o=i.attributes.position;let a=0;for(let h=n.start,l=n.start+n.count;h<l;h++){let m=h;r&&(m=r.getX(m)),X.fromBufferAttribute(o,m),a=Math.max(a,s.center.distanceToSquared(X))}s.radius=Math.sqrt(a),n.boundingSphere=s}return t.copy(n.boundingSphere),t}setVisibleAt(e,t){return this.validateGeometryId(e),this._geometryInfo[e].visible===t?this:(this._geometryInfo[e].visible=t,this)}getVisibleAt(e){return this.validateGeometryId(e),this._geometryInfo[e].visible}getGeometryRangeAt(e){return this.validateGeometryId(e),this._geometryInfo[e]}setGeometrySize(e,t){const i=this.geometry;i.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new d.BufferGeometry,this._initializeGeometry(i));const n=this.geometry;i.index&&N(i.index.array,n.index.array);for(const s in i.attributes)N(i.attributes[s].array,n.attributes[s].array)}getObjectAt(e){const t=new d.Mesh;this._initializeRaycastObject(t);const i=this._geometryInfo[e];return this._setRaycastObjectInfo(t,e,i.start,i.count),t}_initializeRaycastObject(e){const t=this.geometry;return e.material=this.material,e.geometry.index=t.index,e.geometry.attributes=t.attributes,e.geometry.boundingBox===null&&(e.geometry.boundingBox=new d.Box3),e.geometry.boundingSphere===null&&(e.geometry.boundingSphere=new d.Sphere),e}_setRaycastObjectInfo(e,t,i,n){e.geometry.setDrawRange(i,n),this.getBoundingBoxAt(t,e.geometry.boundingBox),this.getBoundingSphereAt(t,e.geometry.boundingSphere)}_resetRaycastObjectInfo(e){e.geometry.index=null,e.geometry.attributes={},e.geometry.setDrawRange(0,1/0)}intersectWith(e,t,i){this._initializeRaycastObject($),this._intersectWith(e,t,i),this._resetRaycastObjectInfo($)}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!(!n.visible||!n.active))if(n.bboxIntersectionCheck){const s=n.boundingBox;if(t.ray.intersectBox(s,X)){const r=t.ray.origin.distanceTo(X);i.push({distance:r,point:X.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}}else{this._setRaycastObjectInfo($,e,n.start,n.count),$.raycast(t,me);for(let s=0,r=me.length;s<r;s++){const o=me[s];o.object=this,o.batchId=e,o.objectId=n.objectId,i.push(o)}me.length=0}}raycast(e,t){const i=this._geometryInfo;this._initializeRaycastObject($);for(let n=0,s=i.length;n<s;n++)this._intersectWith(n,e,t);this._resetRaycastObjectInfo($)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this}dispose(){return this.geometry.dispose(),this}}const et=new d.Box3,Y=new d.Vector3,H=new d.Points,ge=[];class Ot extends d.Points{constructor(e=1e3,t){super(new d.BufferGeometry,t),this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextVertexStart=0,this._geometryCount=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxVertexCount=e}get geometryCount(){return this._geometryCount}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get mappingStats(){const e=this._geometryInfo.length;let t=0;return e>0&&(t=ne.estimateObjectSize(this._geometryInfo[0])),{count:e,size:e*t}}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount;if(this._geometryInitialized===!1){for(const n in e.attributes){const s=e.getAttribute(n),{array:r,itemSize:o,normalized:a}=s,h=new r.constructor(i*o),l=new d.BufferAttribute(h,o,a);t.setAttribute(n,l)}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`AcTrBatchedLine: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),s=t.getAttribute(i);if(n.itemSize!==s.itemSize||n.normalized!==s.normalized)throw new Error("AcTrBatchedLine: All attributes must have a consistent itemSize and normalized value.")}}_resizeSpaceIfNeeded(e){const t=e.getAttribute("position");let i=this._maxVertexCount;t&&this.unusedVertexCount<t.count&&(i=(this._maxVertexCount+t.count)*1.5),i>this._maxVertexCount&&this.setGeometrySize(i)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`AcTrBatchedLine: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}reset(){this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextVertexStart=0,this._geometryCount=0,this._geometryInfo.length=0,this._geometryInitialized=!1,this.geometry.dispose()}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new d.Box3);const e=this.boundingBox,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingBox!=null&&e.union(s.boundingBox)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new d.Sphere);const e=this.boundingSphere,t=this._geometryInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){const s=t[i];s.active!==!1&&s.boundingSphere!=null&&e.union(s.boundingSphere)}}addGeometry(e,t=-1){this._initializeGeometry(e),this._validateGeometry(e),e.boundingBox==null&&e.computeBoundingBox(),e.boundingSphere==null&&e.computeBoundingSphere(),this._resizeSpaceIfNeeded(e);const i={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,boundingBox:e.boundingBox,boundingSphere:e.boundingSphere,active:!0,visible:!0},n=this._geometryInfo;i.vertexStart=this._nextVertexStart,i.reservedVertexCount=t===-1?e.getAttribute("position").count:t;let s;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Ae),s=this._availableGeometryIds.shift(),n[s]=i):(s=this._geometryCount,this._geometryCount++,n.push(i)),this.setGeometryAt(s,e),this._nextVertexStart=i.vertexStart+i.reservedVertexCount,this.geometry.setDrawRange(0,this._nextVertexStart),s}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine: Maximum geometry count reached.");const i=this._geometryInfo[e],n=t.position;n&&(i.position={...n}),i.objectId=t.objectId,i.bboxIntersectionCheck=t.bboxIntersectionCheck}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=this._geometryInfo[e],s=n.vertexStart,r=n.reservedVertexCount;n.vertexCount=t.getAttribute("position").count;for(const o in i.attributes){const a=t.getAttribute(o),h=i.getAttribute(o);Be(a,h,s);const l=a.itemSize;for(let m=a.count,u=r;m<u;m++){const y=s+m;for(let p=0;p<l;p++)h.setComponent(y,p,0)}h.needsUpdate=!0,h.addUpdateRange(s*l,r*l)}return n.boundingBox=null,t.boundingBox!==null&&(n.boundingBox=t.boundingBox.clone()),n.boundingSphere=null,t.boundingSphere!==null&&(n.boundingSphere=t.boundingSphere.clone()),e}deleteGeometry(e){const t=this._geometryInfo;return e>=t.length||t[e].active===!1?this:(t[e].active=!1,this._availableGeometryIds.push(e),this)}optimize(){let e=0;const t=this._geometryInfo,i=t.map((s,r)=>r).sort((s,r)=>t[s].vertexStart-t[r].vertexStart),n=this.geometry;for(let s=0,r=t.length;s<r;s++){const o=i[s],a=t[o];if(a.active!==!1){if(a.vertexStart!==e){const{vertexStart:h,reservedVertexCount:l}=a,m=n.attributes;for(const u in m){const y=m[u],{array:p,itemSize:f}=y;p.copyWithin(e*f,h*f,(h+l)*f),y.addUpdateRange(e*f,l*f)}a.vertexStart=e}e+=a.reservedVertexCount,this._nextVertexStart=a.vertexStart+a.reservedVertexCount}}return this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingBox===null){const s=new d.Box3,r=i.index,o=i.attributes.position;for(let a=n.vertexStart,h=n.vertexStart+n.vertexCount;a<h;a++){let l=a;r&&(l=r.getX(l)),s.expandByPoint(Y.fromBufferAttribute(o,l))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingSphere===null){const s=new d.Sphere;this.getBoundingBoxAt(e,et),et.getCenter(s.center);const r=i.index,o=i.attributes.position;let a=0;for(let h=n.vertexStart,l=n.vertexStart+n.vertexCount;h<l;h++){let m=h;r&&(m=r.getX(m)),Y.fromBufferAttribute(o,m),a=Math.max(a,s.center.distanceToSquared(Y))}s.radius=Math.sqrt(a),n.boundingSphere=s}return t.copy(n.boundingSphere),t}setVisibleAt(e,t){return this.validateGeometryId(e),this._geometryInfo[e].visible===t?this:(this._geometryInfo[e].visible=t,this)}getVisibleAt(e){return this.validateGeometryId(e),this._geometryInfo[e].visible}getGeometryAt(e){return this.validateGeometryId(e),this._geometryInfo[e]}setGeometrySize(e){const t=this.geometry;t.dispose(),this._maxVertexCount=e,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new d.BufferGeometry,this._initializeGeometry(t));const i=this.geometry;t.index&&N(t.index.array,i.index.array);for(const n in t.attributes)N(t.attributes[n].array,i.attributes[n].array)}getObjectAt(e){const t=new d.Points;this._initializeRaycastObject(t);const i=this._geometryInfo[e];return this._setRaycastObjectInfo(t,e,i.vertexStart,i.vertexCount),t}_initializeRaycastObject(e){const t=this.geometry;return e.material=this.material,e.geometry.index=t.index,e.geometry.attributes=t.attributes,e.geometry.boundingBox===null&&(e.geometry.boundingBox=new d.Box3),e.geometry.boundingSphere===null&&(e.geometry.boundingSphere=new d.Sphere),e}_setRaycastObjectInfo(e,t,i,n){e.geometry.setDrawRange(i,n),this.getBoundingBoxAt(t,e.geometry.boundingBox),this.getBoundingSphereAt(t,e.geometry.boundingSphere)}_resetRaycastObjectInfo(e){e.geometry.index=null,e.geometry.attributes={},e.geometry.setDrawRange(0,1/0)}intersectWith(e,t,i){this._initializeRaycastObject(H),this._intersectWith(e,t,i),this._resetRaycastObjectInfo(H)}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!(!n.visible||!n.active))if(n.bboxIntersectionCheck){const s=n.boundingBox;if(t.ray.intersectBox(s,Y)){const r=t.ray.origin.distanceTo(Y);i.push({distance:r,point:Y.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}}else{this._setRaycastObjectInfo(H,e,n.vertexStart,n.vertexCount),H.raycast(t,ge);for(let s=0,r=ge.length;s<r;s++){const o=ge[s];o.object=this,o.batchId=e,o.objectId=n.objectId,i.push(o)}ge.length=0}}raycast(e,t){const i=this._geometryInfo;this._initializeRaycastObject(H);for(let n=0,s=i.length;n<s;n++)this._intersectWith(n,e,t);this._resetRaycastObjectInfo(H)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._maxVertexCount=e._maxVertexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this}dispose(){return this.geometry.dispose(),this}}class Gt extends d.Group{constructor(){super(),this._pointBatches=new Map,this._pointSymbolBatches=new Map,this._lineBatches=new Map,this._lineWithIndexBatches=new Map,this._meshBatches=new Map,this._meshWithIndexBatches=new Map,this._entitiesMap=new Map,this._selectedObjects=new d.Group,this._hoverObjects=new d.Group,this.add(this._selectedObjects),this.add(this._hoverObjects)}get entityCount(){return this._entitiesMap.size}get stats(){const e={summary:{entityCount:this._entitiesMap.size,totalGeometrySize:0,totalMappingSize:0},mesh:{indexed:{count:this._meshWithIndexBatches.size,geometrySize:this.getBatchedGeometrySize(this._meshWithIndexBatches),mappingSize:this.getBatchedGeometryMappingSize(this._meshWithIndexBatches)},nonIndexed:{count:this._meshBatches.size,geometrySize:this.getBatchedGeometrySize(this._meshBatches),mappingSize:this.getBatchedGeometryMappingSize(this._meshBatches)}},line:{indexed:{count:this._lineWithIndexBatches.size,geometrySize:this.getBatchedGeometrySize(this._lineWithIndexBatches),mappingSize:this.getBatchedGeometryMappingSize(this._lineWithIndexBatches)},nonIndexed:{count:this._lineBatches.size,geometrySize:this.getBatchedGeometrySize(this._lineBatches),mappingSize:this.getBatchedGeometryMappingSize(this._lineBatches)}},point:{indexed:{count:this._pointSymbolBatches.size,geometrySize:this.getBatchedGeometrySize(this._pointSymbolBatches),mappingSize:this.getBatchedGeometryMappingSize(this._pointSymbolBatches)},nonIndexed:{count:this._pointBatches.size,geometrySize:this.getBatchedGeometrySize(this._pointBatches),mappingSize:this.getBatchedGeometryMappingSize(this._pointBatches)}}};return e.summary.totalGeometrySize=e.line.indexed.geometrySize+e.line.nonIndexed.geometrySize+e.mesh.indexed.geometrySize+e.mesh.nonIndexed.geometrySize+e.point.indexed.geometrySize+e.point.nonIndexed.geometrySize,e.summary.totalMappingSize=e.line.indexed.mappingSize+e.line.nonIndexed.mappingSize+e.mesh.indexed.mappingSize+e.mesh.nonIndexed.mappingSize+e.point.indexed.mappingSize+e.point.nonIndexed.mappingSize,e}rerenderPoints(e){const t=R.instance.create(e);t.line&&this._pointSymbolBatches.forEach(n=>{n.resetGeometry(e)});const i=t.point!=null;this._pointBatches.forEach(n=>{n.visible=i})}clear(){return this.clearPoint(),this.clearLine(),this.clearMesh(),this}clearPoint(){this.clearBatch(this._pointBatches),this.clearBatch(this._pointSymbolBatches)}clearLine(){this.clearBatch(this._lineBatches),this.clearBatch(this._lineWithIndexBatches)}clearMesh(){this.clearBatch(this._meshBatches),this.clearBatch(this._meshWithIndexBatches)}hasEntity(e){return this._entitiesMap.has(e)}addEntity(e){const t=[];this._entitiesMap.set(e.objectId,t),e.updateMatrixWorld(!0),e.traverse(i=>{const n=!!i.userData.bboxIntersectionCheck;i instanceof d.LineSegments?t.push(this.addLine(i,{position:i.userData.position,objectId:e.objectId,bboxIntersectionCheck:n})):i instanceof d.Mesh?t.push(this.addMesh(i,{objectId:e.objectId,bboxIntersectionCheck:n})):i instanceof d.Points&&t.push(this.addPoint(i,{objectId:e.objectId,bboxIntersectionCheck:n}))})}isIntersectWith(e,t){const i=this._entitiesMap.get(e);if(i){const n=[];for(let s=0,r=i.length;s<r;s++){const o=i[s];if(this.getObjectById(o.batchedObjectId).intersectWith(o.batchId,t,n),n.length>0)return!0}}return!1}hover(e){this.highlight(e,this._hoverObjects)}unhover(e){this.unhighlight(e,this._hoverObjects)}select(e){this.highlight(e,this._selectedObjects)}unselect(e){this.unhighlight(e,this._selectedObjects)}highlight(e,t){const i=this._entitiesMap.get(e);i&&i.forEach(n=>{const s=this.getObjectById(n.batchedObjectId).getObjectAt(n.batchId),r=de.cloneMaterial(s.material);de.setMaterialColor(r),s.material=r,s.userData.objectId=e,t.add(s)})}unhighlight(e,t){const i=[];t.children.forEach(n=>{n.userData.objectId===e&&i.push(n)}),t.remove(...i)}addLine(e,t){const i=e.material,n=this.getMatchedLineBatches(e);let s=n.get(i.id);s==null&&(s=new zt(1e3,2e3,i),n.set(i.id,s),this.add(s)),e.geometry.applyMatrix4(e.matrixWorld);const r=s.addGeometry(e.geometry);return s.setGeometryInfo(r,t),{batchedObjectId:s.id,batchId:r}}addMesh(e,t){const i=e.material,n=this.getMatchedMeshBatches(e);let s=n.get(i.id);s==null&&(s=new Pt(1e3,2e3,i),n.set(i.id,s),this.add(s)),e.geometry.applyMatrix4(e.matrixWorld);const r=s.addGeometry(e.geometry);return s.setGeometryInfo(r,t),{batchedObjectId:s.id,batchId:r}}addPoint(e,t){const i=e.material;let n=this._pointBatches.get(i.id);n==null&&(n=new Ot(100,i),n.visible=e.visible,this._pointBatches.set(i.id,n),this.add(n)),e.geometry.applyMatrix4(e.matrixWorld);const s=n.addGeometry(e.geometry);return n.setGeometryInfo(s,t),{batchedObjectId:n.id,batchId:s}}getMatchedLineBatches(e){if(e.userData.isPoint)return this._pointSymbolBatches;{const t=e.geometry.getIndex()!==null;let i=this._lineBatches;return t&&(i=this._lineWithIndexBatches),i}}getMatchedMeshBatches(e){const t=e.geometry.getIndex()!==null;let i=this._meshBatches;return t&&(i=this._meshWithIndexBatches),i}clearBatch(e){e.forEach(t=>{t.dispose()}),e.clear()}getBatchedGeometrySize(e){let t=0;return e.forEach(i=>{t+=this.getGeometrySize(i)}),t}getBatchedGeometryMappingSize(e){let t=0;return e.forEach(i=>{t+=i.mappingStats.size}),t}getGeometrySize(e){let t=0;if("geometry"in e){const i=e.geometry;i.attributes.position&&(t+=i.attributes.position.array.byteLength),i.attributes.normal&&(t+=i.attributes.normal.array.byteLength),i.attributes.uv&&(t+=i.attributes.uv.array.byteLength),i.index&&(t+=i.index.array.byteLength)}return t}}class tt extends le{constructor(e){super(),this._styleManager=e}get styleManager(){return this._styleManager}copy(e,t){return this._styleManager=e._styleManager,super.copy(e,t)}}class E extends tt{constructor(e){super(e),this._objectId="",this._ownerId="",this._layerName="",this._box=new d.Box3}get box(){return this._box}set box(e){this._box.copy(e)}get objectId(){return this._objectId}set objectId(e){this._objectId=e}get ownerId(){return this._ownerId}set ownerId(e){this._ownerId=e}get layerName(){return this._layerName}set layerName(e){this._layerName=e}async draw(){}applyMatrix(e){const t=e.elements,i=new d.Matrix4(t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13],t[2],t[6],t[10],t[14],t[3],t[7],t[11],t[15]);this.applyMatrix4(i),this.updateMatrixWorld(!0),this._box.applyMatrix4(i)}highlight(){this.highlightObject(this)}highlightObject(e){if("material"in e){const t=e.material;if(e.userData.originalMaterial==null){const i=de.cloneMaterial(t);de.setMaterialColor(i),e.userData.originalMaterial=e.material,e.material=i}}else e.children.length>0&&e.children.forEach(t=>{this.highlightObject(t)})}unhighlight(){this.unhighlightObject(this)}fastDeepClone(){const e=new E(this.styleManager);return e.copy(this,!1),this.copyGeometry(this,e),e}copy(e,t){return this.objectId=e.objectId,this.ownerId=e.ownerId,this.layerName=e.layerName,this.box=e.box,super.copy(e,t)}copyGeometry(e,t){for(let i=0;i<e.children.length;i++){const n=e.children[i].clone(!1);"geometry"in n&&(n.geometry=n.geometry.clone()),t.add(n)}}unhighlightObject(e){if("material"in e){const t=e.material;e.material=e.userData.originalMaterial,delete e.userData.originalMaterial,Array.isArray(t)?t.forEach(i=>i.dispose()):t instanceof d.Material&&t.dispose()}else e.children.length>0&&e.children.forEach(t=>{this.unhighlightObject(t)})}createColorArray(e,t){const i=(e>>16&255)/256,n=(e>>8&255)/256,s=(e&255)/256,r=new Float32Array(t*3);for(let o=0,a=0;o<t;o++)r[a]=i,r[a+1]=n,r[a+2]=s,a+=3;return r}}const it=class K{constructor(){}static getInstance(){return K._instance||(K._instance=new K),K._instance}async asyncRenderMText(e,t,i={byLayerColor:16777215,byBlockColor:16777215}){if(!this._renderer)throw new Error("AcTrMTextRenderer not initialized!");const n=this._renderer.getMode();this._renderer.switchMode("main");const s=await this._renderer.asyncRenderMText(e,t,i);return this._renderer.switchMode(n),s}syncRenderMText(e,t,i={byLayerColor:16777215,byBlockColor:16777215}){if(!this._renderer)throw new Error("AcTrMTextRenderer not initialized!");const n=this._renderer.getMode();this._renderer.switchMode("main");const s=this._renderer.syncRenderMText(e,t,i);return this._renderer.switchMode(n),s}initialize(e){this._renderer=new V.UnifiedRenderer("main",{workerUrl:e})}dispose(){this._renderer&&(this._renderer.destroy(),this._renderer=void 0),K._instance=null}};it._instance=null;let pe=it;class Rt extends E{constructor(e,t){super(t),e.forEach(i=>{if(Array.isArray(i)){const n=new E(t);this.add(n),this.box.union(n.box)}else this.add(i),this.box.union(i.box)}),this.flatten()}}class Vt extends E{constructor(e,t,i){super(i);const n=URL.createObjectURL(e),s=new d.TextureLoader().load(n);s.colorSpace=d.SRGBColorSpace;const r=new d.MeshBasicMaterial({side:d.DoubleSide,map:s}),o=new d.Shape(t.boundary),a=new d.ShapeGeometry(o);this.generateUVs(a);const h=new d.Mesh(a,r);this.add(h)}generateUVs(e){const t=e.attributes.position.array,i=new Float32Array(t.length/3*2),n=Math.min(...t.filter((l,m)=>m%3===0)),s=Math.max(...t.filter((l,m)=>m%3===0)),r=Math.min(...t.filter((l,m)=>m%3===1)),o=Math.max(...t.filter((l,m)=>m%3===1)),a=s-n,h=o-r;for(let l=0;l<t.length;l+=3){const m=t[l],u=t[l+1];i[l/3*2]=(m-n)/a,i[l/3*2+1]=(u-r)/h}e.setAttribute("uv",new d.BufferAttribute(i,2))}}const ye=new d.Vector3,fe=new d.Vector3;class se{static release(e){e.index=null,e.attributes={}}static toNonIndexed(e){if(!e.index)return e;const t=new d.BufferGeometry,i=e.index;for(const n in e.attributes)t.setAttribute(n,se.createGeometryAttributeByIndex(e.attributes[n],i));return t}static createGeometryAttributeByIndex(e,t){const i=t.count,n=e.itemSize,s=e.array.constructor,r=new s(i*n);for(let o=0;o<i;o++){const a=t.getX(o)*n;for(let h=0;h<n;h++)r[o*n+h]=e.array[a+h]}return new d.BufferAttribute(r,n,e.normalized)}static tryConvertInterleavedBufferAttributes(e){!e||!e.attributes||Object.keys(e.attributes).forEach(t=>{const i=e.attributes[t];if(i instanceof d.InterleavedBufferAttribute){const n=i.clone();e.attributes[t]=n}})}static createBufferGeometryByPoints(e){const t=new d.BufferGeometry,i=new Float32Array(e.length*3),n=new Uint16Array((e.length-1)*2);return e.forEach((s,r)=>{let o=r*3;i[o]=s.x,i[o+1]=s.y,i[o+2]=s.z,r>0&&(o=(r-1)*2,n[o]=r-1,n[o+1]=r)}),t.setAttribute("position",new d.Float32BufferAttribute(i,3)),t.setIndex(new d.Uint16BufferAttribute(n,1)),t}static computeLineDistance(e){const t=e.isLineSegments===!0;let i=e.geometry;const n=e.matrixWorld;if(i.index&&(i=se.toNonIndexed(i)),i.index===null){const s=i.attributes.position;if(!s||s.count===0)return;const r=[];if(t)for(let o=0,a=s.count;o<a;o+=2)ye.fromBufferAttribute(s,o).applyMatrix4(n),fe.fromBufferAttribute(s,o+1).applyMatrix4(n),r[o]=o===0?0:r[o-1],r[o+1]=r[o]+ye.distanceTo(fe);else{r[0]=0;for(let o=1,a=s.count;o<a;o++)ye.fromBufferAttribute(s,o-1).applyMatrix4(n),fe.fromBufferAttribute(s,o).applyMatrix4(n),r[o]=r[o-1],r[o]+=ye.distanceTo(fe)}i.setAttribute("lineDistance",new d.Float32BufferAttribute(r,1)),e.geometry.dispose(),e.geometry=i}}static computeLineDistances(e){e.traverse(t=>{let i=t;i.isLine&&i.material instanceof d.ShaderMaterial&&this.computeLineDistance(i)})}static apply2dTransform(e,t,i=0,n=1){const s=e.attributes.position,r=s.itemSize,o=s.array;if(i!=0){const a=Math.cos(i),h=Math.sin(i);for(let l=0;l<o.length;l+=r){const m=o[l],u=o[l+1],y=m*a-u*h,p=m*h+u*a;o[l]=y*n+t.x,o[l+1]=p*n+t.y}}else for(let a=0;a<o.length;a+=r)o[a]=o[a]*n+t.x,o[a+1]+=o[a+1]*n+t.y;return s.needsUpdate=!0,e}static apply3dTransform(e,t,i){const n=e.attributes.position,s=n.itemSize,r=n.array,o=Math.cos(i.x),a=Math.sin(i.x),h=Math.cos(i.y),l=Math.sin(i.y),m=Math.cos(i.z),u=Math.sin(i.z);for(let y=0;y<r.length;y+=s){let p=r[y],f=r[y+1],x=r[y+2],b=f*o-x*a,_=f*a+x*o;f=b,x=_;let S=p*h+x*l;_=-p*l+x*h,p=S,x=_,S=p*m-f*u,b=p*u+f*m,p=S,f=b,r[y]=p+t.x,r[y+1]=f+t.y,r[y+2]=x+t.z}return n.needsUpdate=!0,e}}class jt extends E{constructor(e,t,i){super(i);let n;const s=t?t.color:16777215;t?n=this.styleManager.getLineShaderMaterial(t,1):n=new d.LineBasicMaterial({color:s});const r=e.length,o=new Float32Array(r*3),a=r*2>65535?new Uint32Array(r*2):new Uint16Array(r*2);for(let m=0,u=0;m<r;m++){const y=e[m];o[u++]=y.x,o[u++]=y.y,o[u++]=y.z??0}for(let m=0,u=0;m<r-1;m++)a[u++]=m,a[u++]=m+1;const h=new d.BufferGeometry;h.setAttribute("position",new d.BufferAttribute(o,3)),h.setIndex(new d.BufferAttribute(a,1)),this.setBoundingBox(h),this.geometry=h;const l=new d.LineSegments(h,n);se.computeLineDistances(l),this.add(l)}setBoundingBox(e){e.computeBoundingBox(),this.box=e.boundingBox}}class kt extends E{constructor(e,t,i,n,s){super(s);let r;n?r=this.styleManager.getLineShaderMaterial(n,1):r=new d.LineBasicMaterial({color:16777215});const o=new d.BufferGeometry;o.setAttribute("position",new d.BufferAttribute(e,t)),o.setIndex(new d.BufferAttribute(i,1)),o.computeBoundingBox(),this.box=o.boundingBox;const a=new d.LineSegments(o,r);se.computeLineDistances(a),this.add(a)}}class Ft extends E{constructor(e,t,i,n=!1){super(i),this._text=e,this._style=t,n||this.syncDraw()}async syncDraw(){const e=pe.getInstance();if(e)try{const t=this._style;this._mtext=e.syncRenderMText(this._text,t,{byLayerColor:t.byLayerColor,byBlockColor:t.byBlockColor}),this.add(this._mtext),this.flatten(),this.traverse(i=>{i.userData.bboxIntersectionCheck=!0})}catch(t){console.log(`Failed to render mtext '${this._text.text}' with the following error:
26
+ `,t)}}async draw(){const e=pe.getInstance();if(e)try{const t=this._style;this._mtext=await e.asyncRenderMText(this._text,t,{byLayerColor:t.byLayerColor,byBlockColor:t.byBlockColor}).then(i=>{this._mtext=i,this.add(this._mtext),this.flatten(),this.traverse(n=>{n.userData.bboxIntersectionCheck=!0})})}catch(t){console.log(`Failed to render mtext '${this._text.text}' with the following error:
27
+ `,t)}}raycast(e,t){var i;(i=this._mtext)==null||i.raycast(e,t)}getTextEncoding(e){return e!=null&&e.bigFont&&e.bigFont.toUpperCase().startsWith("GB")?"gbk":"utf8"}}const Nt=new d.Vector3;class Ut extends E{constructor(e,t,i){super(i);const n=R.instance.create(t.displayMode,e);this.isShowPoint=n.point!=null;const s=n.point??new d.BufferGeometry().setFromPoints([Nt.copy(e)]);s.computeBoundingBox(),s.boundingBox&&this.box.union(s.boundingBox);const r=this.styleManager.getPointsMaterial(t.color),o=new d.Points(s,r);if(o.userData.bboxIntersectionCheck=!0,o.visible=this.isShowPoint,this.add(o),n.line){const a=n.line;a.computeBoundingBox(),a.boundingBox&&this.box.union(a.boundingBox);const h=this.styleManager.getLineBasicMaterial(t.color),l=new d.LineSegments(a,h);l.userData.bboxIntersectionCheck=!0,l.userData.isPoint=!0,l.userData.position={x:e.x,y:e.y,z:e.z},this.add(l)}}}class Wt extends E{constructor(e,t,i){var n;super(i);const s=e.getPoints(100),r=e.buildHierarchy(),o=[];this.buildHatchGeometry(s,r,o);let a;if(o.length>0&&(a=dt.mergeGeometries(o)),!a||!a.getIndex()||((n=a.getIndex())==null?void 0:n.count)===0)console.warn("Failed to convert hatch boundaries!");else{a.computeBoundingBox(),this.box=a.boundingBox;const h=this.styleManager.getHatchShaderMaterial(t,new d.Vector2(0,0));this.add(new d.Mesh(a,h))}}buildHatchGeometry(e,t,i){if(t.children.length===0)return;const n=[],s=new Map;t.children.forEach(a=>{a.children.length===0?n.push(a.index):s.set(a.index,a.children.map(h=>h.index))});const r=a=>{try{const h=new d.ShapeGeometry(a);h.hasAttribute("uv")&&h.deleteAttribute("uv"),h.hasAttribute("normal")&&h.deleteAttribute("normal"),i.push(h)}catch{console.warn(`Triangulate shape error: ${a.getPoints().map(h=>h.toArray()).toString()}`)}};n.forEach(a=>{const h=e[a];if(h.length===0)return;const l=new d.Shape(h);r(l)});const o=a=>a.map(h=>h.toArray());for(const a of s){const h=new d.Shape(e[a[0]]);let l={regions:[],inverted:!1};const m=this.findIntersectHole(e,a[1]);m.forEach(y=>{let p={segments:[],inverted:!1},f=1e-6;try{y.forEach((x,b)=>{f=Math.min(e[x][0].relativeEps(),1e-6);const _=new Qe(new $e(f));if(b===0)p=_.segments({regions:[o(e[x])],inverted:!1});else{const S=_.segments({regions:[o(e[x])],inverted:!1}),v=_.combine(p,S);l=_.polygon(_.selectUnion(v)),l.regions.length>0?l.regions.forEach(A=>{if(A.length===0)return;const O=A.map(I=>new d.Vector2(I[0],I[1]));h.holes.push(new d.Path(O))}):console.warn("mergedHoles.regions is empty!")}})}catch(x){console.warn(`Polybool error: ${x}, epsilon is ${f}`)}});const u=m.flat(2);for(let y=0;y<a[1].length;y++){const p=a[1][y];u.includes(p)||h.holes.push(new d.Path(e[p]))}r(h)}t.children.forEach(a=>{a.children.forEach(h=>{this.buildHatchGeometry(e,h,i)})})}findIntersectHole(e,t){const i=t.length,n=[];for(let s=0;s<i;s++){const r=e[t[s]];let o=!1;const a=[];for(let h=s+1;h<i;h++){const l=e[t[h]];g.AcGeGeometryUtil.isPolygonIntersect(r,l)&&(o=!0,a.push(t[h]))}o&&(a.push(t[s]),n.push(a))}return n}}function Xt(c,e,t,i,n=0){const s={u_cameraZoom:t,u_patternLines:{value:c},u_patternAngle:{value:e},u_color:{value:i}},r=`
27
28
  varying vec3 v_pos;
28
29
 
29
30
  #include <clipping_planes_pars_vertex>
@@ -223,7 +224,7 @@
223
224
  gl_FragColor = vec4(u_color * total, 1.0);
224
225
  #include <colorspace_fragment>
225
226
  }
226
- `;return new u.ShaderMaterial({uniforms:s,vertexShader:r,fragmentShader:o,clipping:!0})}class $t{static createLineShaderMaterial(e,t,i,n,s){let r=0;const o=[];for(let m=0;m<e.length;m++)o[m]=e[m].elementLength*i,r+=Math.abs(o[m]);for(let m=0;m<o.length;m++)o[m]===0&&(o[m]=r*.01*i,r+=o[m]);const a=u.UniformsUtils.merge([u.UniformsLib.common,{pattern:{value:o},patternLength:{value:r},u_color:{value:new u.Color(t)}}]);a.u_viewportScale=n,a.u_cameraZoom=s;const h=`
227
+ `;return new d.ShaderMaterial({uniforms:s,vertexShader:r,fragmentShader:o,clipping:!0})}class $t{static createLineShaderMaterial(e,t,i,n,s){let r=0;const o=[];for(let m=0;m<e.length;m++)o[m]=e[m].elementLength*i,r+=Math.abs(o[m]);for(let m=0;m<o.length;m++)o[m]===0&&(o[m]=r*.01*i,r+=o[m]);const a=d.UniformsUtils.merge([d.UniformsLib.common,{pattern:{value:o},patternLength:{value:r},u_color:{value:new d.Color(t)}}]);a.u_viewportScale=n,a.u_cameraZoom=s;const h=`
227
228
  attribute float lineDistance;
228
229
  varying float vLineDistance;
229
230
 
@@ -278,4 +279,4 @@
278
279
  }
279
280
  }
280
281
  #include <colorspace_fragment>
281
- }`;return new u.ShaderMaterial({uniforms:a,vertexShader:h,fragmentShader:l,clipping:!0})}}const fe=class ce{constructor(){this.pointMaterials={},this.lineShaderMaterials={},this.lineBasicMaterials={},this.hatchShaderMaterials=[],this.meshBasicMaterials={},this.unsupportedTextStyles={}}getPointsMaterial(e,t=2){const i=`${e}_${t}`;return this.pointMaterials[i]||(this.pointMaterials[i]=new u.PointsMaterial({size:t,color:e})),this.pointMaterials[i]}getMeshBasicMaterial(e){return this.meshBasicMaterials[e]||(this.meshBasicMaterials[e]=new u.MeshBasicMaterial({color:e})),this.meshBasicMaterials[e]}getLineBasicMaterial(e){return this.lineBasicMaterials[e]||(this.lineBasicMaterials[e]=new u.LineBasicMaterial({color:e})),this.lineBasicMaterials[e]}getLineShaderMaterial(e,t){if(e.pattern&&e.pattern.length!==0){const i=`${e.name}_${e.color}_${t}`;return this.lineShaderMaterials[i]||(this.lineShaderMaterials[i]=$t.createLineShaderMaterial(e.pattern,e.color,t,ce.ViewportScaleUniform,ce.CameraZoomUniform)),this.lineShaderMaterials[i]}else return this.getLineBasicMaterial(e.color)}getHatchShaderMaterial(e,t){if(!e.patternLines||e.patternLines.length<1)return this.getMeshBasicMaterial(e.color);let i=!1;if(e.patternLines.forEach(d=>{d.dashPattern||(i=!0,console.log("Invalid dash pattern: ",e))}),i)return;const n=this.findMatchedHatchShaderMaterial(e);if(n)return n;const s=.005,r=.05;let o=2;e.patternLines.forEach(d=>{o=Math.max(d.dashPattern.length,o)});let a=0;const h=[],l=new u.Vector2;for(const d of e.patternLines){const y=new u.Vector2(d.origin.x,d.origin.y).sub(t).rotateAround(l,-u.MathUtils.degToRad(e.patternAngle)),p=new u.Vector2(d.delta.x,d.delta.y).rotateAround(l,-u.MathUtils.degToRad(d.angle));if(p.y===0){console.warn("delta.y is equal to zero!");return}const f=d.dashPattern.length;let x=!0,b=0;for(let I=0;I<f;++I){const J=d.dashPattern[I];J>0&&(x=!1),b+=Math.abs(J)}const _=x?r:s,S=[],v=[];let A=0;v[0]=A;for(let I=0;I<f;++I)S[I]=d.dashPattern[I],S[I]===0&&(S[I]=_*b),A+=Math.abs(S[I]),v[I+1]=A;for(let I=f;I<o;++I)S[I]=0;for(let I=v.length;I<o+1;++I)v[I]=A;const O={origin:y,delta:p,angle:d.angle-e.patternAngle,pattern:S,patternSum:v,patternLength:A};if(a+=4,a+=o,a+=o+1,a>ce.MaxFragmentUniforms){console.warn("There will be warning in fragment shader when number of uniforms exceeds 1024, so extra hatch line patterns are ignored here!");break}h.push(O)}const m=Xt(h,e.patternAngle,ce.CameraZoomUniform,new u.Color(e.color));return m.defines={MAX_PATTERN_SEGMENT_COUNT:o},this.hatchShaderMaterials.push({patternLines:e.patternLines,patternAngle:e.patternAngle,color:e.color,material:m}),m}findMatchedHatchShaderMaterial(e){const t=e.patternLines;if(!t||t.length<1)return;const i=(a,h)=>Math.abs(a-h)<1e-5,n=(a,h)=>{if(a.length!==h.length)return!1;for(let l=0;l<a.length;++l)if(!i(a[l],h[l]))return!1;return!0},s=(a,h)=>i(a.angle,h.angle)&&i(a.delta.x,h.delta.x)&&i(a.delta.y,h.delta.y)&&i(a.origin.x,h.origin.x)&&i(a.origin.y,h.origin.y)&&n(a.dashPattern,h.dashPattern),r=(a,h)=>{if(a.length!==h.length)return!1;for(let l=0;l<a.length;++l)if(!s(a[l],h[l]))return!1;return!0},o=this.hatchShaderMaterials.find(a=>a.color===e.color&&a.patternAngle===e.patternAngle&&r(a.patternLines,t));return o==null?void 0:o.material}};fe.CameraZoomUniform={value:1},fe.ViewportScaleUniform={value:1},fe.MaxFragmentUniforms=1024;let Yt=fe;class Ht{constructor(e){this.events={fontNotFound:new g.AcCmEventManager},this._renderer=e,this._styleManager=new Yt,V.FontManager.instance.events.fontNotFound.addEventListener(t=>{this.events.fontNotFound.dispatch(t)})}get autoClear(){return this._renderer.autoClear}set autoClear(e){this._renderer.autoClear=e}get domElement(){return this._renderer.domElement}setSize(e,t){this._renderer.setSize(e,t)}getViewport(e){return this._renderer.getViewport(e)}setViewport(e,t,i,n){this._renderer.setViewport(e,t,i,n)}clear(){this._renderer.clear()}clearDepth(){this._renderer.clearDepth()}render(e,t){this._renderer.render(e,t.internalCamera)}setClearColor(e,t){this._renderer.setClearColor(e,t)}getClearColor(){const e=new u.Color;return this._renderer.getClearColor(e),e.getHex()}setClearAlpha(e){this._renderer.setClearAlpha(e)}getClearAlpha(){return this._renderer.getClearAlpha()}get internalRenderer(){return this._renderer}async loadFonts(e){return await V.FontManager.instance.loadFontsByUrls(e)}setFontMapping(e){V.FontManager.instance.setFontMapping(e)}get missedFonts(){return V.FontManager.instance.missedFonts}clearMissedFonts(){V.FontManager.instance.missedFonts={}}createObject(){return new tt(this._styleManager)}createEntity(){return new E(this._styleManager)}group(e){return new Rt(e,this._styleManager)}point(e,t){return new Ut(e,t,this._styleManager)}circularArc(e,t){return this.linePoints(e.getPoints(100),t)}ellipticalArc(e,t){return this.linePoints(e.getPoints(100),t)}lines(e,t){return this.linePoints(e,t)}lineSegments(e,t,i,n){return new kt(e,t,i,n,this._styleManager)}area(e,t){return new Wt(e,t,this._styleManager)}mtext(e,t){return new Ft(e,t,this._styleManager)}image(e,t){return new Vt(e,t,this._styleManager)}linePoints(e,t=void 0){return new jt(e,t,this._styleManager)}}class qt{constructor(e){this._camera=e}get position(){return this._camera.position}get left(){return this._camera.left}set left(e){this._camera.left=e}get right(){return this._camera.right}set right(e){this._camera.right=e}get top(){return this._camera.top}set top(e){this._camera.top=e}get bottom(){return this._camera.bottom}set bottom(e){this._camera.bottom=e}get zoom(){return this._camera.zoom}set zoom(e){this._camera.zoom=e}get internalCamera(){return this._camera}lookAt(e){this._camera.lookAt(e)}setRotationFromEuler(e){this._camera.setRotationFromEuler(e)}updateProjectionMatrix(){this._camera.updateProjectionMatrix()}cwcs2Wcs(e,t,i){const n=new u.Vector3(e.x,e.y,0);n.x=e.x/t*2-1,n.y=-(e.y/i)*2+1;const s=n.unproject(this._camera);return new g.AcGePoint2d(s.x,s.y)}wcs2Cwcs(e,t,i){const n=new u.Vector3(e.x,e.y,0).project(this._camera);return new g.AcGePoint2d((n.x+1)/2*t,(-n.y+1)/2*i)}wcs2Ndc(e,t,i){const n=this.wcs2Cwcs(e,t,i);return this.cwcs2Ndc(n,t,i)}cwcs2Ndc(e,t,i){return new g.AcGePoint2d(e.x/t*2-1,-(e.y/i)*2+1)}}class nt{constructor(e,t,i){this._frustum=400,this.events={viewChanged:new g.AcCmEventManager},this._renderer=e,this._width=t,this._height=i;const n=this.createCamera();this._camera=new qt(n),this._cameraControls=this.createCameraControls(),this._cameraControls.addEventListener("change",()=>{this.events.viewChanged.dispatch({view:this})}),this._raycaster=new u.Raycaster}get width(){return this._width}set width(e){this._width=e}get height(){return this._height}set height(e){this._height=e}get enabled(){return this._cameraControls.enabled}set enabled(e){this._cameraControls.enabled=e}get center(){return this._camera.cwcs2Wcs({x:this._width/2,y:this._height/2},this._width,this._height)}set center(e){this._camera.position.set(e.x,e.y,this._camera.position.z),this._camera.updateProjectionMatrix()}cwcs2Wcs(e){return this._camera.cwcs2Wcs(e,this._width,this._height)}wcs2Cwcs(e){return this._camera.wcs2Cwcs(e,this._width,this._height)}pointToBox(e,t){const i=this.wcs2Cwcs(e),n=this.cwcs2Wcs({x:i.x+t,y:i.y+t}),s=this.cwcs2Wcs({x:i.x-t,y:i.y-t});return new g.AcGeBox2d().setFromPoints([n,s])}resetRaycaster(e,t){const i=this._camera.wcs2Ndc(e,this._width,this._height);return this._raycaster.setFromCamera(new u.Vector2(i.x,i.y),this._camera.internalCamera),this._raycaster.params.Line.threshold=t,this._raycaster.params.Points.threshold=t,this._raycaster}zoomTo(e,t=1.1){const i=new g.AcGeVector2d;e.getSize(i);const n=new g.AcGeVector2d;e.getCenter(n);const s=new u.Vector3(n.x,n.y,0);this._camera.position.set(n.x,n.y,this._camera.position.z),this._camera.lookAt(s),this._camera.setRotationFromEuler(new u.Euler(0,0,0));const r=i.x*t,o=i.y*t,a=this._width/r,h=this._height/o;this._camera.zoom=Math.min(a,h),this._cameraControls.target=s,this.updateCameraFrustum()}updateCameraFrustum(e,t){const i=(e??this._width)/(t??this._height);this._camera.left=-i*this._frustum,this._camera.right=i*this._frustum,this._camera.top=this._frustum,this._camera.bottom=-this._frustum,this._camera.updateProjectionMatrix(),this._cameraControls.update()}createCamera(){const e=new u.OrthographicCamera(-this._width/2,this._width/2,this._height/2,-this._height/2,.1,1e3);return e.position.set(0,0,500),e.up.set(0,1,0),e.updateProjectionMatrix(),e}createCameraControls(){const e=new dt.OrbitControls(this._camera.internalCamera,this._renderer.domElement);return e.enableDamping=!1,e.autoRotate=!1,e.enableRotate=!1,e.zoomSpeed=5,e.mouseButtons={MIDDLE:u.MOUSE.PAN},e.update(),e}}class xe extends nt{static calculateViewportWindowBox(e,t){const i=t.box,n=new g.AcGeBox2d;return n.expandByPoint(e.wcs2Cwcs(i.min)),n.expandByPoint(e.wcs2Cwcs(i.max)),n}constructor(e,t,i){const n=xe.calculateViewportWindowBox(e,t).size;super(i,n.width,n.height),this._parentView=e,this._viewport=t.clone(),this._frustum*=t.height/e.height,this.zoomTo(this._viewport.viewBox),this.enabled=!1}get viewport(){return this._viewport}update(){this.zoomTo(this._viewport.viewBox)}render(e){const t=xe.calculateViewportWindowBox(this._parentView,this._viewport);if(!t.isEmpty()){const i=this._parentView.height-t.min.y-t.size.height;this._renderer.setViewport(t.min.x,i,t.size.width,t.size.height),this._renderer.internalRenderer.setScissor(t.min.x,i,t.size.width,t.size.height),this._renderer.internalRenderer.setScissorTest(!0),this._renderer.render(e,this._camera),this._renderer.internalRenderer.setScissorTest(!1)}}}const Qt={threeBo2dToGeBox2d:c=>new g.AcGeBox2d(c.min,c.max),geBox2dToThreeBox2d:c=>new u.Box2(c.min,c.max),threeBox3dToGeBox3d:c=>new g.AcGeBox3d(c.min,c.max),geBox3dToThreeBox3d:c=>new u.Box3(c.min,c.max),goBox3dToGeBox2d:c=>new g.AcGeBox2d(c.min,c.max),threeBox3dToGeBox2d:c=>new g.AcGeBox2d(c.min,c.max),geBox2dToThreeBox3d:c=>{const e=new u.Box3;return e.min.set(c.min.x,c.min.y,0),e.max.set(c.max.x,c.max.y,0),e}};var _e=(c=>(c[c.LEFT_BOTTOM=0]="LEFT_BOTTOM",c[c.LEFT_TOP=1]="LEFT_TOP",c[c.RIGHT_TOP=2]="RIGHT_TOP",c[c.RIGHT_BOTTOM=4]="RIGHT_BOTTOM",c))(_e||{});class Zt extends u.Object3D{constructor(e,t,i=150,n=2){super(),this.camera=e,this.renderer=t,this.gizmoCamera=new u.OrthographicCamera(-2,2,2,-2,0,4),this.gizmoCamera.position.set(0,0,2),this.gizmoDim=i,this.gizmoPos=n,this.initialize()}initialize(){}update(){this.updateOrientation();const e=this.renderer.autoClear;this.renderer.autoClear=!1,this.renderer.clearDepth();const t=new u.Vector4;this.renderer.getViewport(t);const i=this.calculateViewportPos();this.renderer.setViewport(i.x,i.y,this.gizmoDim,this.gizmoDim),this.renderer.render(this,this.gizmoCamera),this.renderer.setViewport(t.x,t.y,t.z,t.w),this.renderer.autoClear=e}dispose(){}updateOrientation(){this.quaternion.copy(this.camera.quaternion).invert(),this.updateMatrixWorld()}calculatePosInViewport(e,t,i){const n=(e-i.min.x)/this.gizmoDim*2-1,s=-((t-i.min.y)/this.gizmoDim)*2+1;return{x:n,y:s}}calculateViewportPos(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,s=this.gizmoDim;let r=t-s,o=i-s;switch(n){case 0:r=0,o=0;break;case 1:r=0;break;case 4:o=0;break}return{x:r,y:o}}calculateViewportBbox(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,s=this.gizmoDim,r=new u.Box2(new u.Vector2(t-s,0),new u.Vector2(t,s));switch(n){case 0:r.set(new u.Vector2(0,i-s),new u.Vector2(s,i));break;case 1:r.set(new u.Vector2(0,0),new u.Vector2(s,s));break;case 4:r.set(new u.Vector2(t-s,i-s),new u.Vector2(t,i));break}return r}}function Jt(c,e){const t=e.font||"Helvetica",i=e.fontSize||30,n=e.width||200,s=e.height||200,r=e.bgColor?e.bgColor.join(", "):"255, 255, 255, 1.0",o=e.color?e.color.join(", "):"0, 0, 0, 1.0",a=document.createElement("canvas");a.width=n,a.height=s;const h=a.getContext("2d");if(h){h.font=`bold ${i}px ${t}`,h.fillStyle=`rgba(${r})`,h.fillRect(0,0,n,s);const d=h.measureText(c).width;h.fillStyle=`rgba(${o})`,h.fillText(c,n/2-d/2,s/2+i/2-2)}const l=new u.Texture(a);return l.minFilter=u.LinearFilter,l.needsUpdate=!0,l}function Ce(c){const e=Jt(c,{fontSize:100,font:"Arial Narrow, sans-serif",color:[255,255,255,1],bgColor:[0,0,0,0]}),t=new u.SpriteMaterial({map:e,transparent:!0});return new u.Sprite(t)}_e.RIGHT_TOP;const Kt={pos:_e.LEFT_BOTTOM,size:100,hasZAxis:!0};class ei extends Zt{constructor(e,t,i){const n={...Kt,...i};super(e,t,n.size,i.pos),this.hasZAxis=n.hasZAxis;const s=[0,0,0,2,0,0,0,0,0,0,2,0],r=[1,0,0,1,.6,0,0,1,0,.6,1,0];this.hasZAxis&&(s.push(0,0,0,0,0,2),r.push(0,0,1,0,.6,1));const o=new u.BufferGeometry;o.setAttribute("position",new u.Float32BufferAttribute(s,3)),o.setAttribute("color",new u.Float32BufferAttribute(r,3));const a=new u.LineBasicMaterial({vertexColors:!0,toneMapped:!1});this.axes=new u.LineSegments(o,a),this.axes.position.set(-1,-1,-1),this.add(this.axes),this.xText=Ce("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=Ce("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=Ce("Z"),this.zText.position.set(-1,-1,1.5),this.add(this.zText))}setLineColors(e,t){const i=new u.Color,n=this.axes.geometry.attributes.color.array;return i.set(e),i.toArray(n,0),i.toArray(n,3),i.set(t),i.toArray(n,6),i.toArray(n,9),this.axes.geometry.attributes.color.needsUpdate=!0,this}setTextColor(e){this.xText.material.color=e,this.yText.material.color=e}dispose(){var e,t;this.axes.geometry.dispose(),this.axes.material.dispose(),this.xText.geometry.dispose(),this.xText.material.dispose(),this.yText.geometry.dispose(),this.yText.material.dispose(),this.hasZAxis&&((e=this.zText)==null||e.geometry.dispose(),(t=this.zText)==null||t.material.dispose())}}class ti extends nt{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=P.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==P.SELECTION?this._cameraControls.mouseButtons={MIDDLE:u.MOUSE.PAN}:e==P.PAN&&(this._cameraControls.mouseButtons={LEFT:u.MOUSE.PAN}),this._cameraControls.update(),this._mode=e}get viewportCount(){return this._viewportViews.size}addViewport(e){this._viewportViews.set(e.viewport.id,e)}removeViewport(e){this._viewportViews.delete(e)}resize(e,t){this._height=t,this._width=e,this.updateCameraFrustum(),this._viewportViews.forEach(i=>{i.update()})}render(e){var i;this._renderer.clear(),this._renderer.render(e.internalScene,this._camera);const t=e.modelSpaceLayout;t&&this.drawViewports(t.internalObject),(i=this._axesGizmo)==null||i.update()}createAxesGizmo(){return new ei(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:_e.LEFT_BOTTOM})}drawViewports(e){if(this._viewportViews.size>0){const t=this._renderer.autoClear;this._renderer.autoClear=!1;const i=new u.Vector4;this._renderer.getViewport(i),this._renderer.clearDepth();const n=e.visible;e.visible=!0,this._viewportViews.forEach(s=>{s.render(e)}),e.visible=n,this._renderer.setViewport(i.x,i.y,i.z,i.w),this._renderer.autoClear=t}}}class ii{constructor(){this._activeLayoutBtrId="",this._layoutViews=new Map}get activeLayoutBtrId(){return this._activeLayoutBtrId}set activeLayoutBtrId(e){this._activeLayoutBtrId=e,this._layoutViews.forEach(t=>{t.enabled=t.layoutBtrId==e})}get activeLayoutView(){return this._layoutViews.get(this._activeLayoutBtrId)}has(e){return this._layoutViews.has(e)}getAt(e){return this._layoutViews.get(e)}resize(e,t){this._layoutViews.forEach(i=>{i.resize(e,t)})}add(e){this._layoutViews.set(e.layoutBtrId,e)}render(e){var t;(t=this.activeLayoutView)==null||t.render(e)}}function st(c,e,t=0,i=c.length-1,n=ni){for(;i>t;){if(i-t>600){const a=i-t+1,h=e-t+1,l=Math.log(a),m=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*m*(a-m)/a)*(h-a/2<0?-1:1),y=Math.max(t,Math.floor(e-h*m/a+d)),p=Math.min(i,Math.floor(e+(a-h)*m/a+d));st(c,e,y,p,n)}const s=c[e];let r=t,o=i;for(re(c,t,e),n(c[i],s)>0&&re(c,t,i);r<o;){for(re(c,r,o),r++,o--;n(c[r],s)<0;)r++;for(;n(c[o],s)>0;)o--}n(c[t],s)===0?re(c,t,o):(o++,re(c,o,i)),o<=e&&(t=o+1),e<=o&&(i=o-1)}}function re(c,e,t){const i=c[e];c[e]=c[t],c[t]=i}function ni(c,e){return c<e?-1:c>e?1:0}class si{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const i=[];if(!we(e,t))return i;const n=this.toBBox,s=[];for(;t;){for(let r=0;r<t.children.length;r++){const o=t.children[r],a=t.leaf?n(o):o;we(e,a)&&(t.leaf?i.push(o):Ee(e,a)?this._all(o,i):s.push(o))}t=s.pop()}return i}collides(e){let t=this.data;if(!we(e,t))return!1;const i=[];for(;t;){for(let n=0;n<t.children.length;n++){const s=t.children[n],r=t.leaf?this.toBBox(s):s;if(we(e,r)){if(t.leaf||Ee(e,r))return!0;i.push(s)}}t=i.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let i=0;i<e.length;i++)this.insert(e[i]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=t;else if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const i=this.data;this.data=t,t=i}this._insert(t,this.data.height-t.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Q([]),this}remove(e,t){if(!e)return this;let i=this.data;const n=this.toBBox(e),s=[],r=[];let o,a,h;for(;i||s.length;){if(i||(i=s.pop(),a=s[s.length-1],o=r.pop(),h=!0),i.leaf){const l=ri(e,i.children,t);if(l!==-1)return i.children.splice(l,1),s.push(i),this._condense(s),this}!h&&!i.leaf&&Ee(i,n)?(s.push(i),r.push(o),o=0,a=i,i=i.children[0]):a?(o++,i=a.children[o],h=!1):i=null}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const i=[];for(;e;)e.leaf?t.push(...e.children):i.push(...e.children),e=i.pop();return t}_build(e,t,i,n){const s=i-t+1;let r=this._maxEntries,o;if(s<=r)return o=Q(e.slice(t,i+1)),q(o,this.toBBox),o;n||(n=Math.ceil(Math.log(s)/Math.log(r)),r=Math.ceil(s/Math.pow(r,n-1))),o=Q([]),o.leaf=!1,o.height=n;const a=Math.ceil(s/r),h=a*Math.ceil(Math.sqrt(r));rt(e,t,i,h,this.compareMinX);for(let l=t;l<=i;l+=h){const m=Math.min(l+h-1,i);rt(e,l,m,a,this.compareMinY);for(let d=l;d<=m;d+=a){const y=Math.min(d+a-1,m);o.children.push(this._build(e,d,y,n-1))}}return q(o,this.toBBox),o}_chooseSubtree(e,t,i,n){for(;n.push(t),!(t.leaf||n.length-1===i);){let s=1/0,r=1/0,o;for(let a=0;a<t.children.length;a++){const h=t.children[a],l=Me(h),m=ci(e,h)-l;m<r?(r=m,s=l<s?l:s,o=h):m===r&&l<s&&(s=l,o=h)}t=o||t.children[0]}return t}_insert(e,t,i){const n=i?e:this.toBBox(e),s=[],r=this._chooseSubtree(n,this.data,t,s);for(r.children.push(e),ae(r,n);t>=0&&s[t].children.length>this._maxEntries;)this._split(s,t),t--;this._adjustParentBBoxes(n,s,t)}_split(e,t){const i=e[t],n=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,n);const r=this._chooseSplitIndex(i,s,n),o=Q(i.children.splice(r,i.children.length-r));o.height=i.height,o.leaf=i.leaf,q(i,this.toBBox),q(o,this.toBBox),t?e[t-1].children.push(o):this._splitRoot(i,o)}_splitRoot(e,t){this.data=Q([e,t]),this.data.height=e.height+1,this.data.leaf=!1,q(this.data,this.toBBox)}_chooseSplitIndex(e,t,i){let n,s=1/0,r=1/0;for(let o=t;o<=i-t;o++){const a=oe(e,0,o,this.toBBox),h=oe(e,o,i,this.toBBox),l=hi(a,h),m=Me(a)+Me(h);l<s?(s=l,n=o,r=m<r?m:r):l===s&&m<r&&(r=m,n=o)}return n||i-t}_chooseSplitAxis(e,t,i){const n=e.leaf?this.compareMinX:oi,s=e.leaf?this.compareMinY:ai,r=this._allDistMargin(e,t,i,n),o=this._allDistMargin(e,t,i,s);r<o&&e.children.sort(n)}_allDistMargin(e,t,i,n){e.children.sort(n);const s=this.toBBox,r=oe(e,0,t,s),o=oe(e,i-t,i,s);let a=be(r)+be(o);for(let h=t;h<i-t;h++){const l=e.children[h];ae(r,e.leaf?s(l):l),a+=be(r)}for(let h=i-t-1;h>=t;h--){const l=e.children[h];ae(o,e.leaf?s(l):l),a+=be(o)}return a}_adjustParentBBoxes(e,t,i){for(let n=i;n>=0;n--)ae(t[n],e)}_condense(e){for(let t=e.length-1,i;t>=0;t--)e[t].children.length===0?t>0?(i=e[t-1].children,i.splice(i.indexOf(e[t]),1)):this.clear():q(e[t],this.toBBox)}}function ri(c,e,t){if(!t)return e.indexOf(c);for(let i=0;i<e.length;i++)if(t(c,e[i]))return i;return-1}function q(c,e){oe(c,0,c.children.length,e,c)}function oe(c,e,t,i,n){n||(n=Q(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let s=e;s<t;s++){const r=c.children[s];ae(n,c.leaf?i(r):r)}return n}function ae(c,e){return c.minX=Math.min(c.minX,e.minX),c.minY=Math.min(c.minY,e.minY),c.maxX=Math.max(c.maxX,e.maxX),c.maxY=Math.max(c.maxY,e.maxY),c}function oi(c,e){return c.minX-e.minX}function ai(c,e){return c.minY-e.minY}function Me(c){return(c.maxX-c.minX)*(c.maxY-c.minY)}function be(c){return c.maxX-c.minX+(c.maxY-c.minY)}function ci(c,e){return(Math.max(e.maxX,c.maxX)-Math.min(e.minX,c.minX))*(Math.max(e.maxY,c.maxY)-Math.min(e.minY,c.minY))}function hi(c,e){const t=Math.max(c.minX,e.minX),i=Math.max(c.minY,e.minY),n=Math.min(c.maxX,e.maxX),s=Math.min(c.maxY,e.maxY);return Math.max(0,n-t)*Math.max(0,s-i)}function Ee(c,e){return c.minX<=e.minX&&c.minY<=e.minY&&e.maxX<=c.maxX&&e.maxY<=c.maxY}function we(c,e){return e.minX<=c.maxX&&e.minY<=c.maxY&&e.maxX>=c.minX&&e.maxY>=c.minY}function Q(c){return{children:c,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function rt(c,e,t,i,n){const s=[e,t];for(;s.length;){if(t=s.pop(),e=s.pop(),t-e<=i)continue;const r=e+Math.ceil((t-e)/i/2)*i;st(c,r,e,t,n),s.push(e,r,r,t)}}class li{constructor(e){this._group=new Gt,this._name=e}get name(){return this._name}set name(e){this._name=e}get visible(){return this._group.visible}set visible(e){this._group.visible=e}get internalObject(){return this._group}get stats(){const e=this._group.stats;return{name:this._name,...e}}get entityCount(){return this._group.entityCount}rerenderPoints(e){this._group.rerenderPoints(e)}hasEntity(e){return this._group.hasEntity(e)}addEntity(e){this._group.addEntity(e)}isIntersectWith(e,t){return this._group.isIntersectWith(e,t)}remove(e){throw new Error("Not implemented yet!")}update(e){return this._group.add(e),!0}hover(e){e.forEach(t=>{this._group.hover(t)})}unhover(e){e.forEach(t=>{this._group.unhover(t)})}select(e){e.forEach(t=>{this._group.select(t)})}unselect(e){e.forEach(t=>{this._group.unselect(t)})}}class ui{constructor(){this._group=new u.Group,this._indexTree=new si,this._box=new u.Box3,this._layers=new Map}get internalObject(){return this._group}get layers(){return this._layers}get box(){return this._box}get visible(){return this._group.visible}set visible(e){this._group.visible=e}get entityCount(){let e=0;return this._layers.forEach(t=>e+=t.entityCount),e}get stats(){const e=[];let t=0,i=0,n=0,s=0,r=0;return this._layers.forEach(o=>{const a=o.stats;e.push(a),n+=a.line.indexed.geometrySize+a.line.nonIndexed.geometrySize,s+=a.mesh.indexed.geometrySize+a.mesh.nonIndexed.geometrySize,r+=a.point.indexed.geometrySize+a.point.nonIndexed.geometrySize,t+=a.summary.totalGeometrySize,i+=a.summary.totalMappingSize}),{layers:e,summary:{entityCount:this.entityCount,totalSize:{line:n,mesh:s,point:r,geometry:t,mapping:i}}}}clear(){return this._layers.forEach(e=>{this._group.remove(e.internalObject)}),this._layers.clear(),this._box.makeEmpty(),this._indexTree.clear(),this}rerenderPoints(e){this._layers.forEach(t=>{t.rerenderPoints(e)})}isIntersectWith(e,t){const i=this.getLayerByObjectId(e);return i&&i.isIntersectWith(e,t)}addEntity(e,t=!0){if(!e.objectId)throw new Error("[AcTrEntity] Object id is required to add one entity!");if(!e.layerName)throw new Error("[AcTrEntity] Layer name is required to add one entity!");const i=this.getLayer(e.layerName,!0);if(i){i.addEntity(e);const n=e.box;t&&this._box.union(n),this._indexTree.insert({minX:n.min.x,minY:n.min.y,maxX:n.max.x,maxY:n.max.y,id:e.objectId})}return this}remove(e){for(const[t,i]of this._layers)if(i.remove(e))return!0;return!1}update(e){for(const[t,i]of this._layers)if(i.update(e))return!0;return!1}hover(e){e.forEach(t=>{const i=this.getLayerByObjectId(t);i&&i.hover([t])})}unhover(e){e.forEach(t=>{const i=this.getLayerByObjectId(t);i&&i.unhover([t])})}select(e){e.forEach(t=>{const i=this.getLayerByObjectId(t);i&&i.select([t])})}unselect(e){e.forEach(t=>{const i=this.getLayerByObjectId(t);i&&i.unselect([t])})}setSnapObject(e){this._snapPointsObject&&this._group.remove(this._snapPointsObject),this._snapPointsObject=e,this._group.add(e)}search(e){return this._indexTree.search({minX:e.min.x,minY:e.min.y,maxX:e.max.x,maxY:e.max.y})}getLayerByObjectId(e){for(const[t,i]of this._layers)if(i.hasEntity(e))return i}getLayer(e,t=!0){let i=this._layers.get(e);return i===void 0&&t&&(i=new li(e),this._layers.set(e,i),this._group.add(i.internalObject)),i}}class di{constructor(){this._scene=new u.Scene,this._layouts=new Map,this._activeLayoutBtrId="",this._modelSpaceBtrId=""}get layouts(){return this._layouts}get box(){var e;return(e=this.activeLayout)==null?void 0:e.box}get internalScene(){return this._scene}get modelSpaceBtrId(){return this._modelSpaceBtrId}set modelSpaceBtrId(e){if(this._modelSpaceBtrId=e,!this._layouts.has(e))throw new Error(`[AcTrScene] No layout assiciated with the specified block table record id '${e}'!`)}get activeLayoutBtrId(){return this._activeLayoutBtrId}set activeLayoutBtrId(e){this._activeLayoutBtrId=e,this._layouts.forEach((t,i)=>{t.visible=e==i})}get activeLayout(){if(this._activeLayoutBtrId&&this._layouts.has(this._activeLayoutBtrId))return this._layouts.get(this._activeLayoutBtrId)}get modelSpaceLayout(){if(this._modelSpaceBtrId&&this._layouts.has(this._modelSpaceBtrId))return this._layouts.get(this._modelSpaceBtrId)}get stats(){const e=[];return this._layouts.forEach(t=>e.push(t.stats)),{layouts:e}}addEmptyLayout(e){const t=new ui;return this._layouts.set(e,t),this._scene.add(t.internalObject),t.visible=e==this._activeLayoutBtrId,t}clear(){return this._layouts.forEach(e=>{this._scene.remove(e.internalObject),e.clear()}),this._layouts.clear(),this._scene.clear(),this}setLayerVisibility(e,t){var n;let i=!1;return(n=this.activeLayout)==null||n.layers.forEach(s=>{s.name===e&&(s.visible=t,i=!0)}),i}hover(e){return this.activeLayout?(this.activeLayout.hover(e),!0):!1}unhover(e){return this.activeLayout?(this.activeLayout.unhover(e),!0):!1}select(e){return this.activeLayout?(this.activeLayout.select(e),!0):!1}unselect(e){return this.activeLayout?(this.activeLayout.unselect(e),!0):!1}search(e){const t=this.activeLayout;return t?t==null?void 0:t.search(e):[]}addEntity(e,t=!0){const i=e.ownerId;if(i){let n=this._layouts.get(i);n||(n=this.addEmptyLayout(i)),n.addEntity(e,t)}else console.warn("[AcTrSecene] The owner id of one entity cannot be empty!");return this}remove(e){for(const[t,i]of this._layouts)if(i.remove(e))return!0;return!1}update(e){for(const[t,i]of this._layouts)if(i.update(e))return!0;return!1}setSnapObject(e){return this._layouts.forEach(t=>{t.setSnapObject(e)}),this}}const Le={background:0};class ot extends Ge{constructor(e=Le){const t={...Le,...e},i=new u.WebGLRenderer({antialias:!0,alpha:!0,canvas:e.canvas});t.canvas==null&&(t.canvas=i.domElement),super(t.canvas),e.calculateSizeCallback&&this.setCalculateSizeCallback(e.calculateSizeCallback),i.setPixelRatio(Math.min(window.devicePixelRatio,2)),i.setSize(this.width,this.height),this._renderer=new Ht(i);const n=Z.instance.fontMapping;this._renderer.setFontMapping(n),this._renderer.events.fontNotFound.addEventListener(s=>{z.emit("font-not-found",{fontName:s.fontName,count:s.count??0})}),this._scene=this.createScene(),this._renderer.setClearColor(t.background||0),this._stats=this.createStats(Z.instance.isShowStats),Z.instance.events.modified.addEventListener(s=>{s.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,s.value)}),this.canvas.addEventListener("click",()=>{this.mode==P.SELECTION&&this.select()}),document.addEventListener("keydown",s=>{s.code==="Escape"&&this.selectionSet.clear()}),g.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(s=>{this.activeLayoutBtrId=s.layout.blockTableRecordId}),this._missedImages=new Map,this._layoutViewManager=new ii,this.initialize(),this.onWindowResize(),this.animate(),this._isDirty=!0}initialize(){this.setCursor(j.Crosshair)}get mode(){const e=this.activeLayoutView;return e?e.mode:P.SELECTION}set mode(e){this.activeLayoutView.mode=e,this.editor.getPoint()}get renderer(){return this._renderer}get isDirty(){return this._isDirty}set isDirty(e){this._isDirty=e}get missedData(){return{fonts:this._renderer.missedFonts,images:this._missedImages}}get center(){return this.activeLayoutView.center}set center(e){this.activeLayoutView.center=e}get backgroundColor(){return this._renderer.getClearColor()}set backgroundColor(e){this._renderer.setClearColor(e),this._isDirty=!0}get modelSpaceBtrId(){return this._scene.modelSpaceBtrId}set modelSpaceBtrId(e){this._scene.modelSpaceBtrId=e}get activeLayoutBtrId(){return this._scene.activeLayoutBtrId}set activeLayoutBtrId(e){this._layoutViewManager.activeLayoutBtrId=e,this._scene.activeLayoutBtrId=e,this._isDirty=!0}get activeLayoutView(){return this._layoutViewManager.activeLayoutView}get stats(){return this._scene.stats}animate(){var e;requestAnimationFrame(this.animate.bind(this)),this._isDirty&&(this._layoutViewManager.render(this._scene),(e=this._stats)==null||e.update(),this._isDirty=!1)}cwcs2Wcs(e){const t=this.activeLayoutView;return t?t.cwcs2Wcs(e):new g.AcGePoint2d(e)}wcs2Cwcs(e){const t=this.activeLayoutView;return t?t.wcs2Cwcs(e):new g.AcGePoint2d(e)}zoomTo(e,t=1.1){this.activeLayoutView.zoomTo(e,t),this._isDirty=!0}rerenderPoints(e){const t=this._scene.activeLayout;t&&(t.rerenderPoints(e),this._isDirty=!0)}zoomToFit(){if(this._scene.box){const e=Qt.threeBox3dToGeBox2d(this._scene.box);this.zoomTo(e),this._isDirty=!0}}pick(e){e==null&&(e=this.curPos);const t=[],i=this._scene.activeLayout;if(i){const n=this.activeLayoutView,s=n.pointToBox(e,this.selectionBoxSize),r=this._scene.search(s),o=Math.max(s.size.width/2,s.size.height/2),a=n.resetRaycaster(e,o);r.forEach(h=>{const l=h.id;i.isIntersectWith(l,a)&&t.push(l)})}return t}search(e){return this._scene.search(e)}select(e){const t=[];this.pick(e).forEach(n=>t.push(n)),t.length>0&&this.selectionSet.add(t)}selectByBox(e){const t=[];this._scene.search(e).forEach(n=>t.push(n.id)),this.selectionSet.add(t)}addEntity(e){const t=Array.isArray(e)?e:[e];setTimeout(async()=>{await this.batchConvert(t)})}removeEntity(e){this._scene.remove(e)}updateEntity(e){let t=[];Array.isArray(e)?t=e:t.push(e);for(let i=0;i<t.length;++i){const n=t[i],s=n.draw(this._renderer);s&&(s.objectId=n.objectId,s.ownerId=n.ownerId,s.layerName=n.layer,s.visible=n.visibility,this._scene.update(s))}this._isDirty=!0,setTimeout(()=>{this._isDirty=!0},100)}addLayout(e){this._scene.addEmptyLayout(e.blockTableRecordId),this.createLayoutViewIfNeeded(e.blockTableRecordId)}clear(){this._scene.clear(),this._isDirty=!0,this._missedImages.clear(),this._renderer.clearMissedFonts()}highlight(e){this._isDirty=this._scene.select(e)}unhighlight(e){this._isDirty=this._scene.unselect(e)}setLayerVisibility(e,t){this._isDirty=this._scene.setLayerVisibility(e,t)}onHover(e){this._isDirty=this._scene.hover([e])}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){const e=new di;return e.layouts.forEach(t=>{t.setSnapObject(this.renderer.createObject())}),e}createStats(e){const t=new mt;document.body.appendChild(t.dom);const i=t.dom;return i.style.position="fixed",i.style.inset="unset",i.style.bottom="30px",i.style.right="0px",this.toggleStatsVisibility(t,e),t}onWindowResize(){super.onWindowResize(),this._renderer.setSize(this.width,this.height),this._layoutViewManager.resize(this.width,this.height),this._isDirty=!0}createLayoutViewIfNeeded(e){let t=this._layoutViewManager.getAt(e);return t==null&&(t=new ti(this._renderer,e,this.width,this.height),t.events.viewChanged.addEventListener(()=>{this._isDirty=!0}),this._layoutViewManager.add(t)),t}toggleStatsVisibility(e,t){t?e.dom.style.display="block":e.dom.style.display="none"}async batchConvert(e){for(let t=0;t<e.length;++t){const i=e[t],n=i.draw(this._renderer);if(n){n.objectId=i.objectId,n.ownerId=i.ownerId,n.layerName=i.layer,n.visible=i.visibility;const s=!(i instanceof g.AcDbRay||i instanceof g.AcDbXline);if(await n.draw().then(()=>{this._scene.addEntity(n,s),n.dispose(),this._isDirty=!0}),i instanceof g.AcDbViewport){if(i.number>1){const r=this._layoutViewManager.getAt(i.ownerId);if(r){const o=new xe(r,i.toGiViewport(),this._renderer);r.addViewport(o)}}}else if(i instanceof g.AcDbRasterImage){const r=i.imageFileName;r&&this._missedImages.set(i.objectId,r)}}}}}class mi{constructor(e){this._cadRenderer=e,this._avaiableFonts=[]}get avaiableFonts(){return this._avaiableFonts}async getAvaiableFonts(){if(this._avaiableFonts.length==0){const e="https://cdn.jsdelivr.net/gh/mlight-lee/cad-data/fonts/",t=e+"fonts.json";try{const i=await fetch(t);this._avaiableFonts=await i.json()}catch{z.emit("failed-to-get-avaiable-fonts",{url:t})}this._avaiableFonts.forEach(i=>{i.url=e+i.file})}return this._avaiableFonts}async load(e){await this.getAvaiableFonts();const t=[];e.forEach(n=>{const s=n.toLowerCase(),r=ve.find(this._avaiableFonts,o=>ve.findIndex(o.name,a=>a.toLowerCase()==s)>=0);r&&t.push(r.url)}),(await this._cadRenderer.loadFonts(t)).forEach(n=>{n.status||z.emit("font-not-loaded",{fontName:n.fontName,url:n.url})})}}class M{constructor(e){this.events={documentCreated:new g.AcCmEventManager,documentActivated:new g.AcCmEventManager};const t=new Re;t.database.events.openProgress.addEventListener(s=>{z.emit("open-file-progress",{database:t.database,percentage:s.percentage,stage:s.stage,subStage:s.subStage,stageStatus:s.stageStatus})});const i=()=>({width:window.innerWidth,height:window.innerHeight-30}),n=new ot({canvas:e,calculateSizeCallback:i});this._context=new Te(n,t),this._fontLoader=new mi(n.renderer),g.acdbHostApplicationServices().workingDatabase=t.database,this.registerCommands()}static createInstance(e){return M._instance==null&&(M._instance=new M(e)),this._instance}static get instance(){return M._instance||(M._instance=new M),M._instance}get context(){return this._context}get curDocument(){return this._context.doc}get mdiActiveDocument(){return this._context.doc}get curView(){return this._context.view}get editor(){return this._context.view.editor}get avaiableFonts(){return this._fontLoader.avaiableFonts}async loadFonts(e){await this._fontLoader.load(e)}async loadDefaultFonts(e){e==null?await this._fontLoader.load(["simkai"]):await this._fontLoader.load(e)}async openUrl(e,t){this.onBeforeOpenDocument(),t=this.setOptions(t);const i=await this.context.doc.openUri(e,t);return this.onAfterOpenDocument(i),i}async openDocument(e,t,i){this.onBeforeOpenDocument(),i=this.setOptions(i);const n=await this.context.doc.openDocument(e,t,i);return this.onAfterOpenDocument(n),n}registerCommands(){const e=C.instance;e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"pan","pan",new Xe),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"select","select",new Fe),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"zoom","zoom",new Ne),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"zoomw","zoomw",new We),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"csvg","csvg",new Ve),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"qnew","qnew",new ke),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"open","open",new je)}sendStringToExecute(e){const i=C.instance.lookupGlobalCmd(e);i==null||i.execute(this.context)}setActiveLayout(){const e=this.curView;e.activeLayoutBtrId=this.curDocument.database.currentSpaceId,e.modelSpaceBtrId=this.curDocument.database.currentSpaceId}onBeforeOpenDocument(){this.curView.clear()}onAfterOpenDocument(e){if(e){const t=this.context.doc;this.events.documentActivated.dispatch({doc:t}),this.setActiveLayout();const i=t.database;this.curView.zoomTo(new g.AcGeBox2d(i.extmin,i.extmax))}}setOptions(e){return e==null?e={fontLoader:this._fontLoader}:e.fontLoader==null&&(e.fontLoader=this._fontLoader),e}}class at{convert(e){const t=this.createEntity(e);return t&&this.processCommonAttrs(e,t),t}createEntity(e){return e.type=="ARC"?this.convertArc(e):e.type=="CIRCLE"?this.convertCirle(e):e.type=="DIMENSION"?this.convertDimension(e):e.type=="ELLIPSE"?this.convertEllipse(e):e.type=="HATCH"?this.convertHatch(e):e.type=="IMAGE"?this.convertImage(e):e.type=="LEADER"?this.convertLeader(e):e.type=="LINE"?this.convertLine(e):e.type=="LWPOLYLINE"?this.convertLWPolyline(e):e.type=="MTEXT"?this.convertMText(e):e.type=="POINT"?this.convertPoint(e):e.type=="POLYLINE"?this.convertPolyline(e):e.type=="RAY"?this.convertRay(e):e.type=="SPLINE"?this.convertSpline(e):e.type=="ACAD_TABLE"?this.convertTable(e):e.type=="TEXT"?this.convertText(e):e.type=="SOLID"?this.convertSolid(e):e.type=="VIEWPORT"?this.convertViewport(e):e.type=="XLINE"?this.convertXline(e):e.type=="INSERT"?this.convertBlockReference(e):null}convertArc(e){return new g.AcDbArc(e.center,e.radius,e.startAngle,e.endAngle)}convertCirle(e){return new g.AcDbCircle(e.center,e.radius)}convertEllipse(e){const t=new g.AcGeVector3d(e.majorAxisEndPoint),i=t.length();return new g.AcDbEllipse(e.center,g.AcGeVector3d.Z_AXIS,t,i,i*e.axisRatio,e.startAngle,e.endAngle)}convertLine(e){const t=e.startPoint,i=e.endPoint;return new g.AcDbLine(new g.AcGePoint3d(t.x,t.y,t.z),new g.AcGePoint3d(i.x,i.y,i.z))}convertSpline(e){return e.numberOfControlPoints>0&&e.numberOfKnots>0?new g.AcDbSpline(e.controlPoints,e.knots,e.weights,e.degree,!!(e.flag&1)):e.numberOfFitPoints>0?new g.AcDbSpline(e.fitPoints,"Uniform",e.degree,!!(e.flag&1)):null}convertPoint(e){const t=new g.AcDbPoint;return t.position=e.position,t}convertSolid(e){const t=new g.AcDbTrace;return t.setPointAt(0,{...e.corner1,z:0}),t.setPointAt(1,{...e.corner2,z:0}),t.setPointAt(2,{...e.corner3,z:0}),t.setPointAt(3,e.corner4?{...e.corner4,z:0}:{...e.corner3,z:0}),t.thickness=e.thickness,t}convertLWPolyline(e){const t=new g.AcDbPolyline;return t.closed=!!(e.flag&512),e.vertices.forEach((i,n)=>{t.addVertexAt(n,new g.AcGePoint2d(i.x,i.y),i.bulge,i.startWidth,i.endWidth)}),t}convertPolyline(e){const t=new g.AcDbPolyline;return t.closed=!!(e.flag&1),e.vertices.forEach((i,n)=>{t.addVertexAt(n,new g.AcGePoint2d(i.x,i.y),i.bulge,i.startWidth,i.endWidth)}),t}convertHatch(e){var t;const i=new g.AcDbHatch;return(t=e.definitionLines)==null||t.forEach(n=>{i.definitionLines.push({angle:n.angle,origin:n.base,delta:n.offset,dashPattern:n.numberOfDashLengths>0?n.dashLengths:[]})}),i.hatchStyle=e.hatchStyle,i.patternName=e.patternName,i.patternType=e.patternType,i.patternAngle=e.patternAngle==null?0:e.patternAngle,i.patternScale=e.patternScale==null?0:e.patternScale,e.boundaryPaths.forEach(n=>{if(n.boundaryPathTypeFlag&2){const s=n,r=new g.AcGePolyline2d;r.closed=s.isClosed,s.vertices.forEach((o,a)=>{r.addVertexAt(a,{x:o.x,y:o.y,bulge:o.bulge})}),i.add(r)}else{const s=n,r=new g.AcGeLoop2d;s.edges.forEach(o=>{if(o.type==1){const a=o;r.add(new g.AcGeLine2d(a.start,a.end))}else if(o.type==2){const a=o;r.add(new g.AcGeCircArc2d(a.center,a.radius,a.startAngle,a.endAngle,!a.isCCW))}else if(o.type==3){const a=o;new g.AcGeVector2d().subVectors(a.end,a.center);const h=Math.sqrt(Math.pow(a.end.x,2)+Math.pow(a.end.y,2)),l=h*a.lengthOfMinorAxis;let m=a.startAngle,d=a.endAngle;const y=Math.atan2(a.end.y,a.end.x);a.isCCW||(m=Math.PI*2-m,d=Math.PI*2-d),r.add(new g.AcGeEllipseArc2d({...a.center,z:0},h,l,m,d,!a.isCCW,y))}else if(o.type==4){const a=o;if(a.numberOfControlPoints>0&&a.numberOfKnots>0){const h=a.controlPoints.map(d=>({x:d.x,y:d.y,z:0}));let l=!0;const m=a.controlPoints.map(d=>(d.weight==null&&(l=!1),d.weight||1));r.add(new g.AcGeSpline3d(h,a.knots,l?m:void 0))}else if(a.numberOfFitData>0){const h=a.fitDatum.map(l=>({x:l.x,y:l.y,z:0}));r.add(new g.AcGeSpline3d(h,"Uniform"))}}}),i.add(r)}}),i}convertTable(e){const t=new g.AcDbTable(e.name,e.rowCount,e.columnCount);return t.attachmentPoint=e.attachmentPoint,t.position.copy(e.startPoint),e.columnWidthArr.forEach((i,n)=>t.setColumnWidth(n,i)),e.rowHeightArr.forEach((i,n)=>t.setRowHeight(n,i)),e.cells.forEach((i,n)=>{t.setCell(n,i)}),t}convertText(e){const t=new g.AcDbText;return t.textString=e.text,t.styleName=e.styleName,t.height=e.textHeight,t.position.copy(e.startPoint),t.rotation=e.rotation,t.oblique=e.obliqueAngle??0,t.thickness=e.thickness,t.horizontalMode=e.halign,t.verticalMode=e.valign,t.widthFactor=e.xScale??1,t}convertMText(e){const t=new g.AcDbMText;return t.contents=e.text,e.styleName!=null&&(t.styleName=e.styleName),t.height=e.textHeight,t.width=e.rectWidth,t.rotation=e.rotation||0,t.location=e.insertionPoint,t.attachmentPoint=e.attachmentPoint,e.direction&&(t.direction=new g.AcGeVector3d(e.direction)),t.drawingDirection=e.drawingDirection,t}convertLeader(e){const t=new g.AcDbLeader;return e.vertices.forEach(i=>{t.appendVertex(i)}),t.hasArrowHead=e.isArrowheadEnabled,t.hasHookLine=e.isHooklineExists,t.isSplined=e.isSpline,t.dimensionStyle=e.styleName,t.annoType=e.leaderCreationFlag,t}convertDimension(e){if(e.subclassMarker=="AcDbAlignedDimension"||e.subclassMarker=="AcDbRotatedDimension"){const t=e,i=new g.AcDbAlignedDimension(t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return i.rotation=t.rotationAngle,this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDb3PointAngularDimension"){const t=e,i=new g.AcDb3PointAngularDimension(t.centerPoint,t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbOrdinateDimension"){const t=e,i=new g.AcDbOrdinateDimension(t.subDefinitionPoint1,t.subDefinitionPoint2);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbRadialDimension"){const t=e,i=new g.AcDbRadialDimension(t.definitionPoint,t.centerPoint,t.leaderLength);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbDiametricDimension"){const t=e,i=new g.AcDbDiametricDimension(t.definitionPoint,t.centerPoint,t.leaderLength);return this.processDimensionCommonAttrs(e,i),i}return null}processImage(e,t){t.position.copy(e.position),t.brightness=e.brightness,t.contrast=e.contrast,t.fade=e.fade,t.imageDefId=e.imageDefHandle.toString(),t.isClipped=(e.flags|4)>0,t.isImageShown=(e.flags|3)>0,t.isImageTransparent=(e.flags|8)>0,e.clippingBoundaryPath.forEach(i=>{t.clipBoundary.push(new g.AcGePoint2d(i))}),t.clipBoundaryType=e.clippingBoundaryType,t.width=Math.sqrt(e.uPixel.x**2+e.uPixel.y**2+e.uPixel.z**2)*e.imageSize.x,t.height=Math.sqrt(e.vPixel.x**2+e.vPixel.y**2+e.vPixel.z**2)*e.imageSize.y,t.rotation=Math.atan2(e.uPixel.y,e.uPixel.x)}convertImage(e){const t=new g.AcDbRasterImage;return this.processImage(e,t),t}convertViewport(e){const t=new g.AcDbViewport;return t.number=e.viewportId,t.centerPoint.copy(e.viewportCenter),t.height=e.height,t.width=e.width,t.viewCenter.copy(e.displayCenter),t.viewHeight=e.viewHeight,t}convertRay(e){const t=new g.AcDbRay;return t.basePoint.copy(e.firstPoint),t.unitDir.copy(e.unitDirection),t}convertXline(e){const t=new g.AcDbXline;return t.basePoint.copy(e.firstPoint),t.unitDir.copy(e.unitDirection),t}convertBlockReference(e){const t=new g.AcDbBlockReference(e.name);return e.insertionPoint&&t.position.copy(e.insertionPoint),t.scaleFactors.x=e.xScale,t.scaleFactors.y=e.yScale,t.scaleFactors.z=e.zScale,t.rotation=e.rotation,t.normal.copy(e.extrusionDirection),t}processDimensionCommonAttrs(e,t){t.dimBlockId=e.name,t.textPosition.copy(e.textPoint),t.textRotation=e.textRotation||0,e.textLineSpacingFactor&&(t.textLineSpacingFactor=e.textLineSpacingFactor),e.textLineSpacingStyle&&(t.textLineSpacingStyle=e.textLineSpacingStyle),t.dimensionStyleName=e.styleName,t.dimensionText=e.text||"",t.measurement=e.measurement}processCommonAttrs(e,t){t.layer=e.layer,t.objectId=e.handle.toString(),t.ownerId=e.ownerBlockRecordSoftId.toString(),e.lineType!=null&&(t.lineType=e.lineType),e.lineweight!=null&&(t.lineWeight=e.lineweight),e.lineTypeScale!=null&&(t.linetypeScale=e.lineTypeScale),e.color!=null&&(t.color.color=e.color),e.colorIndex!=null&&(t.color.colorIndex=e.colorIndex),e.colorName!=null&&(t.color.colorName=e.colorName),e.isVisible!=null&&(t.visibility=e.isVisible),e.transparency!=null&&(t.transparency=e.transparency)}}class gi extends g.AcDbDatabaseConverter{constructor(e={}){super(e),e.useWorker=!0,e.parserWorkerUrl||(e.parserWorkerUrl="/assets/libredwg-parser-worker.js")}async parse(e){if(this.config.useWorker&&this.config.parserWorkerUrl){const t=g.createWorkerApi({workerUrl:this.config.parserWorkerUrl,maxConcurrentWorkers:1}),i=await t.execute(e);return t.destroy(),i.data}else throw new Error("dwg converter can run in web worker only!")}getFonts(e){const t=new Map;e.tables.BLOCK_RECORD.entries.forEach(r=>{t.set(r.name,r)});const i=new Map,n=r=>{if(r){const o=r.lastIndexOf(".");return o>=0?r.substring(0,o).toLowerCase():r.toLowerCase()}};e.tables.STYLE.entries.forEach(r=>{const o=[];let a=n(r.font);a&&o.push(a),a=n(r.bigFont),a&&o.push(a),i.set(r.name,o)});const s=new Set;return this.getFontsInBlock(e.entities,t,i,s),Array.from(s)}getFontsInBlock(e,t,i,n){const s=/\\f(.*?)\|/g;e.forEach(r=>{if(r.type=="MTEXT"){const o=r;[...o.text.matchAll(s)].forEach(h=>{n.add(h[1].toLowerCase())});const a=i.get(o.styleName);a==null||a.forEach(h=>n.add(h))}else if(r.type=="TEXT"){const o=r,a=i.get(o.styleName);a==null||a.forEach(h=>n.add(h))}else if(r.type=="INSERT"){const o=r,a=t.get(o.name);a&&this.getFontsInBlock(a.entities,t,i,n)}})}processLineTypes(e,t){e.tables.LTYPE.entries.forEach(i=>{const n={name:i.name,description:i.description,standardFlag:i.standardFlag,totalPatternLength:i.totalPatternLength,pattern:i.pattern},s=new g.AcDbLinetypeTableRecord(n);this.processCommonTableEntryAttrs(i,s),s.name=i.name,t.tables.linetypeTable.add(s)})}processTextStyles(e,t){e.tables.STYLE.entries.forEach(i=>{const n=new g.AcDbTextStyleTableRecord(i);this.processCommonTableEntryAttrs(i,n),t.tables.textStyleTable.add(n)})}processDimStyles(e,t){e.tables.DIMSTYLE.entries.forEach(i=>{const n={name:i.name,ownerId:i.ownerHandle.toString(),dimpost:i.DIMPOST||"",dimapost:i.DIMAPOST||"",dimscale:i.DIMSCALE,dimasz:i.DIMASZ,dimexo:i.DIMEXO,dimdli:i.DIMDLI,dimexe:i.DIMEXE,dimrnd:i.DIMRND,dimdle:i.DIMDLE,dimtp:i.DIMTP,dimtm:i.DIMTM,dimtxt:i.DIMTXT,dimcen:i.DIMCEN,dimtsz:i.DIMTSZ,dimaltf:i.DIMALTF,dimlfac:i.DIMLFAC,dimtvp:i.DIMTVP,dimtfac:i.DIMTFAC,dimgap:i.DIMGAP,dimaltrnd:i.DIMALTRND,dimtol:i.DIMTOL==null||i.DIMTOL==0?0:1,dimlim:i.DIMLIM==null||i.DIMLIM==0?0:1,dimtih:i.DIMTIH==null||i.DIMTIH==0?0:1,dimtoh:i.DIMTOH==null||i.DIMTOH==0?0:1,dimse1:i.DIMSE1==null||i.DIMSE1==0?0:1,dimse2:i.DIMSE2==null||i.DIMSE2==0?0:1,dimtad:i.DIMTAD,dimzin:i.DIMZIN,dimazin:i.DIMAZIN,dimalt:i.DIMALT,dimaltd:i.DIMALTD,dimtofl:i.DIMTOFL,dimsah:i.DIMSAH,dimtix:i.DIMTIX,dimsoxd:i.DIMSOXD,dimclrd:i.DIMCLRD,dimclre:i.DIMCLRE,dimclrt:i.DIMCLRT,dimadec:i.DIMADEC||0,dimunit:i.DIMUNIT||2,dimdec:i.DIMDEC,dimtdec:i.DIMTDEC,dimaltu:i.DIMALTU,dimalttd:i.DIMALTTD,dimaunit:i.DIMAUNIT,dimfrac:i.DIMFRAC,dimlunit:i.DIMLUNIT,dimdsep:i.DIMDSEP,dimtmove:i.DIMTMOVE||0,dimjust:i.DIMJUST,dimsd1:i.DIMSD1,dimsd2:i.DIMSD2,dimtolj:i.DIMTOLJ,dimtzin:i.DIMTZIN,dimaltz:i.DIMALTZ,dimalttz:i.DIMALTTZ,dimfit:i.DIMFIT||0,dimupt:i.DIMUPT,dimatfit:i.DIMATFIT,dimtxsty:"Standard",dimldrblk:"",dimblk:i.DIMBLK||"",dimblk1:i.DIMBLK1||"",dimblk2:i.DIMBLK2||"",dimlwd:i.DIMLWD,dimlwe:i.DIMLWE},s=new g.AcDbDimStyleTableRecord(n);this.processCommonTableEntryAttrs(i,s),t.tables.dimStyleTable.add(s)})}processLayers(e,t){e.tables.LAYER.entries.forEach(i=>{const n=new g.AcCmColor;n.colorIndex=i.colorIndex;const s=new g.AcDbLayerTableRecord({name:i.name,standardFlags:i.standardFlag,linetype:i.lineType,lineWeight:i.lineweight,isOff:i.off,color:n,isPlottable:i.plotFlag!=0});this.processCommonTableEntryAttrs(i,s),t.tables.layerTable.add(s)})}processViewports(e,t){e.tables.VPORT.entries.forEach(i=>{const n=new g.AcDbViewportTableRecord;this.processCommonTableEntryAttrs(i,n),i.circleSides&&(n.circleSides=i.circleSides),n.standardFlag=i.standardFlag,n.center.copy(i.center),n.lowerLeftCorner.copy(i.lowerLeftCorner),n.upperRightCorner.copy(i.upperRightCorner),i.snapBasePoint&&n.snapBase.copy(i.snapBasePoint),i.snapRotationAngle&&(n.snapAngle=i.snapRotationAngle),i.snapSpacing&&n.snapIncrements.copy(i.snapSpacing),i.majorGridLines&&(n.gridMajor=i.majorGridLines),i.gridSpacing&&n.gridIncrements.copy(i.gridSpacing),i.backgroundObjectId&&(n.backgroundObjectId=i.backgroundObjectId),n.gsView.center.copy(i.center),n.gsView.viewDirectionFromTarget.copy(i.viewDirectionFromTarget),n.gsView.viewTarget.copy(i.viewTarget),i.lensLength&&(n.gsView.lensLength=i.lensLength),i.frontClippingPlane&&(n.gsView.frontClippingPlane=i.frontClippingPlane),i.backClippingPlane&&(n.gsView.backClippingPlane=i.backClippingPlane),i.viewHeight&&(n.gsView.viewHeight=i.viewHeight),i.viewTwistAngle&&(n.gsView.viewTwistAngle=i.viewTwistAngle),i.frozenLayers&&(n.gsView.frozenLayers=i.frozenLayers),i.styleSheet&&(n.gsView.styleSheet=i.styleSheet),i.renderMode&&(n.gsView.renderMode=i.renderMode),i.viewMode&&(n.gsView.viewMode=i.viewMode),i.ucsIconSetting&&(n.gsView.ucsIconSetting=i.ucsIconSetting),i.ucsOrigin&&n.gsView.ucsOrigin.copy(i.ucsOrigin),i.ucsXAxis&&n.gsView.ucsXAxis.copy(i.ucsXAxis),i.ucsYAxis&&n.gsView.ucsYAxis.copy(i.ucsYAxis),i.orthographicType&&(n.gsView.orthographicType=i.orthographicType),i.shadePlotSetting&&(n.gsView.shadePlotSetting=i.shadePlotSetting),i.shadePlotObjectId&&(n.gsView.shadePlotObjectId=i.shadePlotObjectId),i.visualStyleObjectId&&(n.gsView.visualStyleObjectId=i.visualStyleObjectId),i.isDefaultLightingOn&&(n.gsView.isDefaultLightingOn=i.isDefaultLightingOn),i.defaultLightingType&&(n.gsView.defaultLightingType=i.defaultLightingType),i.brightness&&(n.gsView.brightness=i.brightness),i.contrast&&(n.gsView.contrast=i.contrast),i.ambientColor&&(n.gsView.ambientColor=i.ambientColor),t.tables.viewportTable.add(n)})}processBlockTables(e,t){e.tables.BLOCK_RECORD.entries.forEach(i=>{let n=t.tables.blockTable.getAt(i.name);n||(n=new g.AcDbBlockTableRecord,n.objectId=i.handle.toString(),n.name=i.name,n.ownerId=i.ownerHandle.toString(),n.origin.copy(i.basePoint),n.layoutId=i.layout.toString(),t.tables.blockTable.add(n)),!n.isModelSapce&&!n.isPaperSapce&&i.entities&&i.entities.length>0&&this.processEntitiesInBlock(i.entities,n)})}processBlocks(e,t){}async processEntitiesInBlock(e,t){const i=new at,n=e.length,s=[];for(let r=0;r<n;r++){const o=e[r],a=i.convert(o);a&&s.push(a)}t.appendEntity(s)}async processEntities(e,t,i,n,s){const r=new at;let o=e.entities;const a=o.length,h=new g.AcDbBatchProcessing(a,100-n.value,i);this.config.convertByEntityType&&(o=this.groupAndFlattenByType(o));const l=t.tables.blockTable.modelSpace;await h.processChunk(async(m,d)=>{const y=[];for(let p=m;p<d;p++){const f=o[p],x=r.convert(f);x&&y.push(x)}if(l.appendEntity(y),s){let p=n.value+d/a*(100-n.value);p>100&&(p=100),await s(p,"ENTITY","IN-PROGRESS")}})}processHeader(e,t){const i=e.header;t.cecolor.colorIndex=i.CECOLOR||256,t.angBase=i.ANGBASE??0,t.angDir=i.ANGDIR??0,t.aunits=i.AUNITS??0,t.extmax=i.EXTMAX,t.extmin=i.EXTMIN,t.insunits=i.INSUNITS??1,t.pdmode=i.PDMODE??0,t.pdsize=i.PDSIZE??0}processCommonTableEntryAttrs(e,t){t.name=e.name,t.objectId=e.handle.toString(),t.ownerId=e.ownerHandle.toString()}processObjects(e,t){this.processLayouts(e,t),this.processImageDefs(e,t)}processLayouts(e,t){const i=t.dictionaries.layouts;e.objects.LAYOUT.forEach(n=>{const s=new g.AcDbLayout;s.layoutName=n.layoutName,s.tabOrder=n.tabOrder;const r=t.tables.blockTable.newIterator();s.objectId=n.handle.toString();for(const o of r)if(o.layoutId===s.objectId){s.blockTableRecordId=o.objectId;break}s.limits.min.copy(n.minLimit),s.limits.max.copy(n.maxLimit),s.extents.min.copy(n.minExtent),s.extents.max.copy(n.maxExtent),this.processCommonObjectAttrs(n,s),i.setAt(s.layoutName,s)})}processImageDefs(e,t){const i=t.dictionaries.imageDefs;e.objects.IMAGEDEF.forEach(n=>{const s=new g.AcDbRasterImageDef;s.sourceFileName=n.fileName,this.processCommonObjectAttrs(n,s),i.setAt(s.objectId,s)})}processCommonObjectAttrs(e,t){t.objectId=e.handle.toString(),t.ownerId=e.ownerHandle.toString()}groupAndFlattenByType(e){const t={},i=[];for(const n of e)t[n.type]||(t[n.type]=[],i.push(n.type)),t[n.type].push(n);return i.flatMap(n=>t[n])}}function ct(){try{const c=new g.AcDbDxfConverter({convertByEntityType:!1,useWorker:!0,parserWorkerUrl:"./assets/dxf-parser-worker.js"});g.AcDbDatabaseConverterManager.instance.register(g.AcDbFileType.DXF,c)}catch(c){console.error("Failed to register dxf converter: ",c)}try{const c=new gi({convertByEntityType:!1,useWorker:!0,parserWorkerUrl:"./assets/libredwg-parser-worker.js"});g.AcDbDatabaseConverterManager.instance.register(g.AcDbFileType.DWG,c)}catch(c){console.error("Failed to register dwg converter: ",c)}}function pi(){ct(),typeof window<"u"&&!!window.location&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1")?Be.getInstance().initialize("/assets/mtext-renderer-worker.js"):Be.getInstance().initialize("./mtext-renderer-worker.js")}const yi={isDebug:!1,isShowCommandLine:!0,isShowCoordinate:!0,isShowToolbar:!0,isShowStats:!1,fontMapping:{}},ht="settings";class Z{constructor(){this.events={modified:new g.AcCmEventManager}}static get instance(){return this._instance||(this._instance=new Z),this._instance}set(e,t){const i=this.settings;i[e]=t,localStorage.setItem(ht,JSON.stringify(i)),this.events.modified.dispatch({key:e,value:t})}get(e){return this.settings[e]}toggle(e){const t=this.get(e);this.set(e,!t)}get isDebug(){return this.get("isDebug")}set isDebug(e){this.set("isDebug",e)}get isShowCommandLine(){return this.get("isShowCommandLine")}set isShowCommandLine(e){this.set("isShowCommandLine",e)}get isShowCoordinate(){return this.get("isShowCoordinate")}set isShowCoordinate(e){this.set("isShowCoordinate",e)}get isShowToolbar(){return this.get("isShowToolbar")}set isShowToolbar(e){this.set("isShowToolbar",e)}get isShowStats(){return this.get("isShowStats")}set isShowStats(e){this.set("isShowStats",e)}get fontMapping(){return this.get("fontMapping")}set fontMapping(e){this.set("fontMapping",e)}setFontMapping(e,t){const i=this.get("fontMapping");i[e]=t,this.set("fontMapping",i)}get settings(){const e=localStorage.getItem(ht),t=e==null?{}:JSON.parse(e);return ve.defaults(t,yi)}}w.AcApContext=Te,w.AcApConvertToSvgCmd=Ve,w.AcApDocManager=M,w.AcApDocument=Re,w.AcApOpenCmd=je,w.AcApPanCmd=Xe,w.AcApQNewCmd=ke,w.AcApSelectCmd=Fe,w.AcApSettingManager=Z,w.AcApZoomCmd=Ne,w.AcApZoomToBoxCmd=We,w.AcApZoomToBoxJig=Ue,w.AcEdBaseView=Ge,w.AcEdCommand=G,w.AcEdCommandStack=C,w.AcEdCorsorType=j,w.AcEdCursorManager=De,w.AcEdJig=ze,w.AcEdSelectionSet=Oe,w.AcEdViewMode=P,w.AcEditor=Pe,w.AcTrView2d=ot,w.DEFAULT_VIEW_2D_OPTIONS=Le,w.acedAlert=ft,w.eventBus=z,w.registerConverters=ct,w.registerWorkers=pi,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
282
+ }`;return new d.ShaderMaterial({uniforms:a,vertexShader:h,fragmentShader:l,clipping:!0})}}const xe=class ce{constructor(){this.pointMaterials={},this.lineShaderMaterials={},this.lineBasicMaterials={},this.hatchShaderMaterials=[],this.meshBasicMaterials={},this.unsupportedTextStyles={}}getPointsMaterial(e,t=2){const i=`${e}_${t}`;return this.pointMaterials[i]||(this.pointMaterials[i]=new d.PointsMaterial({size:t,color:e})),this.pointMaterials[i]}getMeshBasicMaterial(e){return this.meshBasicMaterials[e]||(this.meshBasicMaterials[e]=new d.MeshBasicMaterial({color:e})),this.meshBasicMaterials[e]}getLineBasicMaterial(e){return this.lineBasicMaterials[e]||(this.lineBasicMaterials[e]=new d.LineBasicMaterial({color:e})),this.lineBasicMaterials[e]}getLineShaderMaterial(e,t){if(e.pattern&&e.pattern.length!==0){const i=`${e.name}_${e.color}_${t}`;return this.lineShaderMaterials[i]||(this.lineShaderMaterials[i]=$t.createLineShaderMaterial(e.pattern,e.color,t,ce.ViewportScaleUniform,ce.CameraZoomUniform)),this.lineShaderMaterials[i]}else return this.getLineBasicMaterial(e.color)}getHatchShaderMaterial(e,t){if(!e.patternLines||e.patternLines.length<1)return this.getMeshBasicMaterial(e.color);let i=!1;if(e.patternLines.forEach(u=>{u.dashPattern||(i=!0,console.log("Invalid dash pattern: ",e))}),i)return;const n=this.findMatchedHatchShaderMaterial(e);if(n)return n;const s=.005,r=.05;let o=2;e.patternLines.forEach(u=>{o=Math.max(u.dashPattern.length,o)});let a=0;const h=[],l=new d.Vector2;for(const u of e.patternLines){const y=new d.Vector2(u.origin.x,u.origin.y).sub(t).rotateAround(l,-d.MathUtils.degToRad(e.patternAngle)),p=new d.Vector2(u.delta.x,u.delta.y).rotateAround(l,-d.MathUtils.degToRad(u.angle));if(p.y===0){console.warn("delta.y is equal to zero!");return}const f=u.dashPattern.length;let x=!0,b=0;for(let I=0;I<f;++I){const J=u.dashPattern[I];J>0&&(x=!1),b+=Math.abs(J)}const _=x?r:s,S=[],v=[];let A=0;v[0]=A;for(let I=0;I<f;++I)S[I]=u.dashPattern[I],S[I]===0&&(S[I]=_*b),A+=Math.abs(S[I]),v[I+1]=A;for(let I=f;I<o;++I)S[I]=0;for(let I=v.length;I<o+1;++I)v[I]=A;const O={origin:y,delta:p,angle:u.angle-e.patternAngle,pattern:S,patternSum:v,patternLength:A};if(a+=4,a+=o,a+=o+1,a>ce.MaxFragmentUniforms){console.warn("There will be warning in fragment shader when number of uniforms exceeds 1024, so extra hatch line patterns are ignored here!");break}h.push(O)}const m=Xt(h,e.patternAngle,ce.CameraZoomUniform,new d.Color(e.color));return m.defines={MAX_PATTERN_SEGMENT_COUNT:o},this.hatchShaderMaterials.push({patternLines:e.patternLines,patternAngle:e.patternAngle,color:e.color,material:m}),m}findMatchedHatchShaderMaterial(e){const t=e.patternLines;if(!t||t.length<1)return;const i=(a,h)=>Math.abs(a-h)<1e-5,n=(a,h)=>{if(a.length!==h.length)return!1;for(let l=0;l<a.length;++l)if(!i(a[l],h[l]))return!1;return!0},s=(a,h)=>i(a.angle,h.angle)&&i(a.delta.x,h.delta.x)&&i(a.delta.y,h.delta.y)&&i(a.origin.x,h.origin.x)&&i(a.origin.y,h.origin.y)&&n(a.dashPattern,h.dashPattern),r=(a,h)=>{if(a.length!==h.length)return!1;for(let l=0;l<a.length;++l)if(!s(a[l],h[l]))return!1;return!0},o=this.hatchShaderMaterials.find(a=>a.color===e.color&&a.patternAngle===e.patternAngle&&r(a.patternLines,t));return o==null?void 0:o.material}};xe.CameraZoomUniform={value:1},xe.ViewportScaleUniform={value:1},xe.MaxFragmentUniforms=1024;let Yt=xe;class Ht{constructor(e){this.events={fontNotFound:new g.AcCmEventManager},this._renderer=e,this._styleManager=new Yt,V.FontManager.instance.events.fontNotFound.addEventListener(t=>{this.events.fontNotFound.dispatch(t)})}get autoClear(){return this._renderer.autoClear}set autoClear(e){this._renderer.autoClear=e}get domElement(){return this._renderer.domElement}setSize(e,t){this._renderer.setSize(e,t)}getViewport(e){return this._renderer.getViewport(e)}setViewport(e,t,i,n){this._renderer.setViewport(e,t,i,n)}clear(){this._renderer.clear()}clearDepth(){this._renderer.clearDepth()}render(e,t){this._renderer.render(e,t.internalCamera)}setClearColor(e,t){this._renderer.setClearColor(e,t)}getClearColor(){const e=new d.Color;return this._renderer.getClearColor(e),e.getHex()}setClearAlpha(e){this._renderer.setClearAlpha(e)}getClearAlpha(){return this._renderer.getClearAlpha()}get internalRenderer(){return this._renderer}async loadFonts(e){return await V.FontManager.instance.loadFontsByUrls(e)}setFontMapping(e){V.FontManager.instance.setFontMapping(e)}get missedFonts(){return V.FontManager.instance.missedFonts}clearMissedFonts(){V.FontManager.instance.missedFonts={}}createObject(){return new tt(this._styleManager)}createEntity(){return new E(this._styleManager)}group(e){return new Rt(e,this._styleManager)}point(e,t){return new Ut(e,t,this._styleManager)}circularArc(e,t){return this.linePoints(e.getPoints(100),t)}ellipticalArc(e,t){return this.linePoints(e.getPoints(100),t)}lines(e,t){return this.linePoints(e,t)}lineSegments(e,t,i,n){return new kt(e,t,i,n,this._styleManager)}area(e,t){return new Wt(e,t,this._styleManager)}mtext(e,t,i){return new Ft(e,t,this._styleManager,i)}image(e,t){return new Vt(e,t,this._styleManager)}linePoints(e,t=void 0){return new jt(e,t,this._styleManager)}}class qt{constructor(e){this._camera=e}get position(){return this._camera.position}get left(){return this._camera.left}set left(e){this._camera.left=e}get right(){return this._camera.right}set right(e){this._camera.right=e}get top(){return this._camera.top}set top(e){this._camera.top=e}get bottom(){return this._camera.bottom}set bottom(e){this._camera.bottom=e}get zoom(){return this._camera.zoom}set zoom(e){this._camera.zoom=e}get internalCamera(){return this._camera}lookAt(e){this._camera.lookAt(e)}setRotationFromEuler(e){this._camera.setRotationFromEuler(e)}updateProjectionMatrix(){this._camera.updateProjectionMatrix()}cwcs2Wcs(e,t,i){const n=new d.Vector3(e.x,e.y,0);n.x=e.x/t*2-1,n.y=-(e.y/i)*2+1;const s=n.unproject(this._camera);return new g.AcGePoint2d(s.x,s.y)}wcs2Cwcs(e,t,i){const n=new d.Vector3(e.x,e.y,0).project(this._camera);return new g.AcGePoint2d((n.x+1)/2*t,(-n.y+1)/2*i)}wcs2Ndc(e,t,i){const n=this.wcs2Cwcs(e,t,i);return this.cwcs2Ndc(n,t,i)}cwcs2Ndc(e,t,i){return new g.AcGePoint2d(e.x/t*2-1,-(e.y/i)*2+1)}}class nt{constructor(e,t,i){this._frustum=400,this.events={viewChanged:new g.AcCmEventManager},this._renderer=e,this._width=t,this._height=i;const n=this.createCamera();this._camera=new qt(n),this._cameraControls=this.createCameraControls(),this._cameraControls.addEventListener("change",()=>{this.events.viewChanged.dispatch({view:this})}),this._raycaster=new d.Raycaster}get width(){return this._width}set width(e){this._width=e}get height(){return this._height}set height(e){this._height=e}get enabled(){return this._cameraControls.enabled}set enabled(e){this._cameraControls.enabled=e}get center(){return this._camera.cwcs2Wcs({x:this._width/2,y:this._height/2},this._width,this._height)}set center(e){this._camera.position.set(e.x,e.y,this._camera.position.z),this._camera.updateProjectionMatrix()}cwcs2Wcs(e){return this._camera.cwcs2Wcs(e,this._width,this._height)}wcs2Cwcs(e){return this._camera.wcs2Cwcs(e,this._width,this._height)}pointToBox(e,t){const i=this.wcs2Cwcs(e),n=this.cwcs2Wcs({x:i.x+t,y:i.y+t}),s=this.cwcs2Wcs({x:i.x-t,y:i.y-t});return new g.AcGeBox2d().setFromPoints([n,s])}resetRaycaster(e,t){const i=this._camera.wcs2Ndc(e,this._width,this._height);return this._raycaster.setFromCamera(new d.Vector2(i.x,i.y),this._camera.internalCamera),this._raycaster.params.Line.threshold=t,this._raycaster.params.Points.threshold=t,this._raycaster}zoomTo(e,t=1.1){const i=new g.AcGeVector2d;e.getSize(i);const n=new g.AcGeVector2d;e.getCenter(n);const s=new d.Vector3(n.x,n.y,0);this._camera.position.set(n.x,n.y,this._camera.position.z),this._camera.lookAt(s),this._camera.setRotationFromEuler(new d.Euler(0,0,0));const r=i.x*t,o=i.y*t,a=this._width/r,h=this._height/o;this._camera.zoom=Math.min(a,h),this._cameraControls.target=s,this.updateCameraFrustum()}updateCameraFrustum(e,t){const i=(e??this._width)/(t??this._height);this._camera.left=-i*this._frustum,this._camera.right=i*this._frustum,this._camera.top=this._frustum,this._camera.bottom=-this._frustum,this._camera.updateProjectionMatrix(),this._cameraControls.update()}createCamera(){const e=new d.OrthographicCamera(-this._width/2,this._width/2,this._height/2,-this._height/2,.1,1e3);return e.position.set(0,0,500),e.up.set(0,1,0),e.updateProjectionMatrix(),e}createCameraControls(){const e=new ut.OrbitControls(this._camera.internalCamera,this._renderer.domElement);return e.enableDamping=!1,e.autoRotate=!1,e.enableRotate=!1,e.zoomSpeed=5,e.mouseButtons={MIDDLE:d.MOUSE.PAN},e.update(),e}}class _e extends nt{static calculateViewportWindowBox(e,t){const i=t.box,n=new g.AcGeBox2d;return n.expandByPoint(e.wcs2Cwcs(i.min)),n.expandByPoint(e.wcs2Cwcs(i.max)),n}constructor(e,t,i){const n=_e.calculateViewportWindowBox(e,t).size;super(i,n.width,n.height),this._parentView=e,this._viewport=t.clone(),this._frustum*=t.height/e.height,this.zoomTo(this._viewport.viewBox),this.enabled=!1}get viewport(){return this._viewport}update(){this.zoomTo(this._viewport.viewBox)}render(e){const t=_e.calculateViewportWindowBox(this._parentView,this._viewport);if(!t.isEmpty()){const i=this._parentView.height-t.min.y-t.size.height;this._renderer.setViewport(t.min.x,i,t.size.width,t.size.height),this._renderer.internalRenderer.setScissor(t.min.x,i,t.size.width,t.size.height),this._renderer.internalRenderer.setScissorTest(!0),this._renderer.render(e,this._camera),this._renderer.internalRenderer.setScissorTest(!1)}}}const Qt={threeBo2dToGeBox2d:c=>new g.AcGeBox2d(c.min,c.max),geBox2dToThreeBox2d:c=>new d.Box2(c.min,c.max),threeBox3dToGeBox3d:c=>new g.AcGeBox3d(c.min,c.max),geBox3dToThreeBox3d:c=>new d.Box3(c.min,c.max),goBox3dToGeBox2d:c=>new g.AcGeBox2d(c.min,c.max),threeBox3dToGeBox2d:c=>new g.AcGeBox2d(c.min,c.max),geBox2dToThreeBox3d:c=>{const e=new d.Box3;return e.min.set(c.min.x,c.min.y,0),e.max.set(c.max.x,c.max.y,0),e}};var be=(c=>(c[c.LEFT_BOTTOM=0]="LEFT_BOTTOM",c[c.LEFT_TOP=1]="LEFT_TOP",c[c.RIGHT_TOP=2]="RIGHT_TOP",c[c.RIGHT_BOTTOM=4]="RIGHT_BOTTOM",c))(be||{});class Zt extends d.Object3D{constructor(e,t,i=150,n=2){super(),this.camera=e,this.renderer=t,this.gizmoCamera=new d.OrthographicCamera(-2,2,2,-2,0,4),this.gizmoCamera.position.set(0,0,2),this.gizmoDim=i,this.gizmoPos=n,this.initialize()}initialize(){}update(){this.updateOrientation();const e=this.renderer.autoClear;this.renderer.autoClear=!1,this.renderer.clearDepth();const t=new d.Vector4;this.renderer.getViewport(t);const i=this.calculateViewportPos();this.renderer.setViewport(i.x,i.y,this.gizmoDim,this.gizmoDim),this.renderer.render(this,this.gizmoCamera),this.renderer.setViewport(t.x,t.y,t.z,t.w),this.renderer.autoClear=e}dispose(){}updateOrientation(){this.quaternion.copy(this.camera.quaternion).invert(),this.updateMatrixWorld()}calculatePosInViewport(e,t,i){const n=(e-i.min.x)/this.gizmoDim*2-1,s=-((t-i.min.y)/this.gizmoDim)*2+1;return{x:n,y:s}}calculateViewportPos(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,s=this.gizmoDim;let r=t-s,o=i-s;switch(n){case 0:r=0,o=0;break;case 1:r=0;break;case 4:o=0;break}return{x:r,y:o}}calculateViewportBbox(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,s=this.gizmoDim,r=new d.Box2(new d.Vector2(t-s,0),new d.Vector2(t,s));switch(n){case 0:r.set(new d.Vector2(0,i-s),new d.Vector2(s,i));break;case 1:r.set(new d.Vector2(0,0),new d.Vector2(s,s));break;case 4:r.set(new d.Vector2(t-s,i-s),new d.Vector2(t,i));break}return r}}function Jt(c,e){const t=e.font||"Helvetica",i=e.fontSize||30,n=e.width||200,s=e.height||200,r=e.bgColor?e.bgColor.join(", "):"255, 255, 255, 1.0",o=e.color?e.color.join(", "):"0, 0, 0, 1.0",a=document.createElement("canvas");a.width=n,a.height=s;const h=a.getContext("2d");if(h){h.font=`bold ${i}px ${t}`,h.fillStyle=`rgba(${r})`,h.fillRect(0,0,n,s);const u=h.measureText(c).width;h.fillStyle=`rgba(${o})`,h.fillText(c,n/2-u/2,s/2+i/2-2)}const l=new d.Texture(a);return l.minFilter=d.LinearFilter,l.needsUpdate=!0,l}function Ce(c){const e=Jt(c,{fontSize:100,font:"Arial Narrow, sans-serif",color:[255,255,255,1],bgColor:[0,0,0,0]}),t=new d.SpriteMaterial({map:e,transparent:!0});return new d.Sprite(t)}be.RIGHT_TOP;const Kt={pos:be.LEFT_BOTTOM,size:100,hasZAxis:!0};class ei extends Zt{constructor(e,t,i){const n={...Kt,...i};super(e,t,n.size,i.pos),this.hasZAxis=n.hasZAxis;const s=[0,0,0,2,0,0,0,0,0,0,2,0],r=[1,0,0,1,.6,0,0,1,0,.6,1,0];this.hasZAxis&&(s.push(0,0,0,0,0,2),r.push(0,0,1,0,.6,1));const o=new d.BufferGeometry;o.setAttribute("position",new d.Float32BufferAttribute(s,3)),o.setAttribute("color",new d.Float32BufferAttribute(r,3));const a=new d.LineBasicMaterial({vertexColors:!0,toneMapped:!1});this.axes=new d.LineSegments(o,a),this.axes.position.set(-1,-1,-1),this.add(this.axes),this.xText=Ce("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=Ce("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=Ce("Z"),this.zText.position.set(-1,-1,1.5),this.add(this.zText))}setLineColors(e,t){const i=new d.Color,n=this.axes.geometry.attributes.color.array;return i.set(e),i.toArray(n,0),i.toArray(n,3),i.set(t),i.toArray(n,6),i.toArray(n,9),this.axes.geometry.attributes.color.needsUpdate=!0,this}setTextColor(e){this.xText.material.color=e,this.yText.material.color=e}dispose(){var e,t;this.axes.geometry.dispose(),this.axes.material.dispose(),this.xText.geometry.dispose(),this.xText.material.dispose(),this.yText.geometry.dispose(),this.yText.material.dispose(),this.hasZAxis&&((e=this.zText)==null||e.geometry.dispose(),(t=this.zText)==null||t.material.dispose())}}class ti extends nt{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=P.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==P.SELECTION?this._cameraControls.mouseButtons={MIDDLE:d.MOUSE.PAN}:e==P.PAN&&(this._cameraControls.mouseButtons={LEFT:d.MOUSE.PAN}),this._cameraControls.update(),this._mode=e}get viewportCount(){return this._viewportViews.size}addViewport(e){this._viewportViews.set(e.viewport.id,e)}removeViewport(e){this._viewportViews.delete(e)}resize(e,t){this._height=t,this._width=e,this.updateCameraFrustum(),this._viewportViews.forEach(i=>{i.update()})}render(e){var i;this._renderer.clear(),this._renderer.render(e.internalScene,this._camera);const t=e.modelSpaceLayout;t&&this.drawViewports(t.internalObject),(i=this._axesGizmo)==null||i.update()}createAxesGizmo(){return new ei(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:be.LEFT_BOTTOM})}drawViewports(e){if(this._viewportViews.size>0){const t=this._renderer.autoClear;this._renderer.autoClear=!1;const i=new d.Vector4;this._renderer.getViewport(i),this._renderer.clearDepth();const n=e.visible;e.visible=!0,this._viewportViews.forEach(s=>{s.render(e)}),e.visible=n,this._renderer.setViewport(i.x,i.y,i.z,i.w),this._renderer.autoClear=t}}}class ii{constructor(){this._activeLayoutBtrId="",this._layoutViews=new Map}get activeLayoutBtrId(){return this._activeLayoutBtrId}set activeLayoutBtrId(e){this._activeLayoutBtrId=e,this._layoutViews.forEach(t=>{t.enabled=t.layoutBtrId==e})}get activeLayoutView(){return this._layoutViews.get(this._activeLayoutBtrId)}has(e){return this._layoutViews.has(e)}getAt(e){return this._layoutViews.get(e)}resize(e,t){this._layoutViews.forEach(i=>{i.resize(e,t)})}add(e){this._layoutViews.set(e.layoutBtrId,e)}render(e){var t;(t=this.activeLayoutView)==null||t.render(e)}}function st(c,e,t=0,i=c.length-1,n=ni){for(;i>t;){if(i-t>600){const a=i-t+1,h=e-t+1,l=Math.log(a),m=.5*Math.exp(2*l/3),u=.5*Math.sqrt(l*m*(a-m)/a)*(h-a/2<0?-1:1),y=Math.max(t,Math.floor(e-h*m/a+u)),p=Math.min(i,Math.floor(e+(a-h)*m/a+u));st(c,e,y,p,n)}const s=c[e];let r=t,o=i;for(re(c,t,e),n(c[i],s)>0&&re(c,t,i);r<o;){for(re(c,r,o),r++,o--;n(c[r],s)<0;)r++;for(;n(c[o],s)>0;)o--}n(c[t],s)===0?re(c,t,o):(o++,re(c,o,i)),o<=e&&(t=o+1),e<=o&&(i=o-1)}}function re(c,e,t){const i=c[e];c[e]=c[t],c[t]=i}function ni(c,e){return c<e?-1:c>e?1:0}class si{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const i=[];if(!ve(e,t))return i;const n=this.toBBox,s=[];for(;t;){for(let r=0;r<t.children.length;r++){const o=t.children[r],a=t.leaf?n(o):o;ve(e,a)&&(t.leaf?i.push(o):Ee(e,a)?this._all(o,i):s.push(o))}t=s.pop()}return i}collides(e){let t=this.data;if(!ve(e,t))return!1;const i=[];for(;t;){for(let n=0;n<t.children.length;n++){const s=t.children[n],r=t.leaf?this.toBBox(s):s;if(ve(e,r)){if(t.leaf||Ee(e,r))return!0;i.push(s)}}t=i.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let i=0;i<e.length;i++)this.insert(e[i]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=t;else if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const i=this.data;this.data=t,t=i}this._insert(t,this.data.height-t.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Q([]),this}remove(e,t){if(!e)return this;let i=this.data;const n=this.toBBox(e),s=[],r=[];let o,a,h;for(;i||s.length;){if(i||(i=s.pop(),a=s[s.length-1],o=r.pop(),h=!0),i.leaf){const l=ri(e,i.children,t);if(l!==-1)return i.children.splice(l,1),s.push(i),this._condense(s),this}!h&&!i.leaf&&Ee(i,n)?(s.push(i),r.push(o),o=0,a=i,i=i.children[0]):a?(o++,i=a.children[o],h=!1):i=null}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const i=[];for(;e;)e.leaf?t.push(...e.children):i.push(...e.children),e=i.pop();return t}_build(e,t,i,n){const s=i-t+1;let r=this._maxEntries,o;if(s<=r)return o=Q(e.slice(t,i+1)),q(o,this.toBBox),o;n||(n=Math.ceil(Math.log(s)/Math.log(r)),r=Math.ceil(s/Math.pow(r,n-1))),o=Q([]),o.leaf=!1,o.height=n;const a=Math.ceil(s/r),h=a*Math.ceil(Math.sqrt(r));rt(e,t,i,h,this.compareMinX);for(let l=t;l<=i;l+=h){const m=Math.min(l+h-1,i);rt(e,l,m,a,this.compareMinY);for(let u=l;u<=m;u+=a){const y=Math.min(u+a-1,m);o.children.push(this._build(e,u,y,n-1))}}return q(o,this.toBBox),o}_chooseSubtree(e,t,i,n){for(;n.push(t),!(t.leaf||n.length-1===i);){let s=1/0,r=1/0,o;for(let a=0;a<t.children.length;a++){const h=t.children[a],l=Me(h),m=ci(e,h)-l;m<r?(r=m,s=l<s?l:s,o=h):m===r&&l<s&&(s=l,o=h)}t=o||t.children[0]}return t}_insert(e,t,i){const n=i?e:this.toBBox(e),s=[],r=this._chooseSubtree(n,this.data,t,s);for(r.children.push(e),ae(r,n);t>=0&&s[t].children.length>this._maxEntries;)this._split(s,t),t--;this._adjustParentBBoxes(n,s,t)}_split(e,t){const i=e[t],n=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,n);const r=this._chooseSplitIndex(i,s,n),o=Q(i.children.splice(r,i.children.length-r));o.height=i.height,o.leaf=i.leaf,q(i,this.toBBox),q(o,this.toBBox),t?e[t-1].children.push(o):this._splitRoot(i,o)}_splitRoot(e,t){this.data=Q([e,t]),this.data.height=e.height+1,this.data.leaf=!1,q(this.data,this.toBBox)}_chooseSplitIndex(e,t,i){let n,s=1/0,r=1/0;for(let o=t;o<=i-t;o++){const a=oe(e,0,o,this.toBBox),h=oe(e,o,i,this.toBBox),l=hi(a,h),m=Me(a)+Me(h);l<s?(s=l,n=o,r=m<r?m:r):l===s&&m<r&&(r=m,n=o)}return n||i-t}_chooseSplitAxis(e,t,i){const n=e.leaf?this.compareMinX:oi,s=e.leaf?this.compareMinY:ai,r=this._allDistMargin(e,t,i,n),o=this._allDistMargin(e,t,i,s);r<o&&e.children.sort(n)}_allDistMargin(e,t,i,n){e.children.sort(n);const s=this.toBBox,r=oe(e,0,t,s),o=oe(e,i-t,i,s);let a=we(r)+we(o);for(let h=t;h<i-t;h++){const l=e.children[h];ae(r,e.leaf?s(l):l),a+=we(r)}for(let h=i-t-1;h>=t;h--){const l=e.children[h];ae(o,e.leaf?s(l):l),a+=we(o)}return a}_adjustParentBBoxes(e,t,i){for(let n=i;n>=0;n--)ae(t[n],e)}_condense(e){for(let t=e.length-1,i;t>=0;t--)e[t].children.length===0?t>0?(i=e[t-1].children,i.splice(i.indexOf(e[t]),1)):this.clear():q(e[t],this.toBBox)}}function ri(c,e,t){if(!t)return e.indexOf(c);for(let i=0;i<e.length;i++)if(t(c,e[i]))return i;return-1}function q(c,e){oe(c,0,c.children.length,e,c)}function oe(c,e,t,i,n){n||(n=Q(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let s=e;s<t;s++){const r=c.children[s];ae(n,c.leaf?i(r):r)}return n}function ae(c,e){return c.minX=Math.min(c.minX,e.minX),c.minY=Math.min(c.minY,e.minY),c.maxX=Math.max(c.maxX,e.maxX),c.maxY=Math.max(c.maxY,e.maxY),c}function oi(c,e){return c.minX-e.minX}function ai(c,e){return c.minY-e.minY}function Me(c){return(c.maxX-c.minX)*(c.maxY-c.minY)}function we(c){return c.maxX-c.minX+(c.maxY-c.minY)}function ci(c,e){return(Math.max(e.maxX,c.maxX)-Math.min(e.minX,c.minX))*(Math.max(e.maxY,c.maxY)-Math.min(e.minY,c.minY))}function hi(c,e){const t=Math.max(c.minX,e.minX),i=Math.max(c.minY,e.minY),n=Math.min(c.maxX,e.maxX),s=Math.min(c.maxY,e.maxY);return Math.max(0,n-t)*Math.max(0,s-i)}function Ee(c,e){return c.minX<=e.minX&&c.minY<=e.minY&&e.maxX<=c.maxX&&e.maxY<=c.maxY}function ve(c,e){return e.minX<=c.maxX&&e.minY<=c.maxY&&e.maxX>=c.minX&&e.maxY>=c.minY}function Q(c){return{children:c,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function rt(c,e,t,i,n){const s=[e,t];for(;s.length;){if(t=s.pop(),e=s.pop(),t-e<=i)continue;const r=e+Math.ceil((t-e)/i/2)*i;st(c,r,e,t,n),s.push(e,r,r,t)}}class li{constructor(e){this._group=new Gt,this._name=e}get name(){return this._name}set name(e){this._name=e}get visible(){return this._group.visible}set visible(e){this._group.visible=e}get internalObject(){return this._group}get stats(){const e=this._group.stats;return{name:this._name,...e}}get entityCount(){return this._group.entityCount}rerenderPoints(e){this._group.rerenderPoints(e)}hasEntity(e){return this._group.hasEntity(e)}addEntity(e){this._group.addEntity(e)}isIntersectWith(e,t){return this._group.isIntersectWith(e,t)}remove(e){throw new Error("Not implemented yet!")}update(e){return this._group.add(e),!0}hover(e){e.forEach(t=>{this._group.hover(t)})}unhover(e){e.forEach(t=>{this._group.unhover(t)})}select(e){e.forEach(t=>{this._group.select(t)})}unselect(e){e.forEach(t=>{this._group.unselect(t)})}}class di{constructor(){this._group=new d.Group,this._indexTree=new si,this._box=new d.Box3,this._layers=new Map}get internalObject(){return this._group}get layers(){return this._layers}get box(){return this._box}get visible(){return this._group.visible}set visible(e){this._group.visible=e}get entityCount(){let e=0;return this._layers.forEach(t=>e+=t.entityCount),e}get stats(){const e=[];let t=0,i=0,n=0,s=0,r=0;return this._layers.forEach(o=>{const a=o.stats;e.push(a),n+=a.line.indexed.geometrySize+a.line.nonIndexed.geometrySize,s+=a.mesh.indexed.geometrySize+a.mesh.nonIndexed.geometrySize,r+=a.point.indexed.geometrySize+a.point.nonIndexed.geometrySize,t+=a.summary.totalGeometrySize,i+=a.summary.totalMappingSize}),{layers:e,summary:{entityCount:this.entityCount,totalSize:{line:n,mesh:s,point:r,geometry:t,mapping:i}}}}clear(){return this._layers.forEach(e=>{this._group.remove(e.internalObject)}),this._layers.clear(),this._box.makeEmpty(),this._indexTree.clear(),this}rerenderPoints(e){this._layers.forEach(t=>{t.rerenderPoints(e)})}isIntersectWith(e,t){const i=this.getLayerByObjectId(e);return i&&i.isIntersectWith(e,t)}addEntity(e,t=!0){if(!e.objectId)throw new Error("[AcTrEntity] Object id is required to add one entity!");if(!e.layerName)throw new Error("[AcTrEntity] Layer name is required to add one entity!");const i=this.getLayer(e.layerName,!0);if(i){i.addEntity(e);const n=e.box;t&&this._box.union(n),this._indexTree.insert({minX:n.min.x,minY:n.min.y,maxX:n.max.x,maxY:n.max.y,id:e.objectId})}return this}remove(e){for(const[t,i]of this._layers)if(i.remove(e))return!0;return!1}update(e){for(const[t,i]of this._layers)if(i.update(e))return!0;return!1}hover(e){e.forEach(t=>{const i=this.getLayerByObjectId(t);i&&i.hover([t])})}unhover(e){e.forEach(t=>{const i=this.getLayerByObjectId(t);i&&i.unhover([t])})}select(e){e.forEach(t=>{const i=this.getLayerByObjectId(t);i&&i.select([t])})}unselect(e){e.forEach(t=>{const i=this.getLayerByObjectId(t);i&&i.unselect([t])})}setSnapObject(e){this._snapPointsObject&&this._group.remove(this._snapPointsObject),this._snapPointsObject=e,this._group.add(e)}search(e){return this._indexTree.search({minX:e.min.x,minY:e.min.y,maxX:e.max.x,maxY:e.max.y})}getLayerByObjectId(e){for(const[t,i]of this._layers)if(i.hasEntity(e))return i}getLayer(e,t=!0){let i=this._layers.get(e);return i===void 0&&t&&(i=new li(e),this._layers.set(e,i),this._group.add(i.internalObject)),i}}class ui{constructor(){this._scene=new d.Scene,this._layers=new Map,this._layouts=new Map,this._activeLayoutBtrId="",this._modelSpaceBtrId=""}get layers(){return this._layers}get layouts(){return this._layouts}get box(){var e;return(e=this.activeLayout)==null?void 0:e.box}get internalScene(){return this._scene}get modelSpaceBtrId(){return this._modelSpaceBtrId}set modelSpaceBtrId(e){if(this._modelSpaceBtrId=e,!this._layouts.has(e))throw new Error(`[AcTrScene] No layout assiciated with the specified block table record id '${e}'!`)}get activeLayoutBtrId(){return this._activeLayoutBtrId}set activeLayoutBtrId(e){this._activeLayoutBtrId=e,this._layouts.forEach((t,i)=>{t.visible=e==i})}get activeLayout(){if(this._activeLayoutBtrId&&this._layouts.has(this._activeLayoutBtrId))return this._layouts.get(this._activeLayoutBtrId)}get modelSpaceLayout(){if(this._modelSpaceBtrId&&this._layouts.has(this._modelSpaceBtrId))return this._layouts.get(this._modelSpaceBtrId)}get stats(){const e=[];return this._layouts.forEach(t=>e.push(t.stats)),{layouts:e}}addEmptyLayout(e){const t=new di;return this._layouts.set(e,t),this._scene.add(t.internalObject),t.visible=e==this._activeLayoutBtrId,t}clear(){return this._layouts.forEach(e=>{this._scene.remove(e.internalObject),e.clear()}),this._layouts.clear(),this._scene.clear(),this}setLayerVisibility(e,t){var n;let i=!1;return(n=this.activeLayout)==null||n.layers.forEach(s=>{s.name===e&&(s.visible=t,i=!0)}),i}hover(e){return this.activeLayout?(this.activeLayout.hover(e),!0):!1}unhover(e){return this.activeLayout?(this.activeLayout.unhover(e),!0):!1}select(e){return this.activeLayout?(this.activeLayout.select(e),!0):!1}unselect(e){return this.activeLayout?(this.activeLayout.unselect(e),!0):!1}search(e){const t=this.activeLayout;return t?t==null?void 0:t.search(e):[]}addLayer(e){this._layers.set(e.name,e)}updateLayer(e){this._layers.set(e.name,e)}addEntity(e,t=!0){const i=e.ownerId;if(i){let n=this._layouts.get(i);n||(n=this.addEmptyLayout(i)),n.addEntity(e,t)}else console.warn("[AcTrSecene] The owner id of one entity cannot be empty!");return this}remove(e){for(const[t,i]of this._layouts)if(i.remove(e))return!0;return!1}update(e){for(const[t,i]of this._layouts)if(i.update(e))return!0;return!1}setSnapObject(e){return this._layouts.forEach(t=>{t.setSnapObject(e)}),this}}const Le={background:0};class ot extends Ge{constructor(e=Le){const t={...Le,...e},i=new d.WebGLRenderer({antialias:!0,alpha:!0,canvas:e.canvas});t.canvas==null&&(t.canvas=i.domElement),super(t.canvas),e.calculateSizeCallback&&this.setCalculateSizeCallback(e.calculateSizeCallback),i.setPixelRatio(Math.min(window.devicePixelRatio,2)),i.setSize(this.width,this.height),this._renderer=new Ht(i);const n=Z.instance.fontMapping;this._renderer.setFontMapping(n),this._renderer.events.fontNotFound.addEventListener(s=>{z.emit("font-not-found",{fontName:s.fontName,count:s.count??0})}),this._scene=this.createScene(),this._renderer.setClearColor(t.background||0),this._stats=this.createStats(Z.instance.isShowStats),Z.instance.events.modified.addEventListener(s=>{s.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,s.value)}),this.canvas.addEventListener("click",()=>{this.mode==P.SELECTION&&this.select()}),document.addEventListener("keydown",s=>{s.code==="Escape"&&this.selectionSet.clear()}),g.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(s=>{this.activeLayoutBtrId=s.layout.blockTableRecordId}),this._missedImages=new Map,this._layoutViewManager=new ii,this.initialize(),this.onWindowResize(),this.animate(),this._isDirty=!0}initialize(){this.setCursor(j.Crosshair)}get mode(){const e=this.activeLayoutView;return e?e.mode:P.SELECTION}set mode(e){this.activeLayoutView.mode=e,this.editor.getPoint()}get renderer(){return this._renderer}get isDirty(){return this._isDirty}set isDirty(e){this._isDirty=e}get missedData(){return{fonts:this._renderer.missedFonts,images:this._missedImages}}get center(){return this.activeLayoutView.center}set center(e){this.activeLayoutView.center=e}get backgroundColor(){return this._renderer.getClearColor()}set backgroundColor(e){this._renderer.setClearColor(e),this._isDirty=!0}get modelSpaceBtrId(){return this._scene.modelSpaceBtrId}set modelSpaceBtrId(e){this._scene.modelSpaceBtrId=e}get activeLayoutBtrId(){return this._scene.activeLayoutBtrId}set activeLayoutBtrId(e){this._layoutViewManager.activeLayoutBtrId=e,this._scene.activeLayoutBtrId=e,this._isDirty=!0}get activeLayoutView(){return this._layoutViewManager.activeLayoutView}get stats(){return this._scene.stats}animate(){var e;requestAnimationFrame(this.animate.bind(this)),this._isDirty&&(this._layoutViewManager.render(this._scene),(e=this._stats)==null||e.update(),this._isDirty=!1)}cwcs2Wcs(e){const t=this.activeLayoutView;return t?t.cwcs2Wcs(e):new g.AcGePoint2d(e)}wcs2Cwcs(e){const t=this.activeLayoutView;return t?t.wcs2Cwcs(e):new g.AcGePoint2d(e)}zoomTo(e,t=1.1){this.activeLayoutView.zoomTo(e,t),this._isDirty=!0}rerenderPoints(e){const t=this._scene.activeLayout;t&&(t.rerenderPoints(e),this._isDirty=!0)}zoomToFit(){if(this._scene.box){const e=Qt.threeBox3dToGeBox2d(this._scene.box);this.zoomTo(e),this._isDirty=!0}}pick(e){e==null&&(e=this.curPos);const t=[],i=this._scene.activeLayout;if(i){const n=this.activeLayoutView,s=n.pointToBox(e,this.selectionBoxSize),r=this._scene.search(s),o=Math.max(s.size.width/2,s.size.height/2),a=n.resetRaycaster(e,o);r.forEach(h=>{const l=h.id;i.isIntersectWith(l,a)&&t.push(l)})}return t}search(e){return this._scene.search(e)}select(e){const t=[];this.pick(e).forEach(n=>t.push(n)),t.length>0&&this.selectionSet.add(t)}selectByBox(e){const t=[];this._scene.search(e).forEach(n=>t.push(n.id)),this.selectionSet.add(t)}addLayer(e){this._scene.addLayer({name:e.name,isFrozen:e.isFrozen,isOff:e.isOff})}updateLayer(e){this._scene.updateLayer({name:e.name,isFrozen:e.isFrozen,isOff:e.isOff})}addEntity(e){const t=Array.isArray(e)?e:[e];setTimeout(async()=>{await this.batchConvert(t)})}removeEntity(e){this._scene.remove(e)}updateEntity(e){let t=[];Array.isArray(e)?t=e:t.push(e);for(let i=0;i<t.length;++i){const n=t[i],s=n.draw(this._renderer,!0);s&&(s.objectId=n.objectId,s.ownerId=n.ownerId,s.layerName=n.layer,s.visible=n.visibility,this._scene.update(s))}this._isDirty=!0,setTimeout(()=>{this._isDirty=!0},100)}addLayout(e){this._scene.addEmptyLayout(e.blockTableRecordId),this.createLayoutViewIfNeeded(e.blockTableRecordId)}clear(){this._scene.clear(),this._isDirty=!0,this._missedImages.clear(),this._renderer.clearMissedFonts()}highlight(e){this._isDirty=this._scene.select(e)}unhighlight(e){this._isDirty=this._scene.unselect(e)}setLayerVisibility(e,t){this._isDirty=this._scene.setLayerVisibility(e,t)}onHover(e){this._isDirty=this._scene.hover([e])}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){const e=new ui;return e.layouts.forEach(t=>{t.setSnapObject(this.renderer.createObject())}),e}createStats(e){const t=new mt;document.body.appendChild(t.dom);const i=t.dom;return i.style.position="fixed",i.style.inset="unset",i.style.bottom="30px",i.style.right="0px",this.toggleStatsVisibility(t,e),t}onWindowResize(){super.onWindowResize(),this._renderer.setSize(this.width,this.height),this._layoutViewManager.resize(this.width,this.height),this._isDirty=!0}createLayoutViewIfNeeded(e){let t=this._layoutViewManager.getAt(e);return t==null&&(t=new ti(this._renderer,e,this.width,this.height),t.events.viewChanged.addEventListener(()=>{this._isDirty=!0}),this._layoutViewManager.add(t)),t}toggleStatsVisibility(e,t){t?e.dom.style.display="block":e.dom.style.display="none"}async batchConvert(e){for(let t=0;t<e.length;++t){const i=e[t],n=i.draw(this._renderer);if(n){n.objectId=i.objectId,n.ownerId=i.ownerId,n.layerName=i.layer,n.visible=i.visibility;const s=!(i instanceof g.AcDbRay||i instanceof g.AcDbXline);if(await n.draw().then(()=>{this._scene.addEntity(n,s),n.dispose(),this._isDirty=!0}),i instanceof g.AcDbViewport){if(i.number>1){const r=this._layoutViewManager.getAt(i.ownerId);if(r){const o=new _e(r,i.toGiViewport(),this._renderer);r.addViewport(o)}}}else if(i instanceof g.AcDbRasterImage){const r=i.imageFileName;r&&this._missedImages.set(i.objectId,r)}}}}}class mi{constructor(e){this._cadRenderer=e,this._avaiableFonts=[]}get avaiableFonts(){return this._avaiableFonts}async getAvaiableFonts(){if(this._avaiableFonts.length==0){const e="https://cdn.jsdelivr.net/gh/mlight-lee/cad-data/fonts/",t=e+"fonts.json";try{const i=await fetch(t);this._avaiableFonts=await i.json()}catch{z.emit("failed-to-get-avaiable-fonts",{url:t})}this._avaiableFonts.forEach(i=>{i.url=e+i.file})}return this._avaiableFonts}async load(e){await this.getAvaiableFonts();const t=[];e.forEach(n=>{const s=n.toLowerCase(),r=Se.find(this._avaiableFonts,o=>Se.findIndex(o.name,a=>a.toLowerCase()==s)>=0);r&&t.push(r.url)}),(await this._cadRenderer.loadFonts(t)).forEach(n=>{n.status||z.emit("font-not-loaded",{fontName:n.fontName,url:n.url})})}}class M{constructor(e){this.events={documentCreated:new g.AcCmEventManager,documentActivated:new g.AcCmEventManager};const t=new Re;t.database.events.openProgress.addEventListener(s=>{z.emit("open-file-progress",{database:t.database,percentage:s.percentage,stage:s.stage,subStage:s.subStage,stageStatus:s.stageStatus})});const i=()=>({width:window.innerWidth,height:window.innerHeight-30}),n=new ot({canvas:e,calculateSizeCallback:i});this._context=new Te(n,t),this._fontLoader=new mi(n.renderer),g.acdbHostApplicationServices().workingDatabase=t.database,this.registerCommands()}static createInstance(e){return M._instance==null&&(M._instance=new M(e)),this._instance}static get instance(){return M._instance||(M._instance=new M),M._instance}get context(){return this._context}get curDocument(){return this._context.doc}get mdiActiveDocument(){return this._context.doc}get curView(){return this._context.view}get editor(){return this._context.view.editor}get avaiableFonts(){return this._fontLoader.avaiableFonts}async loadFonts(e){await this._fontLoader.load(e)}async loadDefaultFonts(e){e==null?await this._fontLoader.load(["simkai"]):await this._fontLoader.load(e)}async openUrl(e,t){this.onBeforeOpenDocument(),t=this.setOptions(t);const i=await this.context.doc.openUri(e,t);return this.onAfterOpenDocument(i),i}async openDocument(e,t,i){this.onBeforeOpenDocument(),i=this.setOptions(i);const n=await this.context.doc.openDocument(e,t,i);return this.onAfterOpenDocument(n),n}registerCommands(){const e=C.instance;e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"pan","pan",new Xe),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"select","select",new Fe),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"zoom","zoom",new Ne),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"zoomw","zoomw",new We),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"csvg","csvg",new Ve),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"qnew","qnew",new ke),e.addCommand(C.SYSTEMT_COMMAND_GROUP_NAME,"open","open",new je)}sendStringToExecute(e){const i=C.instance.lookupGlobalCmd(e);i==null||i.execute(this.context)}setActiveLayout(){const e=this.curView;e.activeLayoutBtrId=this.curDocument.database.currentSpaceId,e.modelSpaceBtrId=this.curDocument.database.currentSpaceId}onBeforeOpenDocument(){this.curView.clear()}onAfterOpenDocument(e){if(e){const t=this.context.doc;this.events.documentActivated.dispatch({doc:t}),this.setActiveLayout();const i=t.database;this.curView.zoomTo(new g.AcGeBox2d(i.extmin,i.extmax))}}setOptions(e){return e==null?e={fontLoader:this._fontLoader}:e.fontLoader==null&&(e.fontLoader=this._fontLoader),e}}class at{convert(e){const t=this.createEntity(e);return t&&this.processCommonAttrs(e,t),t}createEntity(e){return e.type=="ARC"?this.convertArc(e):e.type=="CIRCLE"?this.convertCirle(e):e.type=="DIMENSION"?this.convertDimension(e):e.type=="ELLIPSE"?this.convertEllipse(e):e.type=="HATCH"?this.convertHatch(e):e.type=="IMAGE"?this.convertImage(e):e.type=="LEADER"?this.convertLeader(e):e.type=="LINE"?this.convertLine(e):e.type=="LWPOLYLINE"?this.convertLWPolyline(e):e.type=="MTEXT"?this.convertMText(e):e.type=="POINT"?this.convertPoint(e):e.type=="POLYLINE"?this.convertPolyline(e):e.type=="RAY"?this.convertRay(e):e.type=="SPLINE"?this.convertSpline(e):e.type=="ACAD_TABLE"?this.convertTable(e):e.type=="TEXT"?this.convertText(e):e.type=="SOLID"?this.convertSolid(e):e.type=="VIEWPORT"?this.convertViewport(e):e.type=="WIPEOUT"?this.convertWipeout(e):e.type=="XLINE"?this.convertXline(e):e.type=="INSERT"?this.convertBlockReference(e):null}convertArc(e){return new g.AcDbArc(e.center,e.radius,e.startAngle,e.endAngle)}convertCirle(e){return new g.AcDbCircle(e.center,e.radius)}convertEllipse(e){const t=new g.AcGeVector3d(e.majorAxisEndPoint),i=t.length();return new g.AcDbEllipse(e.center,g.AcGeVector3d.Z_AXIS,t,i,i*e.axisRatio,e.startAngle,e.endAngle)}convertLine(e){const t=e.startPoint,i=e.endPoint;return new g.AcDbLine(new g.AcGePoint3d(t.x,t.y,t.z),new g.AcGePoint3d(i.x,i.y,i.z))}convertSpline(e){return e.numberOfControlPoints>0&&e.numberOfKnots>0?new g.AcDbSpline(e.controlPoints,e.knots,e.weights,e.degree,!!(e.flag&1)):e.numberOfFitPoints>0?new g.AcDbSpline(e.fitPoints,"Uniform",e.degree,!!(e.flag&1)):null}convertPoint(e){const t=new g.AcDbPoint;return t.position=e.position,t}convertSolid(e){const t=new g.AcDbTrace;return t.setPointAt(0,{...e.corner1,z:0}),t.setPointAt(1,{...e.corner2,z:0}),t.setPointAt(2,{...e.corner3,z:0}),t.setPointAt(3,e.corner4?{...e.corner4,z:0}:{...e.corner3,z:0}),t.thickness=e.thickness,t}convertLWPolyline(e){const t=new g.AcDbPolyline;return t.closed=!!(e.flag&512),e.vertices.forEach((i,n)=>{t.addVertexAt(n,new g.AcGePoint2d(i.x,i.y),i.bulge,i.startWidth,i.endWidth)}),t}convertPolyline(e){const t=new g.AcDbPolyline;return t.closed=!!(e.flag&1),e.vertices.forEach((i,n)=>{t.addVertexAt(n,new g.AcGePoint2d(i.x,i.y),i.bulge,i.startWidth,i.endWidth)}),t}convertHatch(e){var t;const i=new g.AcDbHatch;return(t=e.definitionLines)==null||t.forEach(n=>{i.definitionLines.push({angle:n.angle,origin:n.base,delta:n.offset,dashPattern:n.numberOfDashLengths>0?n.dashLengths:[]})}),i.hatchStyle=e.hatchStyle,i.patternName=e.patternName,i.patternType=e.patternType,i.patternAngle=e.patternAngle==null?0:e.patternAngle,i.patternScale=e.patternScale==null?0:e.patternScale,e.boundaryPaths.forEach(n=>{if(n.boundaryPathTypeFlag&2){const s=n,r=new g.AcGePolyline2d;r.closed=s.isClosed,s.vertices.forEach((o,a)=>{r.addVertexAt(a,{x:o.x,y:o.y,bulge:o.bulge})}),i.add(r)}else{const s=n,r=new g.AcGeLoop2d;s.edges.forEach(o=>{if(o.type==1){const a=o;r.add(new g.AcGeLine2d(a.start,a.end))}else if(o.type==2){const a=o;r.add(new g.AcGeCircArc2d(a.center,a.radius,a.startAngle,a.endAngle,!a.isCCW))}else if(o.type==3){const a=o;new g.AcGeVector2d().subVectors(a.end,a.center);const h=Math.sqrt(Math.pow(a.end.x,2)+Math.pow(a.end.y,2)),l=h*a.lengthOfMinorAxis;let m=a.startAngle,u=a.endAngle;const y=Math.atan2(a.end.y,a.end.x);a.isCCW||(m=Math.PI*2-m,u=Math.PI*2-u),r.add(new g.AcGeEllipseArc2d({...a.center,z:0},h,l,m,u,!a.isCCW,y))}else if(o.type==4){const a=o;if(a.numberOfControlPoints>0&&a.numberOfKnots>0){const h=a.controlPoints.map(u=>({x:u.x,y:u.y,z:0}));let l=!0;const m=a.controlPoints.map(u=>(u.weight==null&&(l=!1),u.weight||1));r.add(new g.AcGeSpline3d(h,a.knots,l?m:void 0))}else if(a.numberOfFitData>0){const h=a.fitDatum.map(l=>({x:l.x,y:l.y,z:0}));r.add(new g.AcGeSpline3d(h,"Uniform"))}}}),i.add(r)}}),i}convertTable(e){const t=new g.AcDbTable(e.name,e.rowCount,e.columnCount);return t.attachmentPoint=e.attachmentPoint,t.position.copy(e.startPoint),e.columnWidthArr.forEach((i,n)=>t.setColumnWidth(n,i)),e.rowHeightArr.forEach((i,n)=>t.setRowHeight(n,i)),e.cells.forEach((i,n)=>{t.setCell(n,i)}),t}convertText(e){const t=new g.AcDbText;return t.textString=e.text,t.styleName=e.styleName,t.height=e.textHeight,t.position.copy(e.startPoint),t.rotation=e.rotation,t.oblique=e.obliqueAngle??0,t.thickness=e.thickness,t.horizontalMode=e.halign,t.verticalMode=e.valign,t.widthFactor=e.xScale??1,t}convertMText(e){const t=new g.AcDbMText;return t.contents=e.text,e.styleName!=null&&(t.styleName=e.styleName),t.height=e.textHeight,t.width=e.rectWidth,t.rotation=e.rotation||0,t.location=e.insertionPoint,t.attachmentPoint=e.attachmentPoint,e.direction&&(t.direction=new g.AcGeVector3d(e.direction)),t.drawingDirection=e.drawingDirection,t}convertLeader(e){const t=new g.AcDbLeader;return e.vertices.forEach(i=>{t.appendVertex(i)}),t.hasArrowHead=e.isArrowheadEnabled,t.hasHookLine=e.isHooklineExists,t.isSplined=e.isSpline,t.dimensionStyle=e.styleName,t.annoType=e.leaderCreationFlag,t}convertDimension(e){if(e.subclassMarker=="AcDbAlignedDimension"||e.subclassMarker=="AcDbRotatedDimension"){const t=e,i=new g.AcDbAlignedDimension(t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return i.rotation=t.rotationAngle,this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDb3PointAngularDimension"){const t=e,i=new g.AcDb3PointAngularDimension(t.centerPoint,t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbOrdinateDimension"){const t=e,i=new g.AcDbOrdinateDimension(t.subDefinitionPoint1,t.subDefinitionPoint2);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbRadialDimension"){const t=e,i=new g.AcDbRadialDimension(t.definitionPoint,t.centerPoint,t.leaderLength);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbDiametricDimension"){const t=e,i=new g.AcDbDiametricDimension(t.definitionPoint,t.centerPoint,t.leaderLength);return this.processDimensionCommonAttrs(e,i),i}return null}processImage(e,t){t.position.copy(e.position),t.brightness=e.brightness,t.contrast=e.contrast,t.fade=e.fade,t.imageDefId=e.imageDefHandle.toString(),t.isClipped=(e.flags|4)>0,t.isImageShown=(e.flags|3)>0,t.isImageTransparent=(e.flags|8)>0,e.clippingBoundaryPath.forEach(i=>{t.clipBoundary.push(new g.AcGePoint2d(i))}),t.clipBoundaryType=e.clippingBoundaryType,t.width=Math.sqrt(e.uPixel.x**2+e.uPixel.y**2+e.uPixel.z**2)*e.imageSize.x,t.height=Math.sqrt(e.vPixel.x**2+e.vPixel.y**2+e.vPixel.z**2)*e.imageSize.y,t.rotation=Math.atan2(e.uPixel.y,e.uPixel.x)}convertImage(e){const t=new g.AcDbRasterImage;return this.processImage(e,t),t}convertWipeout(e){const t=new g.AcDbWipeout;return this.processImage(e,t),t}convertViewport(e){const t=new g.AcDbViewport;return t.number=e.viewportId,t.centerPoint.copy(e.viewportCenter),t.height=e.height,t.width=e.width,t.viewCenter.copy(e.displayCenter),t.viewHeight=e.viewHeight,t}convertRay(e){const t=new g.AcDbRay;return t.basePoint.copy(e.firstPoint),t.unitDir.copy(e.unitDirection),t}convertXline(e){const t=new g.AcDbXline;return t.basePoint.copy(e.firstPoint),t.unitDir.copy(e.unitDirection),t}convertBlockReference(e){const t=new g.AcDbBlockReference(e.name);return e.insertionPoint&&t.position.copy(e.insertionPoint),t.scaleFactors.x=e.xScale,t.scaleFactors.y=e.yScale,t.scaleFactors.z=e.zScale,t.rotation=e.rotation,t.normal.copy(e.extrusionDirection),t}processDimensionCommonAttrs(e,t){t.dimBlockId=e.name,t.textPosition.copy(e.textPoint),t.textRotation=e.textRotation||0,e.textLineSpacingFactor&&(t.textLineSpacingFactor=e.textLineSpacingFactor),e.textLineSpacingStyle&&(t.textLineSpacingStyle=e.textLineSpacingStyle),t.dimensionStyleName=e.styleName,t.dimensionText=e.text||"",t.measurement=e.measurement}processCommonAttrs(e,t){t.layer=e.layer,t.objectId=e.handle.toString(),t.ownerId=e.ownerBlockRecordSoftId.toString(),e.lineType!=null&&(t.lineType=e.lineType),e.lineweight!=null&&(t.lineWeight=e.lineweight),e.lineTypeScale!=null&&(t.linetypeScale=e.lineTypeScale),e.color!=null&&(t.color.color=e.color),e.colorIndex!=null&&(t.color.colorIndex=e.colorIndex),e.colorName!=null&&(t.color.colorName=e.colorName),e.isVisible!=null&&(t.visibility=e.isVisible),e.transparency!=null&&(t.transparency=e.transparency)}}class gi extends g.AcDbDatabaseConverter{constructor(e={}){super(e),e.useWorker=!0,e.parserWorkerUrl||(e.parserWorkerUrl="/assets/libredwg-parser-worker.js")}async parse(e){if(this.config.useWorker&&this.config.parserWorkerUrl){const t=g.createWorkerApi({workerUrl:this.config.parserWorkerUrl,maxConcurrentWorkers:1}),i=await t.execute(e);return t.destroy(),i.data}else throw new Error("dwg converter can run in web worker only!")}getFonts(e){const t=new Map;e.tables.BLOCK_RECORD.entries.forEach(r=>{t.set(r.name,r)});const i=new Map,n=r=>{if(r){const o=r.lastIndexOf(".");return o>=0?r.substring(0,o).toLowerCase():r.toLowerCase()}};e.tables.STYLE.entries.forEach(r=>{const o=[];let a=n(r.font);a&&o.push(a),a=n(r.bigFont),a&&o.push(a),i.set(r.name,o)});const s=new Set;return this.getFontsInBlock(e.entities,t,i,s),Array.from(s)}getFontsInBlock(e,t,i,n){const s=/\\f(.*?)\|/g;e.forEach(r=>{if(r.type=="MTEXT"){const o=r;[...o.text.matchAll(s)].forEach(h=>{n.add(h[1].toLowerCase())});const a=i.get(o.styleName);a==null||a.forEach(h=>n.add(h))}else if(r.type=="TEXT"){const o=r,a=i.get(o.styleName);a==null||a.forEach(h=>n.add(h))}else if(r.type=="INSERT"){const o=r,a=t.get(o.name);a&&this.getFontsInBlock(a.entities,t,i,n)}})}processLineTypes(e,t){e.tables.LTYPE.entries.forEach(i=>{const n={name:i.name,description:i.description,standardFlag:i.standardFlag,totalPatternLength:i.totalPatternLength,pattern:i.pattern},s=new g.AcDbLinetypeTableRecord(n);this.processCommonTableEntryAttrs(i,s),s.name=i.name,t.tables.linetypeTable.add(s)})}processTextStyles(e,t){e.tables.STYLE.entries.forEach(i=>{const n=new g.AcDbTextStyleTableRecord(i);this.processCommonTableEntryAttrs(i,n),t.tables.textStyleTable.add(n)})}processDimStyles(e,t){e.tables.DIMSTYLE.entries.forEach(i=>{const n={name:i.name,ownerId:i.ownerHandle.toString(),dimpost:i.DIMPOST||"",dimapost:i.DIMAPOST||"",dimscale:i.DIMSCALE,dimasz:i.DIMASZ,dimexo:i.DIMEXO,dimdli:i.DIMDLI,dimexe:i.DIMEXE,dimrnd:i.DIMRND,dimdle:i.DIMDLE,dimtp:i.DIMTP,dimtm:i.DIMTM,dimtxt:i.DIMTXT,dimcen:i.DIMCEN,dimtsz:i.DIMTSZ,dimaltf:i.DIMALTF,dimlfac:i.DIMLFAC,dimtvp:i.DIMTVP,dimtfac:i.DIMTFAC,dimgap:i.DIMGAP,dimaltrnd:i.DIMALTRND,dimtol:i.DIMTOL==null||i.DIMTOL==0?0:1,dimlim:i.DIMLIM==null||i.DIMLIM==0?0:1,dimtih:i.DIMTIH==null||i.DIMTIH==0?0:1,dimtoh:i.DIMTOH==null||i.DIMTOH==0?0:1,dimse1:i.DIMSE1==null||i.DIMSE1==0?0:1,dimse2:i.DIMSE2==null||i.DIMSE2==0?0:1,dimtad:i.DIMTAD,dimzin:i.DIMZIN,dimazin:i.DIMAZIN,dimalt:i.DIMALT,dimaltd:i.DIMALTD,dimtofl:i.DIMTOFL,dimsah:i.DIMSAH,dimtix:i.DIMTIX,dimsoxd:i.DIMSOXD,dimclrd:i.DIMCLRD,dimclre:i.DIMCLRE,dimclrt:i.DIMCLRT,dimadec:i.DIMADEC||0,dimunit:i.DIMUNIT||2,dimdec:i.DIMDEC,dimtdec:i.DIMTDEC,dimaltu:i.DIMALTU,dimalttd:i.DIMALTTD,dimaunit:i.DIMAUNIT,dimfrac:i.DIMFRAC,dimlunit:i.DIMLUNIT,dimdsep:i.DIMDSEP,dimtmove:i.DIMTMOVE||0,dimjust:i.DIMJUST,dimsd1:i.DIMSD1,dimsd2:i.DIMSD2,dimtolj:i.DIMTOLJ,dimtzin:i.DIMTZIN,dimaltz:i.DIMALTZ,dimalttz:i.DIMALTTZ,dimfit:i.DIMFIT||0,dimupt:i.DIMUPT,dimatfit:i.DIMATFIT,dimtxsty:"Standard",dimldrblk:"",dimblk:i.DIMBLK||"",dimblk1:i.DIMBLK1||"",dimblk2:i.DIMBLK2||"",dimlwd:i.DIMLWD,dimlwe:i.DIMLWE},s=new g.AcDbDimStyleTableRecord(n);this.processCommonTableEntryAttrs(i,s),t.tables.dimStyleTable.add(s)})}processLayers(e,t){e.tables.LAYER.entries.forEach(i=>{const n=new g.AcCmColor;n.colorIndex=i.colorIndex;const s=new g.AcDbLayerTableRecord({name:i.name,standardFlags:i.standardFlag,linetype:i.lineType,lineWeight:i.lineweight,isOff:i.off,color:n,isPlottable:i.plotFlag!=0});this.processCommonTableEntryAttrs(i,s),t.tables.layerTable.add(s)})}processViewports(e,t){e.tables.VPORT.entries.forEach(i=>{const n=new g.AcDbViewportTableRecord;this.processCommonTableEntryAttrs(i,n),i.circleSides&&(n.circleSides=i.circleSides),n.standardFlag=i.standardFlag,n.center.copy(i.center),n.lowerLeftCorner.copy(i.lowerLeftCorner),n.upperRightCorner.copy(i.upperRightCorner),i.snapBasePoint&&n.snapBase.copy(i.snapBasePoint),i.snapRotationAngle&&(n.snapAngle=i.snapRotationAngle),i.snapSpacing&&n.snapIncrements.copy(i.snapSpacing),i.majorGridLines&&(n.gridMajor=i.majorGridLines),i.gridSpacing&&n.gridIncrements.copy(i.gridSpacing),i.backgroundObjectId&&(n.backgroundObjectId=i.backgroundObjectId),n.gsView.center.copy(i.center),n.gsView.viewDirectionFromTarget.copy(i.viewDirectionFromTarget),n.gsView.viewTarget.copy(i.viewTarget),i.lensLength&&(n.gsView.lensLength=i.lensLength),i.frontClippingPlane&&(n.gsView.frontClippingPlane=i.frontClippingPlane),i.backClippingPlane&&(n.gsView.backClippingPlane=i.backClippingPlane),i.viewHeight&&(n.gsView.viewHeight=i.viewHeight),i.viewTwistAngle&&(n.gsView.viewTwistAngle=i.viewTwistAngle),i.frozenLayers&&(n.gsView.frozenLayers=i.frozenLayers),i.styleSheet&&(n.gsView.styleSheet=i.styleSheet),i.renderMode&&(n.gsView.renderMode=i.renderMode),i.viewMode&&(n.gsView.viewMode=i.viewMode),i.ucsIconSetting&&(n.gsView.ucsIconSetting=i.ucsIconSetting),i.ucsOrigin&&n.gsView.ucsOrigin.copy(i.ucsOrigin),i.ucsXAxis&&n.gsView.ucsXAxis.copy(i.ucsXAxis),i.ucsYAxis&&n.gsView.ucsYAxis.copy(i.ucsYAxis),i.orthographicType&&(n.gsView.orthographicType=i.orthographicType),i.shadePlotSetting&&(n.gsView.shadePlotSetting=i.shadePlotSetting),i.shadePlotObjectId&&(n.gsView.shadePlotObjectId=i.shadePlotObjectId),i.visualStyleObjectId&&(n.gsView.visualStyleObjectId=i.visualStyleObjectId),i.isDefaultLightingOn&&(n.gsView.isDefaultLightingOn=i.isDefaultLightingOn),i.defaultLightingType&&(n.gsView.defaultLightingType=i.defaultLightingType),i.brightness&&(n.gsView.brightness=i.brightness),i.contrast&&(n.gsView.contrast=i.contrast),i.ambientColor&&(n.gsView.ambientColor=i.ambientColor),t.tables.viewportTable.add(n)})}processBlockTables(e,t){e.tables.BLOCK_RECORD.entries.forEach(i=>{let n=t.tables.blockTable.getAt(i.name);n||(n=new g.AcDbBlockTableRecord,n.objectId=i.handle.toString(),n.name=i.name,n.ownerId=i.ownerHandle.toString(),n.origin.copy(i.basePoint),n.layoutId=i.layout.toString(),t.tables.blockTable.add(n)),!n.isModelSapce&&!n.isPaperSapce&&i.entities&&i.entities.length>0&&this.processEntitiesInBlock(i.entities,n)})}processBlocks(e,t){}async processEntitiesInBlock(e,t){const i=new at,n=e.length,s=[];for(let r=0;r<n;r++){const o=e[r],a=i.convert(o);a&&s.push(a)}t.appendEntity(s)}async processEntities(e,t,i,n,s){const r=new at;let o=e.entities;const a=o.length,h=new g.AcDbBatchProcessing(a,100-n.value,i);this.config.convertByEntityType&&(o=this.groupAndFlattenByType(o));const l=t.tables.blockTable.modelSpace;await h.processChunk(async(m,u)=>{const y=[];for(let p=m;p<u;p++){const f=o[p],x=r.convert(f);x&&y.push(x)}if(l.appendEntity(y),s){let p=n.value+u/a*(100-n.value);p>100&&(p=100),await s(p,"ENTITY","IN-PROGRESS")}})}processHeader(e,t){const i=e.header;t.cecolor.colorIndex=i.CECOLOR||256,t.angBase=i.ANGBASE??0,t.angDir=i.ANGDIR??0,t.aunits=i.AUNITS??0,t.extmax=i.EXTMAX,t.extmin=i.EXTMIN,t.insunits=i.INSUNITS??1,t.pdmode=i.PDMODE??0,t.pdsize=i.PDSIZE??0}processCommonTableEntryAttrs(e,t){t.name=e.name,t.objectId=e.handle.toString(),t.ownerId=e.ownerHandle.toString()}processObjects(e,t){this.processLayouts(e,t),this.processImageDefs(e,t)}processLayouts(e,t){const i=t.dictionaries.layouts;e.objects.LAYOUT.forEach(n=>{const s=new g.AcDbLayout;s.layoutName=n.layoutName,s.tabOrder=n.tabOrder;const r=t.tables.blockTable.newIterator();s.objectId=n.handle.toString();for(const o of r)if(o.layoutId===s.objectId){s.blockTableRecordId=o.objectId;break}s.limits.min.copy(n.minLimit),s.limits.max.copy(n.maxLimit),s.extents.min.copy(n.minExtent),s.extents.max.copy(n.maxExtent),this.processCommonObjectAttrs(n,s),i.setAt(s.layoutName,s)})}processImageDefs(e,t){const i=t.dictionaries.imageDefs;e.objects.IMAGEDEF.forEach(n=>{const s=new g.AcDbRasterImageDef;s.sourceFileName=n.fileName,this.processCommonObjectAttrs(n,s),i.setAt(s.objectId,s)})}processCommonObjectAttrs(e,t){t.objectId=e.handle.toString(),t.ownerId=e.ownerHandle.toString()}groupAndFlattenByType(e){const t={},i=[];for(const n of e)t[n.type]||(t[n.type]=[],i.push(n.type)),t[n.type].push(n);return i.flatMap(n=>t[n])}}function ct(){try{const c=new g.AcDbDxfConverter({convertByEntityType:!1,useWorker:!0,parserWorkerUrl:"./assets/dxf-parser-worker.js"});g.AcDbDatabaseConverterManager.instance.register(g.AcDbFileType.DXF,c)}catch(c){console.error("Failed to register dxf converter: ",c)}try{const c=new gi({convertByEntityType:!1,useWorker:!0,parserWorkerUrl:"./assets/libredwg-parser-worker.js"});g.AcDbDatabaseConverterManager.instance.register(g.AcDbFileType.DWG,c)}catch(c){console.error("Failed to register dwg converter: ",c)}}function pi(){ct(),typeof window<"u"&&!!window.location&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1")?pe.getInstance().initialize("/assets/mtext-renderer-worker.js"):pe.getInstance().initialize("./mtext-renderer-worker.js")}const yi={isDebug:!1,isShowCommandLine:!0,isShowCoordinate:!0,isShowToolbar:!0,isShowStats:!1,fontMapping:{}},ht="settings";class Z{constructor(){this.events={modified:new g.AcCmEventManager}}static get instance(){return this._instance||(this._instance=new Z),this._instance}set(e,t){const i=this.settings;i[e]=t,localStorage.setItem(ht,JSON.stringify(i)),this.events.modified.dispatch({key:e,value:t})}get(e){return this.settings[e]}toggle(e){const t=this.get(e);this.set(e,!t)}get isDebug(){return this.get("isDebug")}set isDebug(e){this.set("isDebug",e)}get isShowCommandLine(){return this.get("isShowCommandLine")}set isShowCommandLine(e){this.set("isShowCommandLine",e)}get isShowCoordinate(){return this.get("isShowCoordinate")}set isShowCoordinate(e){this.set("isShowCoordinate",e)}get isShowToolbar(){return this.get("isShowToolbar")}set isShowToolbar(e){this.set("isShowToolbar",e)}get isShowStats(){return this.get("isShowStats")}set isShowStats(e){this.set("isShowStats",e)}get fontMapping(){return this.get("fontMapping")}set fontMapping(e){this.set("fontMapping",e)}setFontMapping(e,t){const i=this.get("fontMapping");i[e]=t,this.set("fontMapping",i)}get settings(){const e=localStorage.getItem(ht),t=e==null?{}:JSON.parse(e);return Se.defaults(t,yi)}}w.AcApContext=Te,w.AcApConvertToSvgCmd=Ve,w.AcApDocManager=M,w.AcApDocument=Re,w.AcApOpenCmd=je,w.AcApPanCmd=Xe,w.AcApQNewCmd=ke,w.AcApSelectCmd=Fe,w.AcApSettingManager=Z,w.AcApZoomCmd=Ne,w.AcApZoomToBoxCmd=We,w.AcApZoomToBoxJig=Ue,w.AcEdBaseView=Ge,w.AcEdCommand=G,w.AcEdCommandStack=C,w.AcEdCorsorType=j,w.AcEdCursorManager=De,w.AcEdJig=ze,w.AcEdSelectionSet=Oe,w.AcEdViewMode=P,w.AcEditor=Pe,w.AcTrView2d=ot,w.DEFAULT_VIEW_2D_OPTIONS=Le,w.acedAlert=ft,w.eventBus=z,w.registerConverters=ct,w.registerWorkers=pi,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});